xref: /PHP-5.5/ext/sqlite3/libsqlite/sqlite3.c (revision b5d1530e)
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.8.10.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 /************** Begin file sqliteInt.h ***************************************/
26 /*
27 ** 2001 September 15
28 **
29 ** The author disclaims copyright to this source code.  In place of
30 ** a legal notice, here is a blessing:
31 **
32 **    May you do good and not evil.
33 **    May you find forgiveness for yourself and forgive others.
34 **    May you share freely, never taking more than you give.
35 **
36 *************************************************************************
37 ** Internal interface definitions for SQLite.
38 **
39 */
40 #ifndef _SQLITEINT_H_
41 #define _SQLITEINT_H_
42 
43 /*
44 ** Include the header file used to customize the compiler options for MSVC.
45 ** This should be done first so that it can successfully prevent spurious
46 ** compiler warnings due to subsequent content in this file and other files
47 ** that are included by this file.
48 */
49 /************** Include msvc.h in the middle of sqliteInt.h ******************/
50 /************** Begin file msvc.h ********************************************/
51 /*
52 ** 2015 January 12
53 **
54 ** The author disclaims copyright to this source code.  In place of
55 ** a legal notice, here is a blessing:
56 **
57 **    May you do good and not evil.
58 **    May you find forgiveness for yourself and forgive others.
59 **    May you share freely, never taking more than you give.
60 **
61 ******************************************************************************
62 **
63 ** This file contains code that is specific to MSVC.
64 */
65 #ifndef _MSVC_H_
66 #define _MSVC_H_
67 
68 #if defined(_MSC_VER)
69 #pragma warning(disable : 4054)
70 #pragma warning(disable : 4055)
71 #pragma warning(disable : 4100)
72 #pragma warning(disable : 4127)
73 #pragma warning(disable : 4130)
74 #pragma warning(disable : 4152)
75 #pragma warning(disable : 4189)
76 #pragma warning(disable : 4206)
77 #pragma warning(disable : 4210)
78 #pragma warning(disable : 4232)
79 #pragma warning(disable : 4244)
80 #pragma warning(disable : 4305)
81 #pragma warning(disable : 4306)
82 #pragma warning(disable : 4702)
83 #pragma warning(disable : 4706)
84 #endif /* defined(_MSC_VER) */
85 
86 #endif /* _MSVC_H_ */
87 
88 /************** End of msvc.h ************************************************/
89 /************** Continuing where we left off in sqliteInt.h ******************/
90 
91 /*
92 ** Special setup for VxWorks
93 */
94 /************** Include vxworks.h in the middle of sqliteInt.h ***************/
95 /************** Begin file vxworks.h *****************************************/
96 /*
97 ** 2015-03-02
98 **
99 ** The author disclaims copyright to this source code.  In place of
100 ** a legal notice, here is a blessing:
101 **
102 **    May you do good and not evil.
103 **    May you find forgiveness for yourself and forgive others.
104 **    May you share freely, never taking more than you give.
105 **
106 ******************************************************************************
107 **
108 ** This file contains code that is specific to Wind River's VxWorks
109 */
110 #if defined(__RTP__) || defined(_WRS_KERNEL)
111 /* This is VxWorks.  Set up things specially for that OS
112 */
113 #include <vxWorks.h>
114 #include <pthread.h>  /* amalgamator: dontcache */
115 #define OS_VXWORKS 1
116 #define SQLITE_OS_OTHER 0
117 #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
118 #define SQLITE_OMIT_LOAD_EXTENSION 1
119 #define SQLITE_ENABLE_LOCKING_STYLE 0
120 #define HAVE_UTIME 1
121 #else
122 /* This is not VxWorks. */
123 #define OS_VXWORKS 0
124 #endif /* defined(_WRS_KERNEL) */
125 
126 /************** End of vxworks.h *********************************************/
127 /************** Continuing where we left off in sqliteInt.h ******************/
128 
129 /*
130 ** These #defines should enable >2GB file support on POSIX if the
131 ** underlying operating system supports it.  If the OS lacks
132 ** large file support, or if the OS is windows, these should be no-ops.
133 **
134 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
135 ** system #includes.  Hence, this block of code must be the very first
136 ** code in all source files.
137 **
138 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
139 ** on the compiler command line.  This is necessary if you are compiling
140 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
141 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
142 ** without this option, LFS is enable.  But LFS does not exist in the kernel
143 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
144 ** portability you should omit LFS.
145 **
146 ** The previous paragraph was written in 2005.  (This paragraph is written
147 ** on 2008-11-28.) These days, all Linux kernels support large files, so
148 ** you should probably leave LFS enabled.  But some embedded platforms might
149 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
150 **
151 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
152 */
153 #ifndef SQLITE_DISABLE_LFS
154 # define _LARGE_FILE       1
155 # ifndef _FILE_OFFSET_BITS
156 #   define _FILE_OFFSET_BITS 64
157 # endif
158 # define _LARGEFILE_SOURCE 1
159 #endif
160 
161 /* Needed for various definitions... */
162 #if defined(__GNUC__) && !defined(_GNU_SOURCE)
163 # define _GNU_SOURCE
164 #endif
165 
166 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
167 # define _BSD_SOURCE
168 #endif
169 
170 /*
171 ** For MinGW, check to see if we can include the header file containing its
172 ** version information, among other things.  Normally, this internal MinGW
173 ** header file would [only] be included automatically by other MinGW header
174 ** files; however, the contained version information is now required by this
175 ** header file to work around binary compatibility issues (see below) and
176 ** this is the only known way to reliably obtain it.  This entire #if block
177 ** would be completely unnecessary if there was any other way of detecting
178 ** MinGW via their preprocessor (e.g. if they customized their GCC to define
179 ** some MinGW-specific macros).  When compiling for MinGW, either the
180 ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
181 ** defined; otherwise, detection of conditions specific to MinGW will be
182 ** disabled.
183 */
184 #if defined(_HAVE_MINGW_H)
185 # include "mingw.h"
186 #elif defined(_HAVE__MINGW_H)
187 # include "_mingw.h"
188 #endif
189 
190 /*
191 ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
192 ** define is required to maintain binary compatibility with the MSVC runtime
193 ** library in use (e.g. for Windows XP).
194 */
195 #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
196     defined(_WIN32) && !defined(_WIN64) && \
197     defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
198     defined(__MSVCRT__)
199 # define _USE_32BIT_TIME_T
200 #endif
201 
202 /* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
203 ** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
204 ** MinGW.
205 */
206 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
207 /************** Begin file sqlite3.h *****************************************/
208 /*
209 ** 2001 September 15
210 **
211 ** The author disclaims copyright to this source code.  In place of
212 ** a legal notice, here is a blessing:
213 **
214 **    May you do good and not evil.
215 **    May you find forgiveness for yourself and forgive others.
216 **    May you share freely, never taking more than you give.
217 **
218 *************************************************************************
219 ** This header file defines the interface that the SQLite library
220 ** presents to client programs.  If a C-function, structure, datatype,
221 ** or constant definition does not appear in this file, then it is
222 ** not a published API of SQLite, is subject to change without
223 ** notice, and should not be referenced by programs that use SQLite.
224 **
225 ** Some of the definitions that are in this file are marked as
226 ** "experimental".  Experimental interfaces are normally new
227 ** features recently added to SQLite.  We do not anticipate changes
228 ** to experimental interfaces but reserve the right to make minor changes
229 ** if experience from use "in the wild" suggest such changes are prudent.
230 **
231 ** The official C-language API documentation for SQLite is derived
232 ** from comments in this file.  This file is the authoritative source
233 ** on how SQLite interfaces are suppose to operate.
234 **
235 ** The name of this file under configuration management is "sqlite.h.in".
236 ** The makefile makes some minor changes to this file (such as inserting
237 ** the version number) and changes its name to "sqlite3.h" as
238 ** part of the build process.
239 */
240 #ifndef _SQLITE3_H_
241 #define _SQLITE3_H_
242 #include <stdarg.h>     /* Needed for the definition of va_list */
243 
244 /*
245 ** Make sure we can call this stuff from C++.
246 */
247 #if 0
248 extern "C" {
249 #endif
250 
251 
252 /*
253 ** Provide the ability to override linkage features of the interface.
254 */
255 #ifndef SQLITE_EXTERN
256 # define SQLITE_EXTERN extern
257 #endif
258 #ifndef SQLITE_API
259 # define SQLITE_API
260 #endif
261 #ifndef SQLITE_CDECL
262 # define SQLITE_CDECL
263 #endif
264 #ifndef SQLITE_STDCALL
265 # define SQLITE_STDCALL
266 #endif
267 
268 /*
269 ** These no-op macros are used in front of interfaces to mark those
270 ** interfaces as either deprecated or experimental.  New applications
271 ** should not use deprecated interfaces - they are supported for backwards
272 ** compatibility only.  Application writers should be aware that
273 ** experimental interfaces are subject to change in point releases.
274 **
275 ** These macros used to resolve to various kinds of compiler magic that
276 ** would generate warning messages when they were used.  But that
277 ** compiler magic ended up generating such a flurry of bug reports
278 ** that we have taken it all out and gone back to using simple
279 ** noop macros.
280 */
281 #define SQLITE_DEPRECATED
282 #define SQLITE_EXPERIMENTAL
283 
284 /*
285 ** Ensure these symbols were not defined by some previous header file.
286 */
287 #ifdef SQLITE_VERSION
288 # undef SQLITE_VERSION
289 #endif
290 #ifdef SQLITE_VERSION_NUMBER
291 # undef SQLITE_VERSION_NUMBER
292 #endif
293 
294 /*
295 ** CAPI3REF: Compile-Time Library Version Numbers
296 **
297 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
298 ** evaluates to a string literal that is the SQLite version in the
299 ** format "X.Y.Z" where X is the major version number (always 3 for
300 ** SQLite3) and Y is the minor version number and Z is the release number.)^
301 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
302 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
303 ** numbers used in [SQLITE_VERSION].)^
304 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
305 ** be larger than the release from which it is derived.  Either Y will
306 ** be held constant and Z will be incremented or else Y will be incremented
307 ** and Z will be reset to zero.
308 **
309 ** Since version 3.6.18, SQLite source code has been stored in the
310 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
311 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
312 ** a string which identifies a particular check-in of SQLite
313 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
314 ** string contains the date and time of the check-in (UTC) and an SHA1
315 ** hash of the entire source tree.
316 **
317 ** See also: [sqlite3_libversion()],
318 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
319 ** [sqlite_version()] and [sqlite_source_id()].
320 */
321 #define SQLITE_VERSION        "3.8.10.2"
322 #define SQLITE_VERSION_NUMBER 3008010
323 #define SQLITE_SOURCE_ID      "2015-05-20 18:17:19 2ef4f3a5b1d1d0c4338f8243d40a2452cc1f7fe4"
324 
325 /*
326 ** CAPI3REF: Run-Time Library Version Numbers
327 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
328 **
329 ** These interfaces provide the same information as the [SQLITE_VERSION],
330 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
331 ** but are associated with the library instead of the header file.  ^(Cautious
332 ** programmers might include assert() statements in their application to
333 ** verify that values returned by these interfaces match the macros in
334 ** the header, and thus insure that the application is
335 ** compiled with matching library and header files.
336 **
337 ** <blockquote><pre>
338 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
339 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
340 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
341 ** </pre></blockquote>)^
342 **
343 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
344 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
345 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
346 ** function is provided for use in DLLs since DLL users usually do not have
347 ** direct access to string constants within the DLL.  ^The
348 ** sqlite3_libversion_number() function returns an integer equal to
349 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
350 ** a pointer to a string constant whose value is the same as the
351 ** [SQLITE_SOURCE_ID] C preprocessor macro.
352 **
353 ** See also: [sqlite_version()] and [sqlite_source_id()].
354 */
355 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
356 SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void);
357 SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void);
358 SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void);
359 
360 /*
361 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
362 **
363 ** ^The sqlite3_compileoption_used() function returns 0 or 1
364 ** indicating whether the specified option was defined at
365 ** compile time.  ^The SQLITE_ prefix may be omitted from the
366 ** option name passed to sqlite3_compileoption_used().
367 **
368 ** ^The sqlite3_compileoption_get() function allows iterating
369 ** over the list of options that were defined at compile time by
370 ** returning the N-th compile time option string.  ^If N is out of range,
371 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
372 ** prefix is omitted from any strings returned by
373 ** sqlite3_compileoption_get().
374 **
375 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
376 ** and sqlite3_compileoption_get() may be omitted by specifying the
377 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
378 **
379 ** See also: SQL functions [sqlite_compileoption_used()] and
380 ** [sqlite_compileoption_get()] and the [compile_options pragma].
381 */
382 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
383 SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName);
384 SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N);
385 #endif
386 
387 /*
388 ** CAPI3REF: Test To See If The Library Is Threadsafe
389 **
390 ** ^The sqlite3_threadsafe() function returns zero if and only if
391 ** SQLite was compiled with mutexing code omitted due to the
392 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
393 **
394 ** SQLite can be compiled with or without mutexes.  When
395 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
396 ** are enabled and SQLite is threadsafe.  When the
397 ** [SQLITE_THREADSAFE] macro is 0,
398 ** the mutexes are omitted.  Without the mutexes, it is not safe
399 ** to use SQLite concurrently from more than one thread.
400 **
401 ** Enabling mutexes incurs a measurable performance penalty.
402 ** So if speed is of utmost importance, it makes sense to disable
403 ** the mutexes.  But for maximum safety, mutexes should be enabled.
404 ** ^The default behavior is for mutexes to be enabled.
405 **
406 ** This interface can be used by an application to make sure that the
407 ** version of SQLite that it is linking against was compiled with
408 ** the desired setting of the [SQLITE_THREADSAFE] macro.
409 **
410 ** This interface only reports on the compile-time mutex setting
411 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
412 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
413 ** can be fully or partially disabled using a call to [sqlite3_config()]
414 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
415 ** or [SQLITE_CONFIG_SERIALIZED].  ^(The return value of the
416 ** sqlite3_threadsafe() function shows only the compile-time setting of
417 ** thread safety, not any run-time changes to that setting made by
418 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
419 ** is unchanged by calls to sqlite3_config().)^
420 **
421 ** See the [threading mode] documentation for additional information.
422 */
423 SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void);
424 
425 /*
426 ** CAPI3REF: Database Connection Handle
427 ** KEYWORDS: {database connection} {database connections}
428 **
429 ** Each open SQLite database is represented by a pointer to an instance of
430 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
431 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
432 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
433 ** and [sqlite3_close_v2()] are its destructors.  There are many other
434 ** interfaces (such as
435 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
436 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
437 ** sqlite3 object.
438 */
439 typedef struct sqlite3 sqlite3;
440 
441 /*
442 ** CAPI3REF: 64-Bit Integer Types
443 ** KEYWORDS: sqlite_int64 sqlite_uint64
444 **
445 ** Because there is no cross-platform way to specify 64-bit integer types
446 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
447 **
448 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
449 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
450 ** compatibility only.
451 **
452 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
453 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
454 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
455 ** between 0 and +18446744073709551615 inclusive.
456 */
457 #ifdef SQLITE_INT64_TYPE
458   typedef SQLITE_INT64_TYPE sqlite_int64;
459   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
460 #elif defined(_MSC_VER) || defined(__BORLANDC__)
461   typedef __int64 sqlite_int64;
462   typedef unsigned __int64 sqlite_uint64;
463 #else
464   typedef long long int sqlite_int64;
465   typedef unsigned long long int sqlite_uint64;
466 #endif
467 typedef sqlite_int64 sqlite3_int64;
468 typedef sqlite_uint64 sqlite3_uint64;
469 
470 /*
471 ** If compiling for a processor that lacks floating point support,
472 ** substitute integer for floating-point.
473 */
474 #ifdef SQLITE_OMIT_FLOATING_POINT
475 # define double sqlite3_int64
476 #endif
477 
478 /*
479 ** CAPI3REF: Closing A Database Connection
480 ** DESTRUCTOR: sqlite3
481 **
482 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
483 ** for the [sqlite3] object.
484 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
485 ** the [sqlite3] object is successfully destroyed and all associated
486 ** resources are deallocated.
487 **
488 ** ^If the database connection is associated with unfinalized prepared
489 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
490 ** will leave the database connection open and return [SQLITE_BUSY].
491 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
492 ** and/or unfinished sqlite3_backups, then the database connection becomes
493 ** an unusable "zombie" which will automatically be deallocated when the
494 ** last prepared statement is finalized or the last sqlite3_backup is
495 ** finished.  The sqlite3_close_v2() interface is intended for use with
496 ** host languages that are garbage collected, and where the order in which
497 ** destructors are called is arbitrary.
498 **
499 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
500 ** [sqlite3_blob_close | close] all [BLOB handles], and
501 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
502 ** with the [sqlite3] object prior to attempting to close the object.  ^If
503 ** sqlite3_close_v2() is called on a [database connection] that still has
504 ** outstanding [prepared statements], [BLOB handles], and/or
505 ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
506 ** of resources is deferred until all [prepared statements], [BLOB handles],
507 ** and [sqlite3_backup] objects are also destroyed.
508 **
509 ** ^If an [sqlite3] object is destroyed while a transaction is open,
510 ** the transaction is automatically rolled back.
511 **
512 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
513 ** must be either a NULL
514 ** pointer or an [sqlite3] object pointer obtained
515 ** from [sqlite3_open()], [sqlite3_open16()], or
516 ** [sqlite3_open_v2()], and not previously closed.
517 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
518 ** argument is a harmless no-op.
519 */
520 SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3*);
521 SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3*);
522 
523 /*
524 ** The type for a callback function.
525 ** This is legacy and deprecated.  It is included for historical
526 ** compatibility and is not documented.
527 */
528 typedef int (*sqlite3_callback)(void*,int,char**, char**);
529 
530 /*
531 ** CAPI3REF: One-Step Query Execution Interface
532 ** METHOD: sqlite3
533 **
534 ** The sqlite3_exec() interface is a convenience wrapper around
535 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
536 ** that allows an application to run multiple statements of SQL
537 ** without having to use a lot of C code.
538 **
539 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
540 ** semicolon-separate SQL statements passed into its 2nd argument,
541 ** in the context of the [database connection] passed in as its 1st
542 ** argument.  ^If the callback function of the 3rd argument to
543 ** sqlite3_exec() is not NULL, then it is invoked for each result row
544 ** coming out of the evaluated SQL statements.  ^The 4th argument to
545 ** sqlite3_exec() is relayed through to the 1st argument of each
546 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
547 ** is NULL, then no callback is ever invoked and result rows are
548 ** ignored.
549 **
550 ** ^If an error occurs while evaluating the SQL statements passed into
551 ** sqlite3_exec(), then execution of the current statement stops and
552 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
553 ** is not NULL then any error message is written into memory obtained
554 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
555 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
556 ** on error message strings returned through the 5th parameter of
557 ** of sqlite3_exec() after the error message string is no longer needed.
558 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
559 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
560 ** NULL before returning.
561 **
562 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
563 ** routine returns SQLITE_ABORT without invoking the callback again and
564 ** without running any subsequent SQL statements.
565 **
566 ** ^The 2nd argument to the sqlite3_exec() callback function is the
567 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
568 ** callback is an array of pointers to strings obtained as if from
569 ** [sqlite3_column_text()], one for each column.  ^If an element of a
570 ** result row is NULL then the corresponding string pointer for the
571 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
572 ** sqlite3_exec() callback is an array of pointers to strings where each
573 ** entry represents the name of corresponding result column as obtained
574 ** from [sqlite3_column_name()].
575 **
576 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
577 ** to an empty string, or a pointer that contains only whitespace and/or
578 ** SQL comments, then no SQL statements are evaluated and the database
579 ** is not changed.
580 **
581 ** Restrictions:
582 **
583 ** <ul>
584 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
585 **      is a valid and open [database connection].
586 ** <li> The application must not close the [database connection] specified by
587 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
588 ** <li> The application must not modify the SQL statement text passed into
589 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
590 ** </ul>
591 */
592 SQLITE_API int SQLITE_STDCALL sqlite3_exec(
593   sqlite3*,                                  /* An open database */
594   const char *sql,                           /* SQL to be evaluated */
595   int (*callback)(void*,int,char**,char**),  /* Callback function */
596   void *,                                    /* 1st argument to callback */
597   char **errmsg                              /* Error msg written here */
598 );
599 
600 /*
601 ** CAPI3REF: Result Codes
602 ** KEYWORDS: {result code definitions}
603 **
604 ** Many SQLite functions return an integer result code from the set shown
605 ** here in order to indicate success or failure.
606 **
607 ** New error codes may be added in future versions of SQLite.
608 **
609 ** See also: [extended result code definitions]
610 */
611 #define SQLITE_OK           0   /* Successful result */
612 /* beginning-of-error-codes */
613 #define SQLITE_ERROR        1   /* SQL error or missing database */
614 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
615 #define SQLITE_PERM         3   /* Access permission denied */
616 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
617 #define SQLITE_BUSY         5   /* The database file is locked */
618 #define SQLITE_LOCKED       6   /* A table in the database is locked */
619 #define SQLITE_NOMEM        7   /* A malloc() failed */
620 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
621 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
622 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
623 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
624 #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
625 #define SQLITE_FULL        13   /* Insertion failed because database is full */
626 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
627 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
628 #define SQLITE_EMPTY       16   /* Database is empty */
629 #define SQLITE_SCHEMA      17   /* The database schema changed */
630 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
631 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
632 #define SQLITE_MISMATCH    20   /* Data type mismatch */
633 #define SQLITE_MISUSE      21   /* Library used incorrectly */
634 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
635 #define SQLITE_AUTH        23   /* Authorization denied */
636 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
637 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
638 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
639 #define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
640 #define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
641 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
642 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
643 /* end-of-error-codes */
644 
645 /*
646 ** CAPI3REF: Extended Result Codes
647 ** KEYWORDS: {extended result code definitions}
648 **
649 ** In its default configuration, SQLite API routines return one of 30 integer
650 ** [result codes].  However, experience has shown that many of
651 ** these result codes are too coarse-grained.  They do not provide as
652 ** much information about problems as programmers might like.  In an effort to
653 ** address this, newer versions of SQLite (version 3.3.8 and later) include
654 ** support for additional result codes that provide more detailed information
655 ** about errors. These [extended result codes] are enabled or disabled
656 ** on a per database connection basis using the
657 ** [sqlite3_extended_result_codes()] API.  Or, the extended code for
658 ** the most recent error can be obtained using
659 ** [sqlite3_extended_errcode()].
660 */
661 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
662 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
663 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
664 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
665 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
666 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
667 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
668 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
669 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
670 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
671 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
672 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
673 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
674 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
675 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
676 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
677 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
678 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
679 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
680 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
681 #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
682 #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
683 #define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
684 #define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
685 #define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
686 #define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
687 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
688 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
689 #define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
690 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
691 #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
692 #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
693 #define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
694 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
695 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
696 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
697 #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
698 #define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
699 #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
700 #define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
701 #define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
702 #define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
703 #define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
704 #define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
705 #define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
706 #define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
707 #define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
708 #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
709 #define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
710 #define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
711 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
712 #define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
713 #define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
714 
715 /*
716 ** CAPI3REF: Flags For File Open Operations
717 **
718 ** These bit values are intended for use in the
719 ** 3rd parameter to the [sqlite3_open_v2()] interface and
720 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
721 */
722 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
723 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
724 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
725 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
726 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
727 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
728 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
729 #define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
730 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
731 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
732 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
733 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
734 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
735 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
736 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
737 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
738 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
739 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
740 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
741 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
742 
743 /* Reserved:                         0x00F00000 */
744 
745 /*
746 ** CAPI3REF: Device Characteristics
747 **
748 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
749 ** object returns an integer which is a vector of these
750 ** bit values expressing I/O characteristics of the mass storage
751 ** device that holds the file that the [sqlite3_io_methods]
752 ** refers to.
753 **
754 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
755 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
756 ** mean that writes of blocks that are nnn bytes in size and
757 ** are aligned to an address which is an integer multiple of
758 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
759 ** that when data is appended to a file, the data is appended
760 ** first then the size of the file is extended, never the other
761 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
762 ** information is written to disk in the same order as calls
763 ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
764 ** after reboot following a crash or power loss, the only bytes in a
765 ** file that were written at the application level might have changed
766 ** and that adjacent bytes, even bytes within the same sector are
767 ** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
768 ** flag indicate that a file cannot be deleted when open.  The
769 ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
770 ** read-only media and cannot be changed even by processes with
771 ** elevated privileges.
772 */
773 #define SQLITE_IOCAP_ATOMIC                 0x00000001
774 #define SQLITE_IOCAP_ATOMIC512              0x00000002
775 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
776 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
777 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
778 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
779 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
780 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
781 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
782 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
783 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
784 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
785 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
786 #define SQLITE_IOCAP_IMMUTABLE              0x00002000
787 
788 /*
789 ** CAPI3REF: File Locking Levels
790 **
791 ** SQLite uses one of these integer values as the second
792 ** argument to calls it makes to the xLock() and xUnlock() methods
793 ** of an [sqlite3_io_methods] object.
794 */
795 #define SQLITE_LOCK_NONE          0
796 #define SQLITE_LOCK_SHARED        1
797 #define SQLITE_LOCK_RESERVED      2
798 #define SQLITE_LOCK_PENDING       3
799 #define SQLITE_LOCK_EXCLUSIVE     4
800 
801 /*
802 ** CAPI3REF: Synchronization Type Flags
803 **
804 ** When SQLite invokes the xSync() method of an
805 ** [sqlite3_io_methods] object it uses a combination of
806 ** these integer values as the second argument.
807 **
808 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
809 ** sync operation only needs to flush data to mass storage.  Inode
810 ** information need not be flushed. If the lower four bits of the flag
811 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
812 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
813 ** to use Mac OS X style fullsync instead of fsync().
814 **
815 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
816 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
817 ** settings.  The [synchronous pragma] determines when calls to the
818 ** xSync VFS method occur and applies uniformly across all platforms.
819 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
820 ** energetic or rigorous or forceful the sync operations are and
821 ** only make a difference on Mac OSX for the default SQLite code.
822 ** (Third-party VFS implementations might also make the distinction
823 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
824 ** operating systems natively supported by SQLite, only Mac OSX
825 ** cares about the difference.)
826 */
827 #define SQLITE_SYNC_NORMAL        0x00002
828 #define SQLITE_SYNC_FULL          0x00003
829 #define SQLITE_SYNC_DATAONLY      0x00010
830 
831 /*
832 ** CAPI3REF: OS Interface Open File Handle
833 **
834 ** An [sqlite3_file] object represents an open file in the
835 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
836 ** implementations will
837 ** want to subclass this object by appending additional fields
838 ** for their own use.  The pMethods entry is a pointer to an
839 ** [sqlite3_io_methods] object that defines methods for performing
840 ** I/O operations on the open file.
841 */
842 typedef struct sqlite3_file sqlite3_file;
843 struct sqlite3_file {
844   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
845 };
846 
847 /*
848 ** CAPI3REF: OS Interface File Virtual Methods Object
849 **
850 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
851 ** [sqlite3_file] object (or, more commonly, a subclass of the
852 ** [sqlite3_file] object) with a pointer to an instance of this object.
853 ** This object defines the methods used to perform various operations
854 ** against the open file represented by the [sqlite3_file] object.
855 **
856 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
857 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
858 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
859 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
860 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
861 ** to NULL.
862 **
863 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
864 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
865 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
866 ** flag may be ORed in to indicate that only the data of the file
867 ** and not its inode needs to be synced.
868 **
869 ** The integer values to xLock() and xUnlock() are one of
870 ** <ul>
871 ** <li> [SQLITE_LOCK_NONE],
872 ** <li> [SQLITE_LOCK_SHARED],
873 ** <li> [SQLITE_LOCK_RESERVED],
874 ** <li> [SQLITE_LOCK_PENDING], or
875 ** <li> [SQLITE_LOCK_EXCLUSIVE].
876 ** </ul>
877 ** xLock() increases the lock. xUnlock() decreases the lock.
878 ** The xCheckReservedLock() method checks whether any database connection,
879 ** either in this process or in some other process, is holding a RESERVED,
880 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
881 ** if such a lock exists and false otherwise.
882 **
883 ** The xFileControl() method is a generic interface that allows custom
884 ** VFS implementations to directly control an open file using the
885 ** [sqlite3_file_control()] interface.  The second "op" argument is an
886 ** integer opcode.  The third argument is a generic pointer intended to
887 ** point to a structure that may contain arguments or space in which to
888 ** write return values.  Potential uses for xFileControl() might be
889 ** functions to enable blocking locks with timeouts, to change the
890 ** locking strategy (for example to use dot-file locks), to inquire
891 ** about the status of a lock, or to break stale locks.  The SQLite
892 ** core reserves all opcodes less than 100 for its own use.
893 ** A [file control opcodes | list of opcodes] less than 100 is available.
894 ** Applications that define a custom xFileControl method should use opcodes
895 ** greater than 100 to avoid conflicts.  VFS implementations should
896 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
897 ** recognize.
898 **
899 ** The xSectorSize() method returns the sector size of the
900 ** device that underlies the file.  The sector size is the
901 ** minimum write that can be performed without disturbing
902 ** other bytes in the file.  The xDeviceCharacteristics()
903 ** method returns a bit vector describing behaviors of the
904 ** underlying device:
905 **
906 ** <ul>
907 ** <li> [SQLITE_IOCAP_ATOMIC]
908 ** <li> [SQLITE_IOCAP_ATOMIC512]
909 ** <li> [SQLITE_IOCAP_ATOMIC1K]
910 ** <li> [SQLITE_IOCAP_ATOMIC2K]
911 ** <li> [SQLITE_IOCAP_ATOMIC4K]
912 ** <li> [SQLITE_IOCAP_ATOMIC8K]
913 ** <li> [SQLITE_IOCAP_ATOMIC16K]
914 ** <li> [SQLITE_IOCAP_ATOMIC32K]
915 ** <li> [SQLITE_IOCAP_ATOMIC64K]
916 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
917 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
918 ** </ul>
919 **
920 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
921 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
922 ** mean that writes of blocks that are nnn bytes in size and
923 ** are aligned to an address which is an integer multiple of
924 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
925 ** that when data is appended to a file, the data is appended
926 ** first then the size of the file is extended, never the other
927 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
928 ** information is written to disk in the same order as calls
929 ** to xWrite().
930 **
931 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
932 ** in the unread portions of the buffer with zeros.  A VFS that
933 ** fails to zero-fill short reads might seem to work.  However,
934 ** failure to zero-fill short reads will eventually lead to
935 ** database corruption.
936 */
937 typedef struct sqlite3_io_methods sqlite3_io_methods;
938 struct sqlite3_io_methods {
939   int iVersion;
940   int (*xClose)(sqlite3_file*);
941   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
942   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
943   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
944   int (*xSync)(sqlite3_file*, int flags);
945   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
946   int (*xLock)(sqlite3_file*, int);
947   int (*xUnlock)(sqlite3_file*, int);
948   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
949   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
950   int (*xSectorSize)(sqlite3_file*);
951   int (*xDeviceCharacteristics)(sqlite3_file*);
952   /* Methods above are valid for version 1 */
953   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
954   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
955   void (*xShmBarrier)(sqlite3_file*);
956   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
957   /* Methods above are valid for version 2 */
958   int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
959   int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
960   /* Methods above are valid for version 3 */
961   /* Additional methods may be added in future releases */
962 };
963 
964 /*
965 ** CAPI3REF: Standard File Control Opcodes
966 ** KEYWORDS: {file control opcodes} {file control opcode}
967 **
968 ** These integer constants are opcodes for the xFileControl method
969 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
970 ** interface.
971 **
972 ** <ul>
973 ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
974 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
975 ** opcode causes the xFileControl method to write the current state of
976 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
977 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
978 ** into an integer that the pArg argument points to. This capability
979 ** is used during testing and is only available when the SQLITE_TEST
980 ** compile-time option is used.
981 **
982 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
983 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
984 ** layer a hint of how large the database file will grow to be during the
985 ** current transaction.  This hint is not guaranteed to be accurate but it
986 ** is often close.  The underlying VFS might choose to preallocate database
987 ** file space based on this hint in order to help writes to the database
988 ** file run faster.
989 **
990 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
991 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
992 ** extends and truncates the database file in chunks of a size specified
993 ** by the user. The fourth argument to [sqlite3_file_control()] should
994 ** point to an integer (type int) containing the new chunk-size to use
995 ** for the nominated database. Allocating database file space in large
996 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
997 ** improve performance on some systems.
998 **
999 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1000 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1001 ** to the [sqlite3_file] object associated with a particular database
1002 ** connection.  See the [sqlite3_file_control()] documentation for
1003 ** additional information.
1004 **
1005 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1006 ** No longer in use.
1007 **
1008 ** <li>[[SQLITE_FCNTL_SYNC]]
1009 ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1010 ** sent to the VFS immediately before the xSync method is invoked on a
1011 ** database file descriptor. Or, if the xSync method is not invoked
1012 ** because the user has configured SQLite with
1013 ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1014 ** of the xSync method. In most cases, the pointer argument passed with
1015 ** this file-control is NULL. However, if the database file is being synced
1016 ** as part of a multi-database commit, the argument points to a nul-terminated
1017 ** string containing the transactions master-journal file name. VFSes that
1018 ** do not need this signal should silently ignore this opcode. Applications
1019 ** should not call [sqlite3_file_control()] with this opcode as doing so may
1020 ** disrupt the operation of the specialized VFSes that do require it.
1021 **
1022 ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1023 ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1024 ** and sent to the VFS after a transaction has been committed immediately
1025 ** but before the database is unlocked. VFSes that do not need this signal
1026 ** should silently ignore this opcode. Applications should not call
1027 ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1028 ** operation of the specialized VFSes that do require it.
1029 **
1030 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1031 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1032 ** retry counts and intervals for certain disk I/O operations for the
1033 ** windows [VFS] in order to provide robustness in the presence of
1034 ** anti-virus programs.  By default, the windows VFS will retry file read,
1035 ** file write, and file delete operations up to 10 times, with a delay
1036 ** of 25 milliseconds before the first retry and with the delay increasing
1037 ** by an additional 25 milliseconds with each subsequent retry.  This
1038 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
1039 ** to be adjusted.  The values are changed for all database connections
1040 ** within the same process.  The argument is a pointer to an array of two
1041 ** integers where the first integer i the new retry count and the second
1042 ** integer is the delay.  If either integer is negative, then the setting
1043 ** is not changed but instead the prior value of that setting is written
1044 ** into the array entry, allowing the current retry settings to be
1045 ** interrogated.  The zDbName parameter is ignored.
1046 **
1047 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1048 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1049 ** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
1050 ** write ahead log and shared memory files used for transaction control
1051 ** are automatically deleted when the latest connection to the database
1052 ** closes.  Setting persistent WAL mode causes those files to persist after
1053 ** close.  Persisting the files is useful when other processes that do not
1054 ** have write permission on the directory containing the database file want
1055 ** to read the database file, as the WAL and shared memory files must exist
1056 ** in order for the database to be readable.  The fourth parameter to
1057 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1058 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1059 ** WAL mode.  If the integer is -1, then it is overwritten with the current
1060 ** WAL persistence setting.
1061 **
1062 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1063 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1064 ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1065 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1066 ** xDeviceCharacteristics methods. The fourth parameter to
1067 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1068 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1069 ** mode.  If the integer is -1, then it is overwritten with the current
1070 ** zero-damage mode setting.
1071 **
1072 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
1073 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1074 ** a write transaction to indicate that, unless it is rolled back for some
1075 ** reason, the entire database file will be overwritten by the current
1076 ** transaction. This is used by VACUUM operations.
1077 **
1078 ** <li>[[SQLITE_FCNTL_VFSNAME]]
1079 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1080 ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1081 ** final bottom-level VFS are written into memory obtained from
1082 ** [sqlite3_malloc()] and the result is stored in the char* variable
1083 ** that the fourth parameter of [sqlite3_file_control()] points to.
1084 ** The caller is responsible for freeing the memory when done.  As with
1085 ** all file-control actions, there is no guarantee that this will actually
1086 ** do anything.  Callers should initialize the char* variable to a NULL
1087 ** pointer in case this file-control is not implemented.  This file-control
1088 ** is intended for diagnostic use only.
1089 **
1090 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1091 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1092 ** file control is sent to the open [sqlite3_file] object corresponding
1093 ** to the database file to which the pragma statement refers. ^The argument
1094 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1095 ** pointers to strings (char**) in which the second element of the array
1096 ** is the name of the pragma and the third element is the argument to the
1097 ** pragma or NULL if the pragma has no argument.  ^The handler for an
1098 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1099 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1100 ** or the equivalent and that string will become the result of the pragma or
1101 ** the error message if the pragma fails. ^If the
1102 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1103 ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1104 ** file control returns [SQLITE_OK], then the parser assumes that the
1105 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1106 ** prepared statement if result string is NULL, or that returns a copy
1107 ** of the result string if the string is non-NULL.
1108 ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1109 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1110 ** that the VFS encountered an error while handling the [PRAGMA] and the
1111 ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1112 ** file control occurs at the beginning of pragma statement analysis and so
1113 ** it is able to override built-in [PRAGMA] statements.
1114 **
1115 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1116 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
1117 ** file-control may be invoked by SQLite on the database file handle
1118 ** shortly after it is opened in order to provide a custom VFS with access
1119 ** to the connections busy-handler callback. The argument is of type (void **)
1120 ** - an array of two (void *) values. The first (void *) actually points
1121 ** to a function of type (int (*)(void *)). In order to invoke the connections
1122 ** busy-handler, this function should be invoked with the second (void *) in
1123 ** the array as the only argument. If it returns non-zero, then the operation
1124 ** should be retried. If it returns zero, the custom VFS should abandon the
1125 ** current operation.
1126 **
1127 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1128 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1129 ** to have SQLite generate a
1130 ** temporary filename using the same algorithm that is followed to generate
1131 ** temporary filenames for TEMP tables and other internal uses.  The
1132 ** argument should be a char** which will be filled with the filename
1133 ** written into memory obtained from [sqlite3_malloc()].  The caller should
1134 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
1135 **
1136 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1137 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1138 ** maximum number of bytes that will be used for memory-mapped I/O.
1139 ** The argument is a pointer to a value of type sqlite3_int64 that
1140 ** is an advisory maximum number of bytes in the file to memory map.  The
1141 ** pointer is overwritten with the old value.  The limit is not changed if
1142 ** the value originally pointed to is negative, and so the current limit
1143 ** can be queried by passing in a pointer to a negative number.  This
1144 ** file-control is used internally to implement [PRAGMA mmap_size].
1145 **
1146 ** <li>[[SQLITE_FCNTL_TRACE]]
1147 ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1148 ** to the VFS about what the higher layers of the SQLite stack are doing.
1149 ** This file control is used by some VFS activity tracing [shims].
1150 ** The argument is a zero-terminated string.  Higher layers in the
1151 ** SQLite stack may generate instances of this file control if
1152 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1153 **
1154 ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1155 ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1156 ** pointer to an integer and it writes a boolean into that integer depending
1157 ** on whether or not the file has been renamed, moved, or deleted since it
1158 ** was first opened.
1159 **
1160 ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1161 ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This
1162 ** opcode causes the xFileControl method to swap the file handle with the one
1163 ** pointed to by the pArg argument.  This capability is used during testing
1164 ** and only needs to be supported when SQLITE_TEST is defined.
1165 **
1166 ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
1167 ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
1168 ** be advantageous to block on the next WAL lock if the lock is not immediately
1169 ** available.  The WAL subsystem issues this signal during rare
1170 ** circumstances in order to fix a problem with priority inversion.
1171 ** Applications should <em>not</em> use this file-control.
1172 **
1173 ** </ul>
1174 */
1175 #define SQLITE_FCNTL_LOCKSTATE               1
1176 #define SQLITE_FCNTL_GET_LOCKPROXYFILE       2
1177 #define SQLITE_FCNTL_SET_LOCKPROXYFILE       3
1178 #define SQLITE_FCNTL_LAST_ERRNO              4
1179 #define SQLITE_FCNTL_SIZE_HINT               5
1180 #define SQLITE_FCNTL_CHUNK_SIZE              6
1181 #define SQLITE_FCNTL_FILE_POINTER            7
1182 #define SQLITE_FCNTL_SYNC_OMITTED            8
1183 #define SQLITE_FCNTL_WIN32_AV_RETRY          9
1184 #define SQLITE_FCNTL_PERSIST_WAL            10
1185 #define SQLITE_FCNTL_OVERWRITE              11
1186 #define SQLITE_FCNTL_VFSNAME                12
1187 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1188 #define SQLITE_FCNTL_PRAGMA                 14
1189 #define SQLITE_FCNTL_BUSYHANDLER            15
1190 #define SQLITE_FCNTL_TEMPFILENAME           16
1191 #define SQLITE_FCNTL_MMAP_SIZE              18
1192 #define SQLITE_FCNTL_TRACE                  19
1193 #define SQLITE_FCNTL_HAS_MOVED              20
1194 #define SQLITE_FCNTL_SYNC                   21
1195 #define SQLITE_FCNTL_COMMIT_PHASETWO        22
1196 #define SQLITE_FCNTL_WIN32_SET_HANDLE       23
1197 #define SQLITE_FCNTL_WAL_BLOCK              24
1198 
1199 /* deprecated names */
1200 #define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
1201 #define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE
1202 #define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO
1203 
1204 
1205 /*
1206 ** CAPI3REF: Mutex Handle
1207 **
1208 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1209 ** abstract type for a mutex object.  The SQLite core never looks
1210 ** at the internal representation of an [sqlite3_mutex].  It only
1211 ** deals with pointers to the [sqlite3_mutex] object.
1212 **
1213 ** Mutexes are created using [sqlite3_mutex_alloc()].
1214 */
1215 typedef struct sqlite3_mutex sqlite3_mutex;
1216 
1217 /*
1218 ** CAPI3REF: OS Interface Object
1219 **
1220 ** An instance of the sqlite3_vfs object defines the interface between
1221 ** the SQLite core and the underlying operating system.  The "vfs"
1222 ** in the name of the object stands for "virtual file system".  See
1223 ** the [VFS | VFS documentation] for further information.
1224 **
1225 ** The value of the iVersion field is initially 1 but may be larger in
1226 ** future versions of SQLite.  Additional fields may be appended to this
1227 ** object when the iVersion value is increased.  Note that the structure
1228 ** of the sqlite3_vfs object changes in the transaction between
1229 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1230 ** modified.
1231 **
1232 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1233 ** structure used by this VFS.  mxPathname is the maximum length of
1234 ** a pathname in this VFS.
1235 **
1236 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1237 ** the pNext pointer.  The [sqlite3_vfs_register()]
1238 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1239 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1240 ** searches the list.  Neither the application code nor the VFS
1241 ** implementation should use the pNext pointer.
1242 **
1243 ** The pNext field is the only field in the sqlite3_vfs
1244 ** structure that SQLite will ever modify.  SQLite will only access
1245 ** or modify this field while holding a particular static mutex.
1246 ** The application should never modify anything within the sqlite3_vfs
1247 ** object once the object has been registered.
1248 **
1249 ** The zName field holds the name of the VFS module.  The name must
1250 ** be unique across all VFS modules.
1251 **
1252 ** [[sqlite3_vfs.xOpen]]
1253 ** ^SQLite guarantees that the zFilename parameter to xOpen
1254 ** is either a NULL pointer or string obtained
1255 ** from xFullPathname() with an optional suffix added.
1256 ** ^If a suffix is added to the zFilename parameter, it will
1257 ** consist of a single "-" character followed by no more than
1258 ** 11 alphanumeric and/or "-" characters.
1259 ** ^SQLite further guarantees that
1260 ** the string will be valid and unchanged until xClose() is
1261 ** called. Because of the previous sentence,
1262 ** the [sqlite3_file] can safely store a pointer to the
1263 ** filename if it needs to remember the filename for some reason.
1264 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1265 ** must invent its own temporary name for the file.  ^Whenever the
1266 ** xFilename parameter is NULL it will also be the case that the
1267 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1268 **
1269 ** The flags argument to xOpen() includes all bits set in
1270 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1271 ** or [sqlite3_open16()] is used, then flags includes at least
1272 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1273 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1274 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1275 **
1276 ** ^(SQLite will also add one of the following flags to the xOpen()
1277 ** call, depending on the object being opened:
1278 **
1279 ** <ul>
1280 ** <li>  [SQLITE_OPEN_MAIN_DB]
1281 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1282 ** <li>  [SQLITE_OPEN_TEMP_DB]
1283 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1284 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1285 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1286 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1287 ** <li>  [SQLITE_OPEN_WAL]
1288 ** </ul>)^
1289 **
1290 ** The file I/O implementation can use the object type flags to
1291 ** change the way it deals with files.  For example, an application
1292 ** that does not care about crash recovery or rollback might make
1293 ** the open of a journal file a no-op.  Writes to this journal would
1294 ** also be no-ops, and any attempt to read the journal would return
1295 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1296 ** file will be doing page-aligned sector reads and writes in a random
1297 ** order and set up its I/O subsystem accordingly.
1298 **
1299 ** SQLite might also add one of the following flags to the xOpen method:
1300 **
1301 ** <ul>
1302 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1303 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1304 ** </ul>
1305 **
1306 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1307 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1308 ** will be set for TEMP databases and their journals, transient
1309 ** databases, and subjournals.
1310 **
1311 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1312 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1313 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1314 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1315 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1316 ** be created, and that it is an error if it already exists.
1317 ** It is <i>not</i> used to indicate the file should be opened
1318 ** for exclusive access.
1319 **
1320 ** ^At least szOsFile bytes of memory are allocated by SQLite
1321 ** to hold the  [sqlite3_file] structure passed as the third
1322 ** argument to xOpen.  The xOpen method does not have to
1323 ** allocate the structure; it should just fill it in.  Note that
1324 ** the xOpen method must set the sqlite3_file.pMethods to either
1325 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1326 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1327 ** element will be valid after xOpen returns regardless of the success
1328 ** or failure of the xOpen call.
1329 **
1330 ** [[sqlite3_vfs.xAccess]]
1331 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1332 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1333 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1334 ** to test whether a file is at least readable.   The file can be a
1335 ** directory.
1336 **
1337 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1338 ** output buffer xFullPathname.  The exact size of the output buffer
1339 ** is also passed as a parameter to both  methods. If the output buffer
1340 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1341 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1342 ** to prevent this by setting mxPathname to a sufficiently large value.
1343 **
1344 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1345 ** interfaces are not strictly a part of the filesystem, but they are
1346 ** included in the VFS structure for completeness.
1347 ** The xRandomness() function attempts to return nBytes bytes
1348 ** of good-quality randomness into zOut.  The return value is
1349 ** the actual number of bytes of randomness obtained.
1350 ** The xSleep() method causes the calling thread to sleep for at
1351 ** least the number of microseconds given.  ^The xCurrentTime()
1352 ** method returns a Julian Day Number for the current date and time as
1353 ** a floating point value.
1354 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1355 ** Day Number multiplied by 86400000 (the number of milliseconds in
1356 ** a 24-hour day).
1357 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1358 ** date and time if that method is available (if iVersion is 2 or
1359 ** greater and the function pointer is not NULL) and will fall back
1360 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1361 **
1362 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1363 ** are not used by the SQLite core.  These optional interfaces are provided
1364 ** by some VFSes to facilitate testing of the VFS code. By overriding
1365 ** system calls with functions under its control, a test program can
1366 ** simulate faults and error conditions that would otherwise be difficult
1367 ** or impossible to induce.  The set of system calls that can be overridden
1368 ** varies from one VFS to another, and from one version of the same VFS to the
1369 ** next.  Applications that use these interfaces must be prepared for any
1370 ** or all of these interfaces to be NULL or for their behavior to change
1371 ** from one release to the next.  Applications must not attempt to access
1372 ** any of these methods if the iVersion of the VFS is less than 3.
1373 */
1374 typedef struct sqlite3_vfs sqlite3_vfs;
1375 typedef void (*sqlite3_syscall_ptr)(void);
1376 struct sqlite3_vfs {
1377   int iVersion;            /* Structure version number (currently 3) */
1378   int szOsFile;            /* Size of subclassed sqlite3_file */
1379   int mxPathname;          /* Maximum file pathname length */
1380   sqlite3_vfs *pNext;      /* Next registered VFS */
1381   const char *zName;       /* Name of this virtual file system */
1382   void *pAppData;          /* Pointer to application-specific data */
1383   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1384                int flags, int *pOutFlags);
1385   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1386   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1387   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1388   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1389   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1390   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1391   void (*xDlClose)(sqlite3_vfs*, void*);
1392   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1393   int (*xSleep)(sqlite3_vfs*, int microseconds);
1394   int (*xCurrentTime)(sqlite3_vfs*, double*);
1395   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1396   /*
1397   ** The methods above are in version 1 of the sqlite_vfs object
1398   ** definition.  Those that follow are added in version 2 or later
1399   */
1400   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1401   /*
1402   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1403   ** Those below are for version 3 and greater.
1404   */
1405   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1406   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1407   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1408   /*
1409   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1410   ** New fields may be appended in figure versions.  The iVersion
1411   ** value will increment whenever this happens.
1412   */
1413 };
1414 
1415 /*
1416 ** CAPI3REF: Flags for the xAccess VFS method
1417 **
1418 ** These integer constants can be used as the third parameter to
1419 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1420 ** what kind of permissions the xAccess method is looking for.
1421 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1422 ** simply checks whether the file exists.
1423 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1424 ** checks whether the named directory is both readable and writable
1425 ** (in other words, if files can be added, removed, and renamed within
1426 ** the directory).
1427 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1428 ** [temp_store_directory pragma], though this could change in a future
1429 ** release of SQLite.
1430 ** With SQLITE_ACCESS_READ, the xAccess method
1431 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1432 ** currently unused, though it might be used in a future release of
1433 ** SQLite.
1434 */
1435 #define SQLITE_ACCESS_EXISTS    0
1436 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1437 #define SQLITE_ACCESS_READ      2   /* Unused */
1438 
1439 /*
1440 ** CAPI3REF: Flags for the xShmLock VFS method
1441 **
1442 ** These integer constants define the various locking operations
1443 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1444 ** following are the only legal combinations of flags to the
1445 ** xShmLock method:
1446 **
1447 ** <ul>
1448 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1449 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1450 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1451 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1452 ** </ul>
1453 **
1454 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1455 ** was given on the corresponding lock.
1456 **
1457 ** The xShmLock method can transition between unlocked and SHARED or
1458 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1459 ** and EXCLUSIVE.
1460 */
1461 #define SQLITE_SHM_UNLOCK       1
1462 #define SQLITE_SHM_LOCK         2
1463 #define SQLITE_SHM_SHARED       4
1464 #define SQLITE_SHM_EXCLUSIVE    8
1465 
1466 /*
1467 ** CAPI3REF: Maximum xShmLock index
1468 **
1469 ** The xShmLock method on [sqlite3_io_methods] may use values
1470 ** between 0 and this upper bound as its "offset" argument.
1471 ** The SQLite core will never attempt to acquire or release a
1472 ** lock outside of this range
1473 */
1474 #define SQLITE_SHM_NLOCK        8
1475 
1476 
1477 /*
1478 ** CAPI3REF: Initialize The SQLite Library
1479 **
1480 ** ^The sqlite3_initialize() routine initializes the
1481 ** SQLite library.  ^The sqlite3_shutdown() routine
1482 ** deallocates any resources that were allocated by sqlite3_initialize().
1483 ** These routines are designed to aid in process initialization and
1484 ** shutdown on embedded systems.  Workstation applications using
1485 ** SQLite normally do not need to invoke either of these routines.
1486 **
1487 ** A call to sqlite3_initialize() is an "effective" call if it is
1488 ** the first time sqlite3_initialize() is invoked during the lifetime of
1489 ** the process, or if it is the first time sqlite3_initialize() is invoked
1490 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1491 ** of sqlite3_initialize() does any initialization.  All other calls
1492 ** are harmless no-ops.)^
1493 **
1494 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1495 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1496 ** an effective call to sqlite3_shutdown() does any deinitialization.
1497 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1498 **
1499 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1500 ** is not.  The sqlite3_shutdown() interface must only be called from a
1501 ** single thread.  All open [database connections] must be closed and all
1502 ** other SQLite resources must be deallocated prior to invoking
1503 ** sqlite3_shutdown().
1504 **
1505 ** Among other things, ^sqlite3_initialize() will invoke
1506 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1507 ** will invoke sqlite3_os_end().
1508 **
1509 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1510 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1511 ** the library (perhaps it is unable to allocate a needed resource such
1512 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1513 **
1514 ** ^The sqlite3_initialize() routine is called internally by many other
1515 ** SQLite interfaces so that an application usually does not need to
1516 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1517 ** calls sqlite3_initialize() so the SQLite library will be automatically
1518 ** initialized when [sqlite3_open()] is called if it has not be initialized
1519 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1520 ** compile-time option, then the automatic calls to sqlite3_initialize()
1521 ** are omitted and the application must call sqlite3_initialize() directly
1522 ** prior to using any other SQLite interface.  For maximum portability,
1523 ** it is recommended that applications always invoke sqlite3_initialize()
1524 ** directly prior to using any other SQLite interface.  Future releases
1525 ** of SQLite may require this.  In other words, the behavior exhibited
1526 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1527 ** default behavior in some future release of SQLite.
1528 **
1529 ** The sqlite3_os_init() routine does operating-system specific
1530 ** initialization of the SQLite library.  The sqlite3_os_end()
1531 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1532 ** performed by these routines include allocation or deallocation
1533 ** of static resources, initialization of global variables,
1534 ** setting up a default [sqlite3_vfs] module, or setting up
1535 ** a default configuration using [sqlite3_config()].
1536 **
1537 ** The application should never invoke either sqlite3_os_init()
1538 ** or sqlite3_os_end() directly.  The application should only invoke
1539 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1540 ** interface is called automatically by sqlite3_initialize() and
1541 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1542 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1543 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1544 ** When [custom builds | built for other platforms]
1545 ** (using the [SQLITE_OS_OTHER=1] compile-time
1546 ** option) the application must supply a suitable implementation for
1547 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1548 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1549 ** must return [SQLITE_OK] on success and some other [error code] upon
1550 ** failure.
1551 */
1552 SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void);
1553 SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void);
1554 SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void);
1555 SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void);
1556 
1557 /*
1558 ** CAPI3REF: Configuring The SQLite Library
1559 **
1560 ** The sqlite3_config() interface is used to make global configuration
1561 ** changes to SQLite in order to tune SQLite to the specific needs of
1562 ** the application.  The default configuration is recommended for most
1563 ** applications and so this routine is usually not necessary.  It is
1564 ** provided to support rare applications with unusual needs.
1565 **
1566 ** The sqlite3_config() interface is not threadsafe.  The application
1567 ** must insure that no other SQLite interfaces are invoked by other
1568 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1569 ** may only be invoked prior to library initialization using
1570 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1571 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1572 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1573 ** Note, however, that ^sqlite3_config() can be called as part of the
1574 ** implementation of an application-defined [sqlite3_os_init()].
1575 **
1576 ** The first argument to sqlite3_config() is an integer
1577 ** [configuration option] that determines
1578 ** what property of SQLite is to be configured.  Subsequent arguments
1579 ** vary depending on the [configuration option]
1580 ** in the first argument.
1581 **
1582 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1583 ** ^If the option is unknown or SQLite is unable to set the option
1584 ** then this routine returns a non-zero [error code].
1585 */
1586 SQLITE_API int SQLITE_CDECL sqlite3_config(int, ...);
1587 
1588 /*
1589 ** CAPI3REF: Configure database connections
1590 ** METHOD: sqlite3
1591 **
1592 ** The sqlite3_db_config() interface is used to make configuration
1593 ** changes to a [database connection].  The interface is similar to
1594 ** [sqlite3_config()] except that the changes apply to a single
1595 ** [database connection] (specified in the first argument).
1596 **
1597 ** The second argument to sqlite3_db_config(D,V,...)  is the
1598 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1599 ** that indicates what aspect of the [database connection] is being configured.
1600 ** Subsequent arguments vary depending on the configuration verb.
1601 **
1602 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1603 ** the call is considered successful.
1604 */
1605 SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3*, int op, ...);
1606 
1607 /*
1608 ** CAPI3REF: Memory Allocation Routines
1609 **
1610 ** An instance of this object defines the interface between SQLite
1611 ** and low-level memory allocation routines.
1612 **
1613 ** This object is used in only one place in the SQLite interface.
1614 ** A pointer to an instance of this object is the argument to
1615 ** [sqlite3_config()] when the configuration option is
1616 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1617 ** By creating an instance of this object
1618 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1619 ** during configuration, an application can specify an alternative
1620 ** memory allocation subsystem for SQLite to use for all of its
1621 ** dynamic memory needs.
1622 **
1623 ** Note that SQLite comes with several [built-in memory allocators]
1624 ** that are perfectly adequate for the overwhelming majority of applications
1625 ** and that this object is only useful to a tiny minority of applications
1626 ** with specialized memory allocation requirements.  This object is
1627 ** also used during testing of SQLite in order to specify an alternative
1628 ** memory allocator that simulates memory out-of-memory conditions in
1629 ** order to verify that SQLite recovers gracefully from such
1630 ** conditions.
1631 **
1632 ** The xMalloc, xRealloc, and xFree methods must work like the
1633 ** malloc(), realloc() and free() functions from the standard C library.
1634 ** ^SQLite guarantees that the second argument to
1635 ** xRealloc is always a value returned by a prior call to xRoundup.
1636 **
1637 ** xSize should return the allocated size of a memory allocation
1638 ** previously obtained from xMalloc or xRealloc.  The allocated size
1639 ** is always at least as big as the requested size but may be larger.
1640 **
1641 ** The xRoundup method returns what would be the allocated size of
1642 ** a memory allocation given a particular requested size.  Most memory
1643 ** allocators round up memory allocations at least to the next multiple
1644 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1645 ** Every memory allocation request coming in through [sqlite3_malloc()]
1646 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1647 ** that causes the corresponding memory allocation to fail.
1648 **
1649 ** The xInit method initializes the memory allocator.  For example,
1650 ** it might allocate any require mutexes or initialize internal data
1651 ** structures.  The xShutdown method is invoked (indirectly) by
1652 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1653 ** by xInit.  The pAppData pointer is used as the only parameter to
1654 ** xInit and xShutdown.
1655 **
1656 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1657 ** the xInit method, so the xInit method need not be threadsafe.  The
1658 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1659 ** not need to be threadsafe either.  For all other methods, SQLite
1660 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1661 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1662 ** it is by default) and so the methods are automatically serialized.
1663 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1664 ** methods must be threadsafe or else make their own arrangements for
1665 ** serialization.
1666 **
1667 ** SQLite will never invoke xInit() more than once without an intervening
1668 ** call to xShutdown().
1669 */
1670 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1671 struct sqlite3_mem_methods {
1672   void *(*xMalloc)(int);         /* Memory allocation function */
1673   void (*xFree)(void*);          /* Free a prior allocation */
1674   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1675   int (*xSize)(void*);           /* Return the size of an allocation */
1676   int (*xRoundup)(int);          /* Round up request size to allocation size */
1677   int (*xInit)(void*);           /* Initialize the memory allocator */
1678   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1679   void *pAppData;                /* Argument to xInit() and xShutdown() */
1680 };
1681 
1682 /*
1683 ** CAPI3REF: Configuration Options
1684 ** KEYWORDS: {configuration option}
1685 **
1686 ** These constants are the available integer configuration options that
1687 ** can be passed as the first argument to the [sqlite3_config()] interface.
1688 **
1689 ** New configuration options may be added in future releases of SQLite.
1690 ** Existing configuration options might be discontinued.  Applications
1691 ** should check the return code from [sqlite3_config()] to make sure that
1692 ** the call worked.  The [sqlite3_config()] interface will return a
1693 ** non-zero [error code] if a discontinued or unsupported configuration option
1694 ** is invoked.
1695 **
1696 ** <dl>
1697 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1698 ** <dd>There are no arguments to this option.  ^This option sets the
1699 ** [threading mode] to Single-thread.  In other words, it disables
1700 ** all mutexing and puts SQLite into a mode where it can only be used
1701 ** by a single thread.   ^If SQLite is compiled with
1702 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1703 ** it is not possible to change the [threading mode] from its default
1704 ** value of Single-thread and so [sqlite3_config()] will return
1705 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1706 ** configuration option.</dd>
1707 **
1708 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1709 ** <dd>There are no arguments to this option.  ^This option sets the
1710 ** [threading mode] to Multi-thread.  In other words, it disables
1711 ** mutexing on [database connection] and [prepared statement] objects.
1712 ** The application is responsible for serializing access to
1713 ** [database connections] and [prepared statements].  But other mutexes
1714 ** are enabled so that SQLite will be safe to use in a multi-threaded
1715 ** environment as long as no two threads attempt to use the same
1716 ** [database connection] at the same time.  ^If SQLite is compiled with
1717 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1718 ** it is not possible to set the Multi-thread [threading mode] and
1719 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1720 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1721 **
1722 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1723 ** <dd>There are no arguments to this option.  ^This option sets the
1724 ** [threading mode] to Serialized. In other words, this option enables
1725 ** all mutexes including the recursive
1726 ** mutexes on [database connection] and [prepared statement] objects.
1727 ** In this mode (which is the default when SQLite is compiled with
1728 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1729 ** to [database connections] and [prepared statements] so that the
1730 ** application is free to use the same [database connection] or the
1731 ** same [prepared statement] in different threads at the same time.
1732 ** ^If SQLite is compiled with
1733 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1734 ** it is not possible to set the Serialized [threading mode] and
1735 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1736 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1737 **
1738 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1739 ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
1740 ** a pointer to an instance of the [sqlite3_mem_methods] structure.
1741 ** The argument specifies
1742 ** alternative low-level memory allocation routines to be used in place of
1743 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1744 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1745 ** before the [sqlite3_config()] call returns.</dd>
1746 **
1747 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1748 ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
1749 ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
1750 ** The [sqlite3_mem_methods]
1751 ** structure is filled with the currently defined memory allocation routines.)^
1752 ** This option can be used to overload the default memory allocation
1753 ** routines with a wrapper that simulations memory allocation failure or
1754 ** tracks memory usage, for example. </dd>
1755 **
1756 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1757 ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
1758 ** interpreted as a boolean, which enables or disables the collection of
1759 ** memory allocation statistics. ^(When memory allocation statistics are
1760 ** disabled, the following SQLite interfaces become non-operational:
1761 **   <ul>
1762 **   <li> [sqlite3_memory_used()]
1763 **   <li> [sqlite3_memory_highwater()]
1764 **   <li> [sqlite3_soft_heap_limit64()]
1765 **   <li> [sqlite3_status64()]
1766 **   </ul>)^
1767 ** ^Memory allocation statistics are enabled by default unless SQLite is
1768 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1769 ** allocation statistics are disabled by default.
1770 ** </dd>
1771 **
1772 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1773 ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
1774 ** that SQLite can use for scratch memory.  ^(There are three arguments
1775 ** to SQLITE_CONFIG_SCRATCH:  A pointer an 8-byte
1776 ** aligned memory buffer from which the scratch allocations will be
1777 ** drawn, the size of each scratch allocation (sz),
1778 ** and the maximum number of scratch allocations (N).)^
1779 ** The first argument must be a pointer to an 8-byte aligned buffer
1780 ** of at least sz*N bytes of memory.
1781 ** ^SQLite will not use more than one scratch buffers per thread.
1782 ** ^SQLite will never request a scratch buffer that is more than 6
1783 ** times the database page size.
1784 ** ^If SQLite needs needs additional
1785 ** scratch memory beyond what is provided by this configuration option, then
1786 ** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
1787 ** ^When the application provides any amount of scratch memory using
1788 ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
1789 ** [sqlite3_malloc|heap allocations].
1790 ** This can help [Robson proof|prevent memory allocation failures] due to heap
1791 ** fragmentation in low-memory embedded systems.
1792 ** </dd>
1793 **
1794 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1795 ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a static memory buffer
1796 ** that SQLite can use for the database page cache with the default page
1797 ** cache implementation.
1798 ** This configuration should not be used if an application-define page
1799 ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]
1800 ** configuration option.
1801 ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
1802 ** 8-byte aligned
1803 ** memory, the size of each page buffer (sz), and the number of pages (N).
1804 ** The sz argument should be the size of the largest database page
1805 ** (a power of two between 512 and 65536) plus some extra bytes for each
1806 ** page header.  ^The number of extra bytes needed by the page header
1807 ** can be determined using the [SQLITE_CONFIG_PCACHE_HDRSZ] option
1808 ** to [sqlite3_config()].
1809 ** ^It is harmless, apart from the wasted memory,
1810 ** for the sz parameter to be larger than necessary.  The first
1811 ** argument should pointer to an 8-byte aligned block of memory that
1812 ** is at least sz*N bytes of memory, otherwise subsequent behavior is
1813 ** undefined.
1814 ** ^SQLite will use the memory provided by the first argument to satisfy its
1815 ** memory needs for the first N pages that it adds to cache.  ^If additional
1816 ** page cache memory is needed beyond what is provided by this option, then
1817 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.</dd>
1818 **
1819 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1820 ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
1821 ** that SQLite will use for all of its dynamic memory allocation needs
1822 ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
1823 ** [SQLITE_CONFIG_PAGECACHE].
1824 ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
1825 ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
1826 ** [SQLITE_ERROR] if invoked otherwise.
1827 ** ^There are three arguments to SQLITE_CONFIG_HEAP:
1828 ** An 8-byte aligned pointer to the memory,
1829 ** the number of bytes in the memory buffer, and the minimum allocation size.
1830 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1831 ** to using its default memory allocator (the system malloc() implementation),
1832 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1833 ** memory pointer is not NULL then the alternative memory
1834 ** allocator is engaged to handle all of SQLites memory allocation needs.
1835 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1836 ** boundary or subsequent behavior of SQLite will be undefined.
1837 ** The minimum allocation size is capped at 2**12. Reasonable values
1838 ** for the minimum allocation size are 2**5 through 2**8.</dd>
1839 **
1840 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1841 ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
1842 ** pointer to an instance of the [sqlite3_mutex_methods] structure.
1843 ** The argument specifies alternative low-level mutex routines to be used
1844 ** in place the mutex routines built into SQLite.)^  ^SQLite makes a copy of
1845 ** the content of the [sqlite3_mutex_methods] structure before the call to
1846 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1847 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1848 ** the entire mutexing subsystem is omitted from the build and hence calls to
1849 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1850 ** return [SQLITE_ERROR].</dd>
1851 **
1852 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1853 ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
1854 ** is a pointer to an instance of the [sqlite3_mutex_methods] structure.  The
1855 ** [sqlite3_mutex_methods]
1856 ** structure is filled with the currently defined mutex routines.)^
1857 ** This option can be used to overload the default mutex allocation
1858 ** routines with a wrapper used to track mutex usage for performance
1859 ** profiling or testing, for example.   ^If SQLite is compiled with
1860 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1861 ** the entire mutexing subsystem is omitted from the build and hence calls to
1862 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1863 ** return [SQLITE_ERROR].</dd>
1864 **
1865 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1866 ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
1867 ** the default size of lookaside memory on each [database connection].
1868 ** The first argument is the
1869 ** size of each lookaside buffer slot and the second is the number of
1870 ** slots allocated to each database connection.)^  ^(SQLITE_CONFIG_LOOKASIDE
1871 ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1872 ** option to [sqlite3_db_config()] can be used to change the lookaside
1873 ** configuration on individual connections.)^ </dd>
1874 **
1875 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
1876 ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
1877 ** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies
1878 ** the interface to a custom page cache implementation.)^
1879 ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
1880 **
1881 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
1882 ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
1883 ** is a pointer to an [sqlite3_pcache_methods2] object.  SQLite copies of
1884 ** the current page cache implementation into that object.)^ </dd>
1885 **
1886 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
1887 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
1888 ** global [error log].
1889 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1890 ** function with a call signature of void(*)(void*,int,const char*),
1891 ** and a pointer to void. ^If the function pointer is not NULL, it is
1892 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
1893 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1894 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1895 ** passed through as the first parameter to the application-defined logger
1896 ** function whenever that function is invoked.  ^The second parameter to
1897 ** the logger function is a copy of the first parameter to the corresponding
1898 ** [sqlite3_log()] call and is intended to be a [result code] or an
1899 ** [extended result code].  ^The third parameter passed to the logger is
1900 ** log message after formatting via [sqlite3_snprintf()].
1901 ** The SQLite logging interface is not reentrant; the logger function
1902 ** supplied by the application must not invoke any SQLite interface.
1903 ** In a multi-threaded application, the application-defined logger
1904 ** function must be threadsafe. </dd>
1905 **
1906 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
1907 ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
1908 ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
1909 ** then URI handling is globally disabled.)^ ^If URI handling is globally
1910 ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
1911 ** [sqlite3_open16()] or
1912 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
1913 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
1914 ** connection is opened. ^If it is globally disabled, filenames are
1915 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
1916 ** database connection is opened. ^(By default, URI handling is globally
1917 ** disabled. The default value may be changed by compiling with the
1918 ** [SQLITE_USE_URI] symbol defined.)^
1919 **
1920 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
1921 ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
1922 ** argument which is interpreted as a boolean in order to enable or disable
1923 ** the use of covering indices for full table scans in the query optimizer.
1924 ** ^The default setting is determined
1925 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
1926 ** if that compile-time option is omitted.
1927 ** The ability to disable the use of covering indices for full table scans
1928 ** is because some incorrectly coded legacy applications might malfunction
1929 ** when the optimization is enabled.  Providing the ability to
1930 ** disable the optimization allows the older, buggy application code to work
1931 ** without change even with newer versions of SQLite.
1932 **
1933 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
1934 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
1935 ** <dd> These options are obsolete and should not be used by new code.
1936 ** They are retained for backwards compatibility but are now no-ops.
1937 ** </dd>
1938 **
1939 ** [[SQLITE_CONFIG_SQLLOG]]
1940 ** <dt>SQLITE_CONFIG_SQLLOG
1941 ** <dd>This option is only available if sqlite is compiled with the
1942 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
1943 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
1944 ** The second should be of type (void*). The callback is invoked by the library
1945 ** in three separate circumstances, identified by the value passed as the
1946 ** fourth parameter. If the fourth parameter is 0, then the database connection
1947 ** passed as the second argument has just been opened. The third argument
1948 ** points to a buffer containing the name of the main database file. If the
1949 ** fourth parameter is 1, then the SQL statement that the third parameter
1950 ** points to has just been executed. Or, if the fourth parameter is 2, then
1951 ** the connection being passed as the second parameter is being closed. The
1952 ** third parameter is passed NULL In this case.  An example of using this
1953 ** configuration option can be seen in the "test_sqllog.c" source file in
1954 ** the canonical SQLite source tree.</dd>
1955 **
1956 ** [[SQLITE_CONFIG_MMAP_SIZE]]
1957 ** <dt>SQLITE_CONFIG_MMAP_SIZE
1958 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
1959 ** that are the default mmap size limit (the default setting for
1960 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
1961 ** ^The default setting can be overridden by each database connection using
1962 ** either the [PRAGMA mmap_size] command, or by using the
1963 ** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
1964 ** will be silently truncated if necessary so that it does not exceed the
1965 ** compile-time maximum mmap size set by the
1966 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
1967 ** ^If either argument to this option is negative, then that argument is
1968 ** changed to its compile-time default.
1969 **
1970 ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
1971 ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
1972 ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
1973 ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
1974 ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
1975 ** that specifies the maximum size of the created heap.
1976 **
1977 ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
1978 ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
1979 ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
1980 ** is a pointer to an integer and writes into that integer the number of extra
1981 ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
1982 ** The amount of extra space required can change depending on the compiler,
1983 ** target platform, and SQLite version.
1984 **
1985 ** [[SQLITE_CONFIG_PMASZ]]
1986 ** <dt>SQLITE_CONFIG_PMASZ
1987 ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
1988 ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
1989 ** sorter to that integer.  The default minimum PMA Size is set by the
1990 ** [SQLITE_SORTER_PMASZ] compile-time option.  New threads are launched
1991 ** to help with sort operations when multithreaded sorting
1992 ** is enabled (using the [PRAGMA threads] command) and the amount of content
1993 ** to be sorted exceeds the page size times the minimum of the
1994 ** [PRAGMA cache_size] setting and this value.
1995 ** </dl>
1996 */
1997 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1998 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1999 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2000 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2001 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2002 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2003 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2004 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2005 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2006 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2007 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2008 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2009 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2010 #define SQLITE_CONFIG_PCACHE       14  /* no-op */
2011 #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
2012 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2013 #define SQLITE_CONFIG_URI          17  /* int */
2014 #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
2015 #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
2016 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
2017 #define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
2018 #define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
2019 #define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
2020 #define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
2021 #define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
2022 
2023 /*
2024 ** CAPI3REF: Database Connection Configuration Options
2025 **
2026 ** These constants are the available integer configuration options that
2027 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2028 **
2029 ** New configuration options may be added in future releases of SQLite.
2030 ** Existing configuration options might be discontinued.  Applications
2031 ** should check the return code from [sqlite3_db_config()] to make sure that
2032 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
2033 ** non-zero [error code] if a discontinued or unsupported configuration option
2034 ** is invoked.
2035 **
2036 ** <dl>
2037 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2038 ** <dd> ^This option takes three additional arguments that determine the
2039 ** [lookaside memory allocator] configuration for the [database connection].
2040 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2041 ** pointer to a memory buffer to use for lookaside memory.
2042 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2043 ** may be NULL in which case SQLite will allocate the
2044 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2045 ** size of each lookaside buffer slot.  ^The third argument is the number of
2046 ** slots.  The size of the buffer in the first argument must be greater than
2047 ** or equal to the product of the second and third arguments.  The buffer
2048 ** must be aligned to an 8-byte boundary.  ^If the second argument to
2049 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2050 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2051 ** configuration for a database connection can only be changed when that
2052 ** connection is not currently using lookaside memory, or in other words
2053 ** when the "current value" returned by
2054 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2055 ** Any attempt to change the lookaside memory configuration when lookaside
2056 ** memory is in use leaves the configuration unchanged and returns
2057 ** [SQLITE_BUSY].)^</dd>
2058 **
2059 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2060 ** <dd> ^This option is used to enable or disable the enforcement of
2061 ** [foreign key constraints].  There should be two additional arguments.
2062 ** The first argument is an integer which is 0 to disable FK enforcement,
2063 ** positive to enable FK enforcement or negative to leave FK enforcement
2064 ** unchanged.  The second parameter is a pointer to an integer into which
2065 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2066 ** following this call.  The second parameter may be a NULL pointer, in
2067 ** which case the FK enforcement setting is not reported back. </dd>
2068 **
2069 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2070 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2071 ** There should be two additional arguments.
2072 ** The first argument is an integer which is 0 to disable triggers,
2073 ** positive to enable triggers or negative to leave the setting unchanged.
2074 ** The second parameter is a pointer to an integer into which
2075 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2076 ** following this call.  The second parameter may be a NULL pointer, in
2077 ** which case the trigger setting is not reported back. </dd>
2078 **
2079 ** </dl>
2080 */
2081 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2082 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2083 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2084 
2085 
2086 /*
2087 ** CAPI3REF: Enable Or Disable Extended Result Codes
2088 ** METHOD: sqlite3
2089 **
2090 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2091 ** [extended result codes] feature of SQLite. ^The extended result
2092 ** codes are disabled by default for historical compatibility.
2093 */
2094 SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3*, int onoff);
2095 
2096 /*
2097 ** CAPI3REF: Last Insert Rowid
2098 ** METHOD: sqlite3
2099 **
2100 ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
2101 ** has a unique 64-bit signed
2102 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2103 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2104 ** names are not also used by explicitly declared columns. ^If
2105 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2106 ** is another alias for the rowid.
2107 **
2108 ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
2109 ** most recent successful [INSERT] into a rowid table or [virtual table]
2110 ** on database connection D.
2111 ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
2112 ** ^If no successful [INSERT]s into rowid tables
2113 ** have ever occurred on the database connection D,
2114 ** then sqlite3_last_insert_rowid(D) returns zero.
2115 **
2116 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2117 ** method, then this routine will return the [rowid] of the inserted
2118 ** row as long as the trigger or virtual table method is running.
2119 ** But once the trigger or virtual table method ends, the value returned
2120 ** by this routine reverts to what it was before the trigger or virtual
2121 ** table method began.)^
2122 **
2123 ** ^An [INSERT] that fails due to a constraint violation is not a
2124 ** successful [INSERT] and does not change the value returned by this
2125 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2126 ** and INSERT OR ABORT make no changes to the return value of this
2127 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2128 ** encounters a constraint violation, it does not fail.  The
2129 ** INSERT continues to completion after deleting rows that caused
2130 ** the constraint problem so INSERT OR REPLACE will always change
2131 ** the return value of this interface.)^
2132 **
2133 ** ^For the purposes of this routine, an [INSERT] is considered to
2134 ** be successful even if it is subsequently rolled back.
2135 **
2136 ** This function is accessible to SQL statements via the
2137 ** [last_insert_rowid() SQL function].
2138 **
2139 ** If a separate thread performs a new [INSERT] on the same
2140 ** database connection while the [sqlite3_last_insert_rowid()]
2141 ** function is running and thus changes the last insert [rowid],
2142 ** then the value returned by [sqlite3_last_insert_rowid()] is
2143 ** unpredictable and might not equal either the old or the new
2144 ** last insert [rowid].
2145 */
2146 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3*);
2147 
2148 /*
2149 ** CAPI3REF: Count The Number Of Rows Modified
2150 ** METHOD: sqlite3
2151 **
2152 ** ^This function returns the number of rows modified, inserted or
2153 ** deleted by the most recently completed INSERT, UPDATE or DELETE
2154 ** statement on the database connection specified by the only parameter.
2155 ** ^Executing any other type of SQL statement does not modify the value
2156 ** returned by this function.
2157 **
2158 ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
2159 ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
2160 ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
2161 **
2162 ** Changes to a view that are intercepted by
2163 ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
2164 ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
2165 ** DELETE statement run on a view is always zero. Only changes made to real
2166 ** tables are counted.
2167 **
2168 ** Things are more complicated if the sqlite3_changes() function is
2169 ** executed while a trigger program is running. This may happen if the
2170 ** program uses the [changes() SQL function], or if some other callback
2171 ** function invokes sqlite3_changes() directly. Essentially:
2172 **
2173 ** <ul>
2174 **   <li> ^(Before entering a trigger program the value returned by
2175 **        sqlite3_changes() function is saved. After the trigger program
2176 **        has finished, the original value is restored.)^
2177 **
2178 **   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
2179 **        statement sets the value returned by sqlite3_changes()
2180 **        upon completion as normal. Of course, this value will not include
2181 **        any changes performed by sub-triggers, as the sqlite3_changes()
2182 **        value will be saved and restored after each sub-trigger has run.)^
2183 ** </ul>
2184 **
2185 ** ^This means that if the changes() SQL function (or similar) is used
2186 ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
2187 ** returns the value as set when the calling statement began executing.
2188 ** ^If it is used by the second or subsequent such statement within a trigger
2189 ** program, the value returned reflects the number of rows modified by the
2190 ** previous INSERT, UPDATE or DELETE statement within the same trigger.
2191 **
2192 ** See also the [sqlite3_total_changes()] interface, the
2193 ** [count_changes pragma], and the [changes() SQL function].
2194 **
2195 ** If a separate thread makes changes on the same database connection
2196 ** while [sqlite3_changes()] is running then the value returned
2197 ** is unpredictable and not meaningful.
2198 */
2199 SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3*);
2200 
2201 /*
2202 ** CAPI3REF: Total Number Of Rows Modified
2203 ** METHOD: sqlite3
2204 **
2205 ** ^This function returns the total number of rows inserted, modified or
2206 ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
2207 ** since the database connection was opened, including those executed as
2208 ** part of trigger programs. ^Executing any other type of SQL statement
2209 ** does not affect the value returned by sqlite3_total_changes().
2210 **
2211 ** ^Changes made as part of [foreign key actions] are included in the
2212 ** count, but those made as part of REPLACE constraint resolution are
2213 ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
2214 ** are not counted.
2215 **
2216 ** See also the [sqlite3_changes()] interface, the
2217 ** [count_changes pragma], and the [total_changes() SQL function].
2218 **
2219 ** If a separate thread makes changes on the same database connection
2220 ** while [sqlite3_total_changes()] is running then the value
2221 ** returned is unpredictable and not meaningful.
2222 */
2223 SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3*);
2224 
2225 /*
2226 ** CAPI3REF: Interrupt A Long-Running Query
2227 ** METHOD: sqlite3
2228 **
2229 ** ^This function causes any pending database operation to abort and
2230 ** return at its earliest opportunity. This routine is typically
2231 ** called in response to a user action such as pressing "Cancel"
2232 ** or Ctrl-C where the user wants a long query operation to halt
2233 ** immediately.
2234 **
2235 ** ^It is safe to call this routine from a thread different from the
2236 ** thread that is currently running the database operation.  But it
2237 ** is not safe to call this routine with a [database connection] that
2238 ** is closed or might close before sqlite3_interrupt() returns.
2239 **
2240 ** ^If an SQL operation is very nearly finished at the time when
2241 ** sqlite3_interrupt() is called, then it might not have an opportunity
2242 ** to be interrupted and might continue to completion.
2243 **
2244 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2245 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2246 ** that is inside an explicit transaction, then the entire transaction
2247 ** will be rolled back automatically.
2248 **
2249 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2250 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2251 ** that are started after the sqlite3_interrupt() call and before the
2252 ** running statements reaches zero are interrupted as if they had been
2253 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2254 ** that are started after the running statement count reaches zero are
2255 ** not effected by the sqlite3_interrupt().
2256 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2257 ** SQL statements is a no-op and has no effect on SQL statements
2258 ** that are started after the sqlite3_interrupt() call returns.
2259 **
2260 ** If the database connection closes while [sqlite3_interrupt()]
2261 ** is running then bad things will likely happen.
2262 */
2263 SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3*);
2264 
2265 /*
2266 ** CAPI3REF: Determine If An SQL Statement Is Complete
2267 **
2268 ** These routines are useful during command-line input to determine if the
2269 ** currently entered text seems to form a complete SQL statement or
2270 ** if additional input is needed before sending the text into
2271 ** SQLite for parsing.  ^These routines return 1 if the input string
2272 ** appears to be a complete SQL statement.  ^A statement is judged to be
2273 ** complete if it ends with a semicolon token and is not a prefix of a
2274 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2275 ** string literals or quoted identifier names or comments are not
2276 ** independent tokens (they are part of the token in which they are
2277 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2278 ** and comments that follow the final semicolon are ignored.
2279 **
2280 ** ^These routines return 0 if the statement is incomplete.  ^If a
2281 ** memory allocation fails, then SQLITE_NOMEM is returned.
2282 **
2283 ** ^These routines do not parse the SQL statements thus
2284 ** will not detect syntactically incorrect SQL.
2285 **
2286 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2287 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2288 ** automatically by sqlite3_complete16().  If that initialization fails,
2289 ** then the return value from sqlite3_complete16() will be non-zero
2290 ** regardless of whether or not the input SQL is complete.)^
2291 **
2292 ** The input to [sqlite3_complete()] must be a zero-terminated
2293 ** UTF-8 string.
2294 **
2295 ** The input to [sqlite3_complete16()] must be a zero-terminated
2296 ** UTF-16 string in native byte order.
2297 */
2298 SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *sql);
2299 SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *sql);
2300 
2301 /*
2302 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2303 ** KEYWORDS: {busy-handler callback} {busy handler}
2304 ** METHOD: sqlite3
2305 **
2306 ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
2307 ** that might be invoked with argument P whenever
2308 ** an attempt is made to access a database table associated with
2309 ** [database connection] D when another thread
2310 ** or process has the table locked.
2311 ** The sqlite3_busy_handler() interface is used to implement
2312 ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
2313 **
2314 ** ^If the busy callback is NULL, then [SQLITE_BUSY]
2315 ** is returned immediately upon encountering the lock.  ^If the busy callback
2316 ** is not NULL, then the callback might be invoked with two arguments.
2317 **
2318 ** ^The first argument to the busy handler is a copy of the void* pointer which
2319 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2320 ** the busy handler callback is the number of times that the busy handler has
2321 ** been invoked previously for the same locking event.  ^If the
2322 ** busy callback returns 0, then no additional attempts are made to
2323 ** access the database and [SQLITE_BUSY] is returned
2324 ** to the application.
2325 ** ^If the callback returns non-zero, then another attempt
2326 ** is made to access the database and the cycle repeats.
2327 **
2328 ** The presence of a busy handler does not guarantee that it will be invoked
2329 ** when there is lock contention. ^If SQLite determines that invoking the busy
2330 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2331 ** to the application instead of invoking the
2332 ** busy handler.
2333 ** Consider a scenario where one process is holding a read lock that
2334 ** it is trying to promote to a reserved lock and
2335 ** a second process is holding a reserved lock that it is trying
2336 ** to promote to an exclusive lock.  The first process cannot proceed
2337 ** because it is blocked by the second and the second process cannot
2338 ** proceed because it is blocked by the first.  If both processes
2339 ** invoke the busy handlers, neither will make any progress.  Therefore,
2340 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2341 ** will induce the first process to release its read lock and allow
2342 ** the second process to proceed.
2343 **
2344 ** ^The default busy callback is NULL.
2345 **
2346 ** ^(There can only be a single busy handler defined for each
2347 ** [database connection].  Setting a new busy handler clears any
2348 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2349 ** or evaluating [PRAGMA busy_timeout=N] will change the
2350 ** busy handler and thus clear any previously set busy handler.
2351 **
2352 ** The busy callback should not take any actions which modify the
2353 ** database connection that invoked the busy handler.  In other words,
2354 ** the busy handler is not reentrant.  Any such actions
2355 ** result in undefined behavior.
2356 **
2357 ** A busy handler must not close the database connection
2358 ** or [prepared statement] that invoked the busy handler.
2359 */
2360 SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2361 
2362 /*
2363 ** CAPI3REF: Set A Busy Timeout
2364 ** METHOD: sqlite3
2365 **
2366 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2367 ** for a specified amount of time when a table is locked.  ^The handler
2368 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2369 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2370 ** the handler returns 0 which causes [sqlite3_step()] to return
2371 ** [SQLITE_BUSY].
2372 **
2373 ** ^Calling this routine with an argument less than or equal to zero
2374 ** turns off all busy handlers.
2375 **
2376 ** ^(There can only be a single busy handler for a particular
2377 ** [database connection] at any given moment.  If another busy handler
2378 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2379 ** this routine, that other busy handler is cleared.)^
2380 **
2381 ** See also:  [PRAGMA busy_timeout]
2382 */
2383 SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3*, int ms);
2384 
2385 /*
2386 ** CAPI3REF: Convenience Routines For Running Queries
2387 ** METHOD: sqlite3
2388 **
2389 ** This is a legacy interface that is preserved for backwards compatibility.
2390 ** Use of this interface is not recommended.
2391 **
2392 ** Definition: A <b>result table</b> is memory data structure created by the
2393 ** [sqlite3_get_table()] interface.  A result table records the
2394 ** complete query results from one or more queries.
2395 **
2396 ** The table conceptually has a number of rows and columns.  But
2397 ** these numbers are not part of the result table itself.  These
2398 ** numbers are obtained separately.  Let N be the number of rows
2399 ** and M be the number of columns.
2400 **
2401 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2402 ** There are (N+1)*M elements in the array.  The first M pointers point
2403 ** to zero-terminated strings that  contain the names of the columns.
2404 ** The remaining entries all point to query results.  NULL values result
2405 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2406 ** string representation as returned by [sqlite3_column_text()].
2407 **
2408 ** A result table might consist of one or more memory allocations.
2409 ** It is not safe to pass a result table directly to [sqlite3_free()].
2410 ** A result table should be deallocated using [sqlite3_free_table()].
2411 **
2412 ** ^(As an example of the result table format, suppose a query result
2413 ** is as follows:
2414 **
2415 ** <blockquote><pre>
2416 **        Name        | Age
2417 **        -----------------------
2418 **        Alice       | 43
2419 **        Bob         | 28
2420 **        Cindy       | 21
2421 ** </pre></blockquote>
2422 **
2423 ** There are two column (M==2) and three rows (N==3).  Thus the
2424 ** result table has 8 entries.  Suppose the result table is stored
2425 ** in an array names azResult.  Then azResult holds this content:
2426 **
2427 ** <blockquote><pre>
2428 **        azResult&#91;0] = "Name";
2429 **        azResult&#91;1] = "Age";
2430 **        azResult&#91;2] = "Alice";
2431 **        azResult&#91;3] = "43";
2432 **        azResult&#91;4] = "Bob";
2433 **        azResult&#91;5] = "28";
2434 **        azResult&#91;6] = "Cindy";
2435 **        azResult&#91;7] = "21";
2436 ** </pre></blockquote>)^
2437 **
2438 ** ^The sqlite3_get_table() function evaluates one or more
2439 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2440 ** string of its 2nd parameter and returns a result table to the
2441 ** pointer given in its 3rd parameter.
2442 **
2443 ** After the application has finished with the result from sqlite3_get_table(),
2444 ** it must pass the result table pointer to sqlite3_free_table() in order to
2445 ** release the memory that was malloced.  Because of the way the
2446 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2447 ** function must not try to call [sqlite3_free()] directly.  Only
2448 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2449 **
2450 ** The sqlite3_get_table() interface is implemented as a wrapper around
2451 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2452 ** to any internal data structures of SQLite.  It uses only the public
2453 ** interface defined here.  As a consequence, errors that occur in the
2454 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2455 ** reflected in subsequent calls to [sqlite3_errcode()] or
2456 ** [sqlite3_errmsg()].
2457 */
2458 SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
2459   sqlite3 *db,          /* An open database */
2460   const char *zSql,     /* SQL to be evaluated */
2461   char ***pazResult,    /* Results of the query */
2462   int *pnRow,           /* Number of result rows written here */
2463   int *pnColumn,        /* Number of result columns written here */
2464   char **pzErrmsg       /* Error msg written here */
2465 );
2466 SQLITE_API void SQLITE_STDCALL sqlite3_free_table(char **result);
2467 
2468 /*
2469 ** CAPI3REF: Formatted String Printing Functions
2470 **
2471 ** These routines are work-alikes of the "printf()" family of functions
2472 ** from the standard C library.
2473 ** These routines understand most of the common K&R formatting options,
2474 ** plus some additional non-standard formats, detailed below.
2475 ** Note that some of the more obscure formatting options from recent
2476 ** C-library standards are omitted from this implementation.
2477 **
2478 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2479 ** results into memory obtained from [sqlite3_malloc()].
2480 ** The strings returned by these two routines should be
2481 ** released by [sqlite3_free()].  ^Both routines return a
2482 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2483 ** memory to hold the resulting string.
2484 **
2485 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2486 ** the standard C library.  The result is written into the
2487 ** buffer supplied as the second parameter whose size is given by
2488 ** the first parameter. Note that the order of the
2489 ** first two parameters is reversed from snprintf().)^  This is an
2490 ** historical accident that cannot be fixed without breaking
2491 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2492 ** returns a pointer to its buffer instead of the number of
2493 ** characters actually written into the buffer.)^  We admit that
2494 ** the number of characters written would be a more useful return
2495 ** value but we cannot change the implementation of sqlite3_snprintf()
2496 ** now without breaking compatibility.
2497 **
2498 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2499 ** guarantees that the buffer is always zero-terminated.  ^The first
2500 ** parameter "n" is the total size of the buffer, including space for
2501 ** the zero terminator.  So the longest string that can be completely
2502 ** written will be n-1 characters.
2503 **
2504 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2505 **
2506 ** These routines all implement some additional formatting
2507 ** options that are useful for constructing SQL statements.
2508 ** All of the usual printf() formatting options apply.  In addition, there
2509 ** is are "%q", "%Q", "%w" and "%z" options.
2510 **
2511 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2512 ** string from the argument list.  But %q also doubles every '\'' character.
2513 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2514 ** character it escapes that character and allows it to be inserted into
2515 ** the string.
2516 **
2517 ** For example, assume the string variable zText contains text as follows:
2518 **
2519 ** <blockquote><pre>
2520 **  char *zText = "It's a happy day!";
2521 ** </pre></blockquote>
2522 **
2523 ** One can use this text in an SQL statement as follows:
2524 **
2525 ** <blockquote><pre>
2526 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2527 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2528 **  sqlite3_free(zSQL);
2529 ** </pre></blockquote>
2530 **
2531 ** Because the %q format string is used, the '\'' character in zText
2532 ** is escaped and the SQL generated is as follows:
2533 **
2534 ** <blockquote><pre>
2535 **  INSERT INTO table1 VALUES('It''s a happy day!')
2536 ** </pre></blockquote>
2537 **
2538 ** This is correct.  Had we used %s instead of %q, the generated SQL
2539 ** would have looked like this:
2540 **
2541 ** <blockquote><pre>
2542 **  INSERT INTO table1 VALUES('It's a happy day!');
2543 ** </pre></blockquote>
2544 **
2545 ** This second example is an SQL syntax error.  As a general rule you should
2546 ** always use %q instead of %s when inserting text into a string literal.
2547 **
2548 ** ^(The %Q option works like %q except it also adds single quotes around
2549 ** the outside of the total string.  Additionally, if the parameter in the
2550 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2551 ** single quotes).)^  So, for example, one could say:
2552 **
2553 ** <blockquote><pre>
2554 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2555 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2556 **  sqlite3_free(zSQL);
2557 ** </pre></blockquote>
2558 **
2559 ** The code above will render a correct SQL statement in the zSQL
2560 ** variable even if the zText variable is a NULL pointer.
2561 **
2562 ** ^(The "%w" formatting option is like "%q" except that it expects to
2563 ** be contained within double-quotes instead of single quotes, and it
2564 ** escapes the double-quote character instead of the single-quote
2565 ** character.)^  The "%w" formatting option is intended for safely inserting
2566 ** table and column names into a constructed SQL statement.
2567 **
2568 ** ^(The "%z" formatting option works like "%s" but with the
2569 ** addition that after the string has been read and copied into
2570 ** the result, [sqlite3_free()] is called on the input string.)^
2571 */
2572 SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char*,...);
2573 SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char*, va_list);
2574 SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int,char*,const char*, ...);
2575 SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int,char*,const char*, va_list);
2576 
2577 /*
2578 ** CAPI3REF: Memory Allocation Subsystem
2579 **
2580 ** The SQLite core uses these three routines for all of its own
2581 ** internal memory allocation needs. "Core" in the previous sentence
2582 ** does not include operating-system specific VFS implementation.  The
2583 ** Windows VFS uses native malloc() and free() for some operations.
2584 **
2585 ** ^The sqlite3_malloc() routine returns a pointer to a block
2586 ** of memory at least N bytes in length, where N is the parameter.
2587 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2588 ** memory, it returns a NULL pointer.  ^If the parameter N to
2589 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2590 ** a NULL pointer.
2591 **
2592 ** ^The sqlite3_malloc64(N) routine works just like
2593 ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
2594 ** of a signed 32-bit integer.
2595 **
2596 ** ^Calling sqlite3_free() with a pointer previously returned
2597 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2598 ** that it might be reused.  ^The sqlite3_free() routine is
2599 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2600 ** to sqlite3_free() is harmless.  After being freed, memory
2601 ** should neither be read nor written.  Even reading previously freed
2602 ** memory might result in a segmentation fault or other severe error.
2603 ** Memory corruption, a segmentation fault, or other severe error
2604 ** might result if sqlite3_free() is called with a non-NULL pointer that
2605 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2606 **
2607 ** ^The sqlite3_realloc(X,N) interface attempts to resize a
2608 ** prior memory allocation X to be at least N bytes.
2609 ** ^If the X parameter to sqlite3_realloc(X,N)
2610 ** is a NULL pointer then its behavior is identical to calling
2611 ** sqlite3_malloc(N).
2612 ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
2613 ** negative then the behavior is exactly the same as calling
2614 ** sqlite3_free(X).
2615 ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
2616 ** of at least N bytes in size or NULL if insufficient memory is available.
2617 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2618 ** of the prior allocation are copied into the beginning of buffer returned
2619 ** by sqlite3_realloc(X,N) and the prior allocation is freed.
2620 ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
2621 ** prior allocation is not freed.
2622 **
2623 ** ^The sqlite3_realloc64(X,N) interfaces works the same as
2624 ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
2625 ** of a 32-bit signed integer.
2626 **
2627 ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
2628 ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
2629 ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
2630 ** ^The value returned by sqlite3_msize(X) might be larger than the number
2631 ** of bytes requested when X was allocated.  ^If X is a NULL pointer then
2632 ** sqlite3_msize(X) returns zero.  If X points to something that is not
2633 ** the beginning of memory allocation, or if it points to a formerly
2634 ** valid memory allocation that has now been freed, then the behavior
2635 ** of sqlite3_msize(X) is undefined and possibly harmful.
2636 **
2637 ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
2638 ** sqlite3_malloc64(), and sqlite3_realloc64()
2639 ** is always aligned to at least an 8 byte boundary, or to a
2640 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2641 ** option is used.
2642 **
2643 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2644 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2645 ** implementation of these routines to be omitted.  That capability
2646 ** is no longer provided.  Only built-in memory allocators can be used.
2647 **
2648 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2649 ** the system malloc() and free() directly when converting
2650 ** filenames between the UTF-8 encoding used by SQLite
2651 ** and whatever filename encoding is used by the particular Windows
2652 ** installation.  Memory allocation errors were detected, but
2653 ** they were reported back as [SQLITE_CANTOPEN] or
2654 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2655 **
2656 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2657 ** must be either NULL or else pointers obtained from a prior
2658 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2659 ** not yet been released.
2660 **
2661 ** The application must not read or write any part of
2662 ** a block of memory after it has been released using
2663 ** [sqlite3_free()] or [sqlite3_realloc()].
2664 */
2665 SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int);
2666 SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64);
2667 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void*, int);
2668 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void*, sqlite3_uint64);
2669 SQLITE_API void SQLITE_STDCALL sqlite3_free(void*);
2670 SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void*);
2671 
2672 /*
2673 ** CAPI3REF: Memory Allocator Statistics
2674 **
2675 ** SQLite provides these two interfaces for reporting on the status
2676 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2677 ** routines, which form the built-in memory allocation subsystem.
2678 **
2679 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2680 ** of memory currently outstanding (malloced but not freed).
2681 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2682 ** value of [sqlite3_memory_used()] since the high-water mark
2683 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2684 ** [sqlite3_memory_highwater()] include any overhead
2685 ** added by SQLite in its implementation of [sqlite3_malloc()],
2686 ** but not overhead added by the any underlying system library
2687 ** routines that [sqlite3_malloc()] may call.
2688 **
2689 ** ^The memory high-water mark is reset to the current value of
2690 ** [sqlite3_memory_used()] if and only if the parameter to
2691 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2692 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2693 ** prior to the reset.
2694 */
2695 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void);
2696 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag);
2697 
2698 /*
2699 ** CAPI3REF: Pseudo-Random Number Generator
2700 **
2701 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2702 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2703 ** already uses the largest possible [ROWID].  The PRNG is also used for
2704 ** the build-in random() and randomblob() SQL functions.  This interface allows
2705 ** applications to access the same PRNG for other purposes.
2706 **
2707 ** ^A call to this routine stores N bytes of randomness into buffer P.
2708 ** ^The P parameter can be a NULL pointer.
2709 **
2710 ** ^If this routine has not been previously called or if the previous
2711 ** call had N less than one or a NULL pointer for P, then the PRNG is
2712 ** seeded using randomness obtained from the xRandomness method of
2713 ** the default [sqlite3_vfs] object.
2714 ** ^If the previous call to this routine had an N of 1 or more and a
2715 ** non-NULL P then the pseudo-randomness is generated
2716 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2717 ** method.
2718 */
2719 SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *P);
2720 
2721 /*
2722 ** CAPI3REF: Compile-Time Authorization Callbacks
2723 ** METHOD: sqlite3
2724 **
2725 ** ^This routine registers an authorizer callback with a particular
2726 ** [database connection], supplied in the first argument.
2727 ** ^The authorizer callback is invoked as SQL statements are being compiled
2728 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2729 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2730 ** points during the compilation process, as logic is being created
2731 ** to perform various actions, the authorizer callback is invoked to
2732 ** see if those actions are allowed.  ^The authorizer callback should
2733 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2734 ** specific action but allow the SQL statement to continue to be
2735 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2736 ** rejected with an error.  ^If the authorizer callback returns
2737 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2738 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2739 ** the authorizer will fail with an error message.
2740 **
2741 ** When the callback returns [SQLITE_OK], that means the operation
2742 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2743 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2744 ** authorizer will fail with an error message explaining that
2745 ** access is denied.
2746 **
2747 ** ^The first parameter to the authorizer callback is a copy of the third
2748 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2749 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2750 ** the particular action to be authorized. ^The third through sixth parameters
2751 ** to the callback are zero-terminated strings that contain additional
2752 ** details about the action to be authorized.
2753 **
2754 ** ^If the action code is [SQLITE_READ]
2755 ** and the callback returns [SQLITE_IGNORE] then the
2756 ** [prepared statement] statement is constructed to substitute
2757 ** a NULL value in place of the table column that would have
2758 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2759 ** return can be used to deny an untrusted user access to individual
2760 ** columns of a table.
2761 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2762 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2763 ** [truncate optimization] is disabled and all rows are deleted individually.
2764 **
2765 ** An authorizer is used when [sqlite3_prepare | preparing]
2766 ** SQL statements from an untrusted source, to ensure that the SQL statements
2767 ** do not try to access data they are not allowed to see, or that they do not
2768 ** try to execute malicious statements that damage the database.  For
2769 ** example, an application may allow a user to enter arbitrary
2770 ** SQL queries for evaluation by a database.  But the application does
2771 ** not want the user to be able to make arbitrary changes to the
2772 ** database.  An authorizer could then be put in place while the
2773 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2774 ** disallows everything except [SELECT] statements.
2775 **
2776 ** Applications that need to process SQL from untrusted sources
2777 ** might also consider lowering resource limits using [sqlite3_limit()]
2778 ** and limiting database size using the [max_page_count] [PRAGMA]
2779 ** in addition to using an authorizer.
2780 **
2781 ** ^(Only a single authorizer can be in place on a database connection
2782 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2783 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2784 ** The authorizer is disabled by default.
2785 **
2786 ** The authorizer callback must not do anything that will modify
2787 ** the database connection that invoked the authorizer callback.
2788 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2789 ** database connections for the meaning of "modify" in this paragraph.
2790 **
2791 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2792 ** statement might be re-prepared during [sqlite3_step()] due to a
2793 ** schema change.  Hence, the application should ensure that the
2794 ** correct authorizer callback remains in place during the [sqlite3_step()].
2795 **
2796 ** ^Note that the authorizer callback is invoked only during
2797 ** [sqlite3_prepare()] or its variants.  Authorization is not
2798 ** performed during statement evaluation in [sqlite3_step()], unless
2799 ** as stated in the previous paragraph, sqlite3_step() invokes
2800 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2801 */
2802 SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
2803   sqlite3*,
2804   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2805   void *pUserData
2806 );
2807 
2808 /*
2809 ** CAPI3REF: Authorizer Return Codes
2810 **
2811 ** The [sqlite3_set_authorizer | authorizer callback function] must
2812 ** return either [SQLITE_OK] or one of these two constants in order
2813 ** to signal SQLite whether or not the action is permitted.  See the
2814 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2815 ** information.
2816 **
2817 ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
2818 ** returned from the [sqlite3_vtab_on_conflict()] interface.
2819 */
2820 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2821 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2822 
2823 /*
2824 ** CAPI3REF: Authorizer Action Codes
2825 **
2826 ** The [sqlite3_set_authorizer()] interface registers a callback function
2827 ** that is invoked to authorize certain SQL statement actions.  The
2828 ** second parameter to the callback is an integer code that specifies
2829 ** what action is being authorized.  These are the integer action codes that
2830 ** the authorizer callback may be passed.
2831 **
2832 ** These action code values signify what kind of operation is to be
2833 ** authorized.  The 3rd and 4th parameters to the authorization
2834 ** callback function will be parameters or NULL depending on which of these
2835 ** codes is used as the second parameter.  ^(The 5th parameter to the
2836 ** authorizer callback is the name of the database ("main", "temp",
2837 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2838 ** is the name of the inner-most trigger or view that is responsible for
2839 ** the access attempt or NULL if this access attempt is directly from
2840 ** top-level SQL code.
2841 */
2842 /******************************************* 3rd ************ 4th ***********/
2843 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2844 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2845 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2846 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2847 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2848 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2849 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2850 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2851 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2852 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2853 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2854 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2855 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2856 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2857 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2858 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2859 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2860 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2861 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2862 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2863 #define SQLITE_SELECT               21   /* NULL            NULL            */
2864 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2865 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2866 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2867 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2868 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2869 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2870 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2871 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2872 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2873 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2874 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2875 #define SQLITE_COPY                  0   /* No longer used */
2876 #define SQLITE_RECURSIVE            33   /* NULL            NULL            */
2877 
2878 /*
2879 ** CAPI3REF: Tracing And Profiling Functions
2880 ** METHOD: sqlite3
2881 **
2882 ** These routines register callback functions that can be used for
2883 ** tracing and profiling the execution of SQL statements.
2884 **
2885 ** ^The callback function registered by sqlite3_trace() is invoked at
2886 ** various times when an SQL statement is being run by [sqlite3_step()].
2887 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2888 ** SQL statement text as the statement first begins executing.
2889 ** ^(Additional sqlite3_trace() callbacks might occur
2890 ** as each triggered subprogram is entered.  The callbacks for triggers
2891 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2892 **
2893 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
2894 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
2895 **
2896 ** ^The callback function registered by sqlite3_profile() is invoked
2897 ** as each SQL statement finishes.  ^The profile callback contains
2898 ** the original statement text and an estimate of wall-clock time
2899 ** of how long that statement took to run.  ^The profile callback
2900 ** time is in units of nanoseconds, however the current implementation
2901 ** is only capable of millisecond resolution so the six least significant
2902 ** digits in the time are meaningless.  Future versions of SQLite
2903 ** might provide greater resolution on the profiler callback.  The
2904 ** sqlite3_profile() function is considered experimental and is
2905 ** subject to change in future versions of SQLite.
2906 */
2907 SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2908 SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_profile(sqlite3*,
2909    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2910 
2911 /*
2912 ** CAPI3REF: Query Progress Callbacks
2913 ** METHOD: sqlite3
2914 **
2915 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2916 ** function X to be invoked periodically during long running calls to
2917 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2918 ** database connection D.  An example use for this
2919 ** interface is to keep a GUI updated during a large query.
2920 **
2921 ** ^The parameter P is passed through as the only parameter to the
2922 ** callback function X.  ^The parameter N is the approximate number of
2923 ** [virtual machine instructions] that are evaluated between successive
2924 ** invocations of the callback X.  ^If N is less than one then the progress
2925 ** handler is disabled.
2926 **
2927 ** ^Only a single progress handler may be defined at one time per
2928 ** [database connection]; setting a new progress handler cancels the
2929 ** old one.  ^Setting parameter X to NULL disables the progress handler.
2930 ** ^The progress handler is also disabled by setting N to a value less
2931 ** than 1.
2932 **
2933 ** ^If the progress callback returns non-zero, the operation is
2934 ** interrupted.  This feature can be used to implement a
2935 ** "Cancel" button on a GUI progress dialog box.
2936 **
2937 ** The progress handler callback must not do anything that will modify
2938 ** the database connection that invoked the progress handler.
2939 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2940 ** database connections for the meaning of "modify" in this paragraph.
2941 **
2942 */
2943 SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2944 
2945 /*
2946 ** CAPI3REF: Opening A New Database Connection
2947 ** CONSTRUCTOR: sqlite3
2948 **
2949 ** ^These routines open an SQLite database file as specified by the
2950 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2951 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2952 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2953 ** returned in *ppDb, even if an error occurs.  The only exception is that
2954 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2955 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2956 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2957 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2958 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2959 ** an English language description of the error following a failure of any
2960 ** of the sqlite3_open() routines.
2961 **
2962 ** ^The default encoding will be UTF-8 for databases created using
2963 ** sqlite3_open() or sqlite3_open_v2().  ^The default encoding for databases
2964 ** created using sqlite3_open16() will be UTF-16 in the native byte order.
2965 **
2966 ** Whether or not an error occurs when it is opened, resources
2967 ** associated with the [database connection] handle should be released by
2968 ** passing it to [sqlite3_close()] when it is no longer required.
2969 **
2970 ** The sqlite3_open_v2() interface works like sqlite3_open()
2971 ** except that it accepts two additional parameters for additional control
2972 ** over the new database connection.  ^(The flags parameter to
2973 ** sqlite3_open_v2() can take one of
2974 ** the following three values, optionally combined with the
2975 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2976 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
2977 **
2978 ** <dl>
2979 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2980 ** <dd>The database is opened in read-only mode.  If the database does not
2981 ** already exist, an error is returned.</dd>)^
2982 **
2983 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2984 ** <dd>The database is opened for reading and writing if possible, or reading
2985 ** only if the file is write protected by the operating system.  In either
2986 ** case the database must already exist, otherwise an error is returned.</dd>)^
2987 **
2988 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2989 ** <dd>The database is opened for reading and writing, and is created if
2990 ** it does not already exist. This is the behavior that is always used for
2991 ** sqlite3_open() and sqlite3_open16().</dd>)^
2992 ** </dl>
2993 **
2994 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2995 ** combinations shown above optionally combined with other
2996 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
2997 ** then the behavior is undefined.
2998 **
2999 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3000 ** opens in the multi-thread [threading mode] as long as the single-thread
3001 ** mode has not been set at compile-time or start-time.  ^If the
3002 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3003 ** in the serialized [threading mode] unless single-thread was
3004 ** previously selected at compile-time or start-time.
3005 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3006 ** eligible to use [shared cache mode], regardless of whether or not shared
3007 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
3008 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3009 ** participate in [shared cache mode] even if it is enabled.
3010 **
3011 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
3012 ** [sqlite3_vfs] object that defines the operating system interface that
3013 ** the new database connection should use.  ^If the fourth parameter is
3014 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3015 **
3016 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3017 ** is created for the connection.  ^This in-memory database will vanish when
3018 ** the database connection is closed.  Future versions of SQLite might
3019 ** make use of additional special filenames that begin with the ":" character.
3020 ** It is recommended that when a database filename actually does begin with
3021 ** a ":" character you should prefix the filename with a pathname such as
3022 ** "./" to avoid ambiguity.
3023 **
3024 ** ^If the filename is an empty string, then a private, temporary
3025 ** on-disk database will be created.  ^This private database will be
3026 ** automatically deleted as soon as the database connection is closed.
3027 **
3028 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3029 **
3030 ** ^If [URI filename] interpretation is enabled, and the filename argument
3031 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3032 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3033 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3034 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3035 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3036 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3037 ** by default, but future releases of SQLite might enable URI filename
3038 ** interpretation by default.  See "[URI filenames]" for additional
3039 ** information.
3040 **
3041 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3042 ** authority, then it must be either an empty string or the string
3043 ** "localhost". ^If the authority is not an empty string or "localhost", an
3044 ** error is returned to the caller. ^The fragment component of a URI, if
3045 ** present, is ignored.
3046 **
3047 ** ^SQLite uses the path component of the URI as the name of the disk file
3048 ** which contains the database. ^If the path begins with a '/' character,
3049 ** then it is interpreted as an absolute path. ^If the path does not begin
3050 ** with a '/' (meaning that the authority section is omitted from the URI)
3051 ** then the path is interpreted as a relative path.
3052 ** ^(On windows, the first component of an absolute path
3053 ** is a drive specification (e.g. "C:").)^
3054 **
3055 ** [[core URI query parameters]]
3056 ** The query component of a URI may contain parameters that are interpreted
3057 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3058 ** SQLite and its built-in [VFSes] interpret the
3059 ** following query parameters:
3060 **
3061 ** <ul>
3062 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3063 **     a VFS object that provides the operating system interface that should
3064 **     be used to access the database file on disk. ^If this option is set to
3065 **     an empty string the default VFS object is used. ^Specifying an unknown
3066 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3067 **     present, then the VFS specified by the option takes precedence over
3068 **     the value passed as the fourth parameter to sqlite3_open_v2().
3069 **
3070 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3071 **     "rwc", or "memory". Attempting to set it to any other value is
3072 **     an error)^.
3073 **     ^If "ro" is specified, then the database is opened for read-only
3074 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3075 **     third argument to sqlite3_open_v2(). ^If the mode option is set to
3076 **     "rw", then the database is opened for read-write (but not create)
3077 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3078 **     been set. ^Value "rwc" is equivalent to setting both
3079 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
3080 **     set to "memory" then a pure [in-memory database] that never reads
3081 **     or writes from disk is used. ^It is an error to specify a value for
3082 **     the mode parameter that is less restrictive than that specified by
3083 **     the flags passed in the third parameter to sqlite3_open_v2().
3084 **
3085 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3086 **     "private". ^Setting it to "shared" is equivalent to setting the
3087 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3088 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3089 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3090 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3091 **     a URI filename, its value overrides any behavior requested by setting
3092 **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3093 **
3094 **  <li> <b>psow</b>: ^The psow parameter indicates whether or not the
3095 **     [powersafe overwrite] property does or does not apply to the
3096 **     storage media on which the database file resides.
3097 **
3098 **  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
3099 **     which if set disables file locking in rollback journal modes.  This
3100 **     is useful for accessing a database on a filesystem that does not
3101 **     support locking.  Caution:  Database corruption might result if two
3102 **     or more processes write to the same database and any one of those
3103 **     processes uses nolock=1.
3104 **
3105 **  <li> <b>immutable</b>: ^The immutable parameter is a boolean query
3106 **     parameter that indicates that the database file is stored on
3107 **     read-only media.  ^When immutable is set, SQLite assumes that the
3108 **     database file cannot be changed, even by a process with higher
3109 **     privilege, and so the database is opened read-only and all locking
3110 **     and change detection is disabled.  Caution: Setting the immutable
3111 **     property on a database file that does in fact change can result
3112 **     in incorrect query results and/or [SQLITE_CORRUPT] errors.
3113 **     See also: [SQLITE_IOCAP_IMMUTABLE].
3114 **
3115 ** </ul>
3116 **
3117 ** ^Specifying an unknown parameter in the query component of a URI is not an
3118 ** error.  Future versions of SQLite might understand additional query
3119 ** parameters.  See "[query parameters with special meaning to SQLite]" for
3120 ** additional information.
3121 **
3122 ** [[URI filename examples]] <h3>URI filename examples</h3>
3123 **
3124 ** <table border="1" align=center cellpadding=5>
3125 ** <tr><th> URI filenames <th> Results
3126 ** <tr><td> file:data.db <td>
3127 **          Open the file "data.db" in the current directory.
3128 ** <tr><td> file:/home/fred/data.db<br>
3129 **          file:///home/fred/data.db <br>
3130 **          file://localhost/home/fred/data.db <br> <td>
3131 **          Open the database file "/home/fred/data.db".
3132 ** <tr><td> file://darkstar/home/fred/data.db <td>
3133 **          An error. "darkstar" is not a recognized authority.
3134 ** <tr><td style="white-space:nowrap">
3135 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3136 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3137 **          C:. Note that the %20 escaping in this example is not strictly
3138 **          necessary - space characters can be used literally
3139 **          in URI filenames.
3140 ** <tr><td> file:data.db?mode=ro&cache=private <td>
3141 **          Open file "data.db" in the current directory for read-only access.
3142 **          Regardless of whether or not shared-cache mode is enabled by
3143 **          default, use a private cache.
3144 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
3145 **          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
3146 **          that uses dot-files in place of posix advisory locking.
3147 ** <tr><td> file:data.db?mode=readonly <td>
3148 **          An error. "readonly" is not a valid option for the "mode" parameter.
3149 ** </table>
3150 **
3151 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3152 ** query components of a URI. A hexadecimal escape sequence consists of a
3153 ** percent sign - "%" - followed by exactly two hexadecimal digits
3154 ** specifying an octet value. ^Before the path or query components of a
3155 ** URI filename are interpreted, they are encoded using UTF-8 and all
3156 ** hexadecimal escape sequences replaced by a single byte containing the
3157 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3158 ** the results are undefined.
3159 **
3160 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
3161 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3162 ** codepage is currently defined.  Filenames containing international
3163 ** characters must be converted to UTF-8 prior to passing them into
3164 ** sqlite3_open() or sqlite3_open_v2().
3165 **
3166 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
3167 ** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
3168 ** features that require the use of temporary files may fail.
3169 **
3170 ** See also: [sqlite3_temp_directory]
3171 */
3172 SQLITE_API int SQLITE_STDCALL sqlite3_open(
3173   const char *filename,   /* Database filename (UTF-8) */
3174   sqlite3 **ppDb          /* OUT: SQLite db handle */
3175 );
3176 SQLITE_API int SQLITE_STDCALL sqlite3_open16(
3177   const void *filename,   /* Database filename (UTF-16) */
3178   sqlite3 **ppDb          /* OUT: SQLite db handle */
3179 );
3180 SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
3181   const char *filename,   /* Database filename (UTF-8) */
3182   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3183   int flags,              /* Flags */
3184   const char *zVfs        /* Name of VFS module to use */
3185 );
3186 
3187 /*
3188 ** CAPI3REF: Obtain Values For URI Parameters
3189 **
3190 ** These are utility routines, useful to VFS implementations, that check
3191 ** to see if a database file was a URI that contained a specific query
3192 ** parameter, and if so obtains the value of that query parameter.
3193 **
3194 ** If F is the database filename pointer passed into the xOpen() method of
3195 ** a VFS implementation when the flags parameter to xOpen() has one or
3196 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3197 ** P is the name of the query parameter, then
3198 ** sqlite3_uri_parameter(F,P) returns the value of the P
3199 ** parameter if it exists or a NULL pointer if P does not appear as a
3200 ** query parameter on F.  If P is a query parameter of F
3201 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3202 ** a pointer to an empty string.
3203 **
3204 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3205 ** parameter and returns true (1) or false (0) according to the value
3206 ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3207 ** value of query parameter P is one of "yes", "true", or "on" in any
3208 ** case or if the value begins with a non-zero number.  The
3209 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3210 ** query parameter P is one of "no", "false", or "off" in any case or
3211 ** if the value begins with a numeric zero.  If P is not a query
3212 ** parameter on F or if the value of P is does not match any of the
3213 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3214 **
3215 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3216 ** 64-bit signed integer and returns that integer, or D if P does not
3217 ** exist.  If the value of P is something other than an integer, then
3218 ** zero is returned.
3219 **
3220 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3221 ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3222 ** is not a database file pathname pointer that SQLite passed into the xOpen
3223 ** VFS method, then the behavior of this routine is undefined and probably
3224 ** undesirable.
3225 */
3226 SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3227 SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3228 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3229 
3230 
3231 /*
3232 ** CAPI3REF: Error Codes And Messages
3233 ** METHOD: sqlite3
3234 **
3235 ** ^If the most recent sqlite3_* API call associated with
3236 ** [database connection] D failed, then the sqlite3_errcode(D) interface
3237 ** returns the numeric [result code] or [extended result code] for that
3238 ** API call.
3239 ** If the most recent API call was successful,
3240 ** then the return value from sqlite3_errcode() is undefined.
3241 ** ^The sqlite3_extended_errcode()
3242 ** interface is the same except that it always returns the
3243 ** [extended result code] even when extended result codes are
3244 ** disabled.
3245 **
3246 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3247 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3248 ** ^(Memory to hold the error message string is managed internally.
3249 ** The application does not need to worry about freeing the result.
3250 ** However, the error string might be overwritten or deallocated by
3251 ** subsequent calls to other SQLite interface functions.)^
3252 **
3253 ** ^The sqlite3_errstr() interface returns the English-language text
3254 ** that describes the [result code], as UTF-8.
3255 ** ^(Memory to hold the error message string is managed internally
3256 ** and must not be freed by the application)^.
3257 **
3258 ** When the serialized [threading mode] is in use, it might be the
3259 ** case that a second error occurs on a separate thread in between
3260 ** the time of the first error and the call to these interfaces.
3261 ** When that happens, the second error will be reported since these
3262 ** interfaces always report the most recent result.  To avoid
3263 ** this, each thread can obtain exclusive use of the [database connection] D
3264 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3265 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3266 ** all calls to the interfaces listed here are completed.
3267 **
3268 ** If an interface fails with SQLITE_MISUSE, that means the interface
3269 ** was invoked incorrectly by the application.  In that case, the
3270 ** error code and message may or may not be set.
3271 */
3272 SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db);
3273 SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db);
3274 SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3*);
3275 SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3*);
3276 SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int);
3277 
3278 /*
3279 ** CAPI3REF: Prepared Statement Object
3280 ** KEYWORDS: {prepared statement} {prepared statements}
3281 **
3282 ** An instance of this object represents a single SQL statement that
3283 ** has been compiled into binary form and is ready to be evaluated.
3284 **
3285 ** Think of each SQL statement as a separate computer program.  The
3286 ** original SQL text is source code.  A prepared statement object
3287 ** is the compiled object code.  All SQL must be converted into a
3288 ** prepared statement before it can be run.
3289 **
3290 ** The life-cycle of a prepared statement object usually goes like this:
3291 **
3292 ** <ol>
3293 ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
3294 ** <li> Bind values to [parameters] using the sqlite3_bind_*()
3295 **      interfaces.
3296 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3297 ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
3298 **      to step 2.  Do this zero or more times.
3299 ** <li> Destroy the object using [sqlite3_finalize()].
3300 ** </ol>
3301 */
3302 typedef struct sqlite3_stmt sqlite3_stmt;
3303 
3304 /*
3305 ** CAPI3REF: Run-time Limits
3306 ** METHOD: sqlite3
3307 **
3308 ** ^(This interface allows the size of various constructs to be limited
3309 ** on a connection by connection basis.  The first parameter is the
3310 ** [database connection] whose limit is to be set or queried.  The
3311 ** second parameter is one of the [limit categories] that define a
3312 ** class of constructs to be size limited.  The third parameter is the
3313 ** new limit for that construct.)^
3314 **
3315 ** ^If the new limit is a negative number, the limit is unchanged.
3316 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3317 ** [limits | hard upper bound]
3318 ** set at compile-time by a C preprocessor macro called
3319 ** [limits | SQLITE_MAX_<i>NAME</i>].
3320 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3321 ** ^Attempts to increase a limit above its hard upper bound are
3322 ** silently truncated to the hard upper bound.
3323 **
3324 ** ^Regardless of whether or not the limit was changed, the
3325 ** [sqlite3_limit()] interface returns the prior value of the limit.
3326 ** ^Hence, to find the current value of a limit without changing it,
3327 ** simply invoke this interface with the third parameter set to -1.
3328 **
3329 ** Run-time limits are intended for use in applications that manage
3330 ** both their own internal database and also databases that are controlled
3331 ** by untrusted external sources.  An example application might be a
3332 ** web browser that has its own databases for storing history and
3333 ** separate databases controlled by JavaScript applications downloaded
3334 ** off the Internet.  The internal databases can be given the
3335 ** large, default limits.  Databases managed by external sources can
3336 ** be given much smaller limits designed to prevent a denial of service
3337 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3338 ** interface to further control untrusted SQL.  The size of the database
3339 ** created by an untrusted script can be contained using the
3340 ** [max_page_count] [PRAGMA].
3341 **
3342 ** New run-time limit categories may be added in future releases.
3343 */
3344 SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3*, int id, int newVal);
3345 
3346 /*
3347 ** CAPI3REF: Run-Time Limit Categories
3348 ** KEYWORDS: {limit category} {*limit categories}
3349 **
3350 ** These constants define various performance limits
3351 ** that can be lowered at run-time using [sqlite3_limit()].
3352 ** The synopsis of the meanings of the various limits is shown below.
3353 ** Additional information is available at [limits | Limits in SQLite].
3354 **
3355 ** <dl>
3356 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3357 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3358 **
3359 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3360 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3361 **
3362 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3363 ** <dd>The maximum number of columns in a table definition or in the
3364 ** result set of a [SELECT] or the maximum number of columns in an index
3365 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3366 **
3367 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3368 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3369 **
3370 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3371 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3372 **
3373 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3374 ** <dd>The maximum number of instructions in a virtual machine program
3375 ** used to implement an SQL statement.  This limit is not currently
3376 ** enforced, though that might be added in some future release of
3377 ** SQLite.</dd>)^
3378 **
3379 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3380 ** <dd>The maximum number of arguments on a function.</dd>)^
3381 **
3382 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3383 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3384 **
3385 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3386 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3387 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3388 ** [GLOB] operators.</dd>)^
3389 **
3390 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3391 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3392 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3393 **
3394 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3395 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3396 **
3397 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
3398 ** <dd>The maximum number of auxiliary worker threads that a single
3399 ** [prepared statement] may start.</dd>)^
3400 ** </dl>
3401 */
3402 #define SQLITE_LIMIT_LENGTH                    0
3403 #define SQLITE_LIMIT_SQL_LENGTH                1
3404 #define SQLITE_LIMIT_COLUMN                    2
3405 #define SQLITE_LIMIT_EXPR_DEPTH                3
3406 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3407 #define SQLITE_LIMIT_VDBE_OP                   5
3408 #define SQLITE_LIMIT_FUNCTION_ARG              6
3409 #define SQLITE_LIMIT_ATTACHED                  7
3410 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3411 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3412 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3413 #define SQLITE_LIMIT_WORKER_THREADS           11
3414 
3415 /*
3416 ** CAPI3REF: Compiling An SQL Statement
3417 ** KEYWORDS: {SQL statement compiler}
3418 ** METHOD: sqlite3
3419 ** CONSTRUCTOR: sqlite3_stmt
3420 **
3421 ** To execute an SQL query, it must first be compiled into a byte-code
3422 ** program using one of these routines.
3423 **
3424 ** The first argument, "db", is a [database connection] obtained from a
3425 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3426 ** [sqlite3_open16()].  The database connection must not have been closed.
3427 **
3428 ** The second argument, "zSql", is the statement to be compiled, encoded
3429 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3430 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3431 ** use UTF-16.
3432 **
3433 ** ^If the nByte argument is negative, then zSql is read up to the
3434 ** first zero terminator. ^If nByte is positive, then it is the
3435 ** number of bytes read from zSql.  ^If nByte is zero, then no prepared
3436 ** statement is generated.
3437 ** If the caller knows that the supplied string is nul-terminated, then
3438 ** there is a small performance advantage to passing an nByte parameter that
3439 ** is the number of bytes in the input string <i>including</i>
3440 ** the nul-terminator.
3441 **
3442 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3443 ** past the end of the first SQL statement in zSql.  These routines only
3444 ** compile the first statement in zSql, so *pzTail is left pointing to
3445 ** what remains uncompiled.
3446 **
3447 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3448 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3449 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3450 ** string or a comment) then *ppStmt is set to NULL.
3451 ** The calling procedure is responsible for deleting the compiled
3452 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3453 ** ppStmt may not be NULL.
3454 **
3455 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3456 ** otherwise an [error code] is returned.
3457 **
3458 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3459 ** recommended for all new programs. The two older interfaces are retained
3460 ** for backwards compatibility, but their use is discouraged.
3461 ** ^In the "v2" interfaces, the prepared statement
3462 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3463 ** original SQL text. This causes the [sqlite3_step()] interface to
3464 ** behave differently in three ways:
3465 **
3466 ** <ol>
3467 ** <li>
3468 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3469 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3470 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3471 ** retries will occur before sqlite3_step() gives up and returns an error.
3472 ** </li>
3473 **
3474 ** <li>
3475 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3476 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3477 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3478 ** and the application would have to make a second call to [sqlite3_reset()]
3479 ** in order to find the underlying cause of the problem. With the "v2" prepare
3480 ** interfaces, the underlying reason for the error is returned immediately.
3481 ** </li>
3482 **
3483 ** <li>
3484 ** ^If the specific value bound to [parameter | host parameter] in the
3485 ** WHERE clause might influence the choice of query plan for a statement,
3486 ** then the statement will be automatically recompiled, as if there had been
3487 ** a schema change, on the first  [sqlite3_step()] call following any change
3488 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3489 ** ^The specific value of WHERE-clause [parameter] might influence the
3490 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3491 ** or [GLOB] operator or if the parameter is compared to an indexed column
3492 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3493 ** </li>
3494 ** </ol>
3495 */
3496 SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
3497   sqlite3 *db,            /* Database handle */
3498   const char *zSql,       /* SQL statement, UTF-8 encoded */
3499   int nByte,              /* Maximum length of zSql in bytes. */
3500   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3501   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3502 );
3503 SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
3504   sqlite3 *db,            /* Database handle */
3505   const char *zSql,       /* SQL statement, UTF-8 encoded */
3506   int nByte,              /* Maximum length of zSql in bytes. */
3507   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3508   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3509 );
3510 SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
3511   sqlite3 *db,            /* Database handle */
3512   const void *zSql,       /* SQL statement, UTF-16 encoded */
3513   int nByte,              /* Maximum length of zSql in bytes. */
3514   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3515   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3516 );
3517 SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
3518   sqlite3 *db,            /* Database handle */
3519   const void *zSql,       /* SQL statement, UTF-16 encoded */
3520   int nByte,              /* Maximum length of zSql in bytes. */
3521   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3522   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3523 );
3524 
3525 /*
3526 ** CAPI3REF: Retrieving Statement SQL
3527 ** METHOD: sqlite3_stmt
3528 **
3529 ** ^This interface can be used to retrieve a saved copy of the original
3530 ** SQL text used to create a [prepared statement] if that statement was
3531 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3532 */
3533 SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt);
3534 
3535 /*
3536 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3537 ** METHOD: sqlite3_stmt
3538 **
3539 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3540 ** and only if the [prepared statement] X makes no direct changes to
3541 ** the content of the database file.
3542 **
3543 ** Note that [application-defined SQL functions] or
3544 ** [virtual tables] might change the database indirectly as a side effect.
3545 ** ^(For example, if an application defines a function "eval()" that
3546 ** calls [sqlite3_exec()], then the following SQL statement would
3547 ** change the database file through side-effects:
3548 **
3549 ** <blockquote><pre>
3550 **    SELECT eval('DELETE FROM t1') FROM t2;
3551 ** </pre></blockquote>
3552 **
3553 ** But because the [SELECT] statement does not change the database file
3554 ** directly, sqlite3_stmt_readonly() would still return true.)^
3555 **
3556 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3557 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3558 ** since the statements themselves do not actually modify the database but
3559 ** rather they control the timing of when other statements modify the
3560 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3561 ** sqlite3_stmt_readonly() to return true since, while those statements
3562 ** change the configuration of a database connection, they do not make
3563 ** changes to the content of the database files on disk.
3564 */
3565 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3566 
3567 /*
3568 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3569 ** METHOD: sqlite3_stmt
3570 **
3571 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3572 ** [prepared statement] S has been stepped at least once using
3573 ** [sqlite3_step(S)] but has not run to completion and/or has not
3574 ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3575 ** interface returns false if S is a NULL pointer.  If S is not a
3576 ** NULL pointer and is not a pointer to a valid [prepared statement]
3577 ** object, then the behavior is undefined and probably undesirable.
3578 **
3579 ** This interface can be used in combination [sqlite3_next_stmt()]
3580 ** to locate all prepared statements associated with a database
3581 ** connection that are in need of being reset.  This can be used,
3582 ** for example, in diagnostic routines to search for prepared
3583 ** statements that are holding a transaction open.
3584 */
3585 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt*);
3586 
3587 /*
3588 ** CAPI3REF: Dynamically Typed Value Object
3589 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3590 **
3591 ** SQLite uses the sqlite3_value object to represent all values
3592 ** that can be stored in a database table. SQLite uses dynamic typing
3593 ** for the values it stores.  ^Values stored in sqlite3_value objects
3594 ** can be integers, floating point values, strings, BLOBs, or NULL.
3595 **
3596 ** An sqlite3_value object may be either "protected" or "unprotected".
3597 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3598 ** will accept either a protected or an unprotected sqlite3_value.
3599 ** Every interface that accepts sqlite3_value arguments specifies
3600 ** whether or not it requires a protected sqlite3_value.
3601 **
3602 ** The terms "protected" and "unprotected" refer to whether or not
3603 ** a mutex is held.  An internal mutex is held for a protected
3604 ** sqlite3_value object but no mutex is held for an unprotected
3605 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3606 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3607 ** or if SQLite is run in one of reduced mutex modes
3608 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3609 ** then there is no distinction between protected and unprotected
3610 ** sqlite3_value objects and they can be used interchangeably.  However,
3611 ** for maximum code portability it is recommended that applications
3612 ** still make the distinction between protected and unprotected
3613 ** sqlite3_value objects even when not strictly required.
3614 **
3615 ** ^The sqlite3_value objects that are passed as parameters into the
3616 ** implementation of [application-defined SQL functions] are protected.
3617 ** ^The sqlite3_value object returned by
3618 ** [sqlite3_column_value()] is unprotected.
3619 ** Unprotected sqlite3_value objects may only be used with
3620 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3621 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3622 ** interfaces require protected sqlite3_value objects.
3623 */
3624 typedef struct Mem sqlite3_value;
3625 
3626 /*
3627 ** CAPI3REF: SQL Function Context Object
3628 **
3629 ** The context in which an SQL function executes is stored in an
3630 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3631 ** is always first parameter to [application-defined SQL functions].
3632 ** The application-defined SQL function implementation will pass this
3633 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3634 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3635 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3636 ** and/or [sqlite3_set_auxdata()].
3637 */
3638 typedef struct sqlite3_context sqlite3_context;
3639 
3640 /*
3641 ** CAPI3REF: Binding Values To Prepared Statements
3642 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3643 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3644 ** METHOD: sqlite3_stmt
3645 **
3646 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3647 ** literals may be replaced by a [parameter] that matches one of following
3648 ** templates:
3649 **
3650 ** <ul>
3651 ** <li>  ?
3652 ** <li>  ?NNN
3653 ** <li>  :VVV
3654 ** <li>  @VVV
3655 ** <li>  $VVV
3656 ** </ul>
3657 **
3658 ** In the templates above, NNN represents an integer literal,
3659 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3660 ** parameters (also called "host parameter names" or "SQL parameters")
3661 ** can be set using the sqlite3_bind_*() routines defined here.
3662 **
3663 ** ^The first argument to the sqlite3_bind_*() routines is always
3664 ** a pointer to the [sqlite3_stmt] object returned from
3665 ** [sqlite3_prepare_v2()] or its variants.
3666 **
3667 ** ^The second argument is the index of the SQL parameter to be set.
3668 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3669 ** SQL parameter is used more than once, second and subsequent
3670 ** occurrences have the same index as the first occurrence.
3671 ** ^The index for named parameters can be looked up using the
3672 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3673 ** for "?NNN" parameters is the value of NNN.
3674 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3675 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3676 **
3677 ** ^The third argument is the value to bind to the parameter.
3678 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3679 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3680 ** is ignored and the end result is the same as sqlite3_bind_null().
3681 **
3682 ** ^(In those routines that have a fourth argument, its value is the
3683 ** number of bytes in the parameter.  To be clear: the value is the
3684 ** number of <u>bytes</u> in the value, not the number of characters.)^
3685 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3686 ** is negative, then the length of the string is
3687 ** the number of bytes up to the first zero terminator.
3688 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
3689 ** the behavior is undefined.
3690 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3691 ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
3692 ** that parameter must be the byte offset
3693 ** where the NUL terminator would occur assuming the string were NUL
3694 ** terminated.  If any NUL characters occur at byte offsets less than
3695 ** the value of the fourth parameter then the resulting string value will
3696 ** contain embedded NULs.  The result of expressions involving strings
3697 ** with embedded NULs is undefined.
3698 **
3699 ** ^The fifth argument to the BLOB and string binding interfaces
3700 ** is a destructor used to dispose of the BLOB or
3701 ** string after SQLite has finished with it.  ^The destructor is called
3702 ** to dispose of the BLOB or string even if the call to bind API fails.
3703 ** ^If the fifth argument is
3704 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3705 ** information is in static, unmanaged space and does not need to be freed.
3706 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3707 ** SQLite makes its own private copy of the data immediately, before
3708 ** the sqlite3_bind_*() routine returns.
3709 **
3710 ** ^The sixth argument to sqlite3_bind_text64() must be one of
3711 ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
3712 ** to specify the encoding of the text in the third parameter.  If
3713 ** the sixth argument to sqlite3_bind_text64() is not one of the
3714 ** allowed values shown above, or if the text encoding is different
3715 ** from the encoding specified by the sixth parameter, then the behavior
3716 ** is undefined.
3717 **
3718 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3719 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3720 ** (just an integer to hold its size) while it is being processed.
3721 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3722 ** content is later written using
3723 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3724 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3725 **
3726 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3727 ** for the [prepared statement] or with a prepared statement for which
3728 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3729 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3730 ** routine is passed a [prepared statement] that has been finalized, the
3731 ** result is undefined and probably harmful.
3732 **
3733 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3734 ** ^Unbound parameters are interpreted as NULL.
3735 **
3736 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3737 ** [error code] if anything goes wrong.
3738 ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
3739 ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
3740 ** [SQLITE_MAX_LENGTH].
3741 ** ^[SQLITE_RANGE] is returned if the parameter
3742 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3743 **
3744 ** See also: [sqlite3_bind_parameter_count()],
3745 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3746 */
3747 SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3748 SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
3749                         void(*)(void*));
3750 SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt*, int, double);
3751 SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt*, int, int);
3752 SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3753 SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt*, int);
3754 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
3755 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3756 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
3757                          void(*)(void*), unsigned char encoding);
3758 SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3759 SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3760 
3761 /*
3762 ** CAPI3REF: Number Of SQL Parameters
3763 ** METHOD: sqlite3_stmt
3764 **
3765 ** ^This routine can be used to find the number of [SQL parameters]
3766 ** in a [prepared statement].  SQL parameters are tokens of the
3767 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3768 ** placeholders for values that are [sqlite3_bind_blob | bound]
3769 ** to the parameters at a later time.
3770 **
3771 ** ^(This routine actually returns the index of the largest (rightmost)
3772 ** parameter. For all forms except ?NNN, this will correspond to the
3773 ** number of unique parameters.  If parameters of the ?NNN form are used,
3774 ** there may be gaps in the list.)^
3775 **
3776 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3777 ** [sqlite3_bind_parameter_name()], and
3778 ** [sqlite3_bind_parameter_index()].
3779 */
3780 SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt*);
3781 
3782 /*
3783 ** CAPI3REF: Name Of A Host Parameter
3784 ** METHOD: sqlite3_stmt
3785 **
3786 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3787 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3788 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3789 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3790 ** respectively.
3791 ** In other words, the initial ":" or "$" or "@" or "?"
3792 ** is included as part of the name.)^
3793 ** ^Parameters of the form "?" without a following integer have no name
3794 ** and are referred to as "nameless" or "anonymous parameters".
3795 **
3796 ** ^The first host parameter has an index of 1, not 0.
3797 **
3798 ** ^If the value N is out of range or if the N-th parameter is
3799 ** nameless, then NULL is returned.  ^The returned string is
3800 ** always in UTF-8 encoding even if the named parameter was
3801 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3802 ** [sqlite3_prepare16_v2()].
3803 **
3804 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3805 ** [sqlite3_bind_parameter_count()], and
3806 ** [sqlite3_bind_parameter_index()].
3807 */
3808 SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3809 
3810 /*
3811 ** CAPI3REF: Index Of A Parameter With A Given Name
3812 ** METHOD: sqlite3_stmt
3813 **
3814 ** ^Return the index of an SQL parameter given its name.  ^The
3815 ** index value returned is suitable for use as the second
3816 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3817 ** is returned if no matching parameter is found.  ^The parameter
3818 ** name must be given in UTF-8 even if the original statement
3819 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3820 **
3821 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3822 ** [sqlite3_bind_parameter_count()], and
3823 ** [sqlite3_bind_parameter_index()].
3824 */
3825 SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3826 
3827 /*
3828 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3829 ** METHOD: sqlite3_stmt
3830 **
3831 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3832 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3833 ** ^Use this routine to reset all host parameters to NULL.
3834 */
3835 SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt*);
3836 
3837 /*
3838 ** CAPI3REF: Number Of Columns In A Result Set
3839 ** METHOD: sqlite3_stmt
3840 **
3841 ** ^Return the number of columns in the result set returned by the
3842 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3843 ** statement that does not return data (for example an [UPDATE]).
3844 **
3845 ** See also: [sqlite3_data_count()]
3846 */
3847 SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt);
3848 
3849 /*
3850 ** CAPI3REF: Column Names In A Result Set
3851 ** METHOD: sqlite3_stmt
3852 **
3853 ** ^These routines return the name assigned to a particular column
3854 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3855 ** interface returns a pointer to a zero-terminated UTF-8 string
3856 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3857 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3858 ** that implements the [SELECT] statement. ^The second parameter is the
3859 ** column number.  ^The leftmost column is number 0.
3860 **
3861 ** ^The returned string pointer is valid until either the [prepared statement]
3862 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3863 ** reprepared by the first call to [sqlite3_step()] for a particular run
3864 ** or until the next call to
3865 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3866 **
3867 ** ^If sqlite3_malloc() fails during the processing of either routine
3868 ** (for example during a conversion from UTF-8 to UTF-16) then a
3869 ** NULL pointer is returned.
3870 **
3871 ** ^The name of a result column is the value of the "AS" clause for
3872 ** that column, if there is an AS clause.  If there is no AS clause
3873 ** then the name of the column is unspecified and may change from
3874 ** one release of SQLite to the next.
3875 */
3876 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt*, int N);
3877 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt*, int N);
3878 
3879 /*
3880 ** CAPI3REF: Source Of Data In A Query Result
3881 ** METHOD: sqlite3_stmt
3882 **
3883 ** ^These routines provide a means to determine the database, table, and
3884 ** table column that is the origin of a particular result column in
3885 ** [SELECT] statement.
3886 ** ^The name of the database or table or column can be returned as
3887 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3888 ** the database name, the _table_ routines return the table name, and
3889 ** the origin_ routines return the column name.
3890 ** ^The returned string is valid until the [prepared statement] is destroyed
3891 ** using [sqlite3_finalize()] or until the statement is automatically
3892 ** reprepared by the first call to [sqlite3_step()] for a particular run
3893 ** or until the same information is requested
3894 ** again in a different encoding.
3895 **
3896 ** ^The names returned are the original un-aliased names of the
3897 ** database, table, and column.
3898 **
3899 ** ^The first argument to these interfaces is a [prepared statement].
3900 ** ^These functions return information about the Nth result column returned by
3901 ** the statement, where N is the second function argument.
3902 ** ^The left-most column is column 0 for these routines.
3903 **
3904 ** ^If the Nth column returned by the statement is an expression or
3905 ** subquery and is not a column value, then all of these functions return
3906 ** NULL.  ^These routine might also return NULL if a memory allocation error
3907 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3908 ** or column that query result column was extracted from.
3909 **
3910 ** ^As with all other SQLite APIs, those whose names end with "16" return
3911 ** UTF-16 encoded strings and the other functions return UTF-8.
3912 **
3913 ** ^These APIs are only available if the library was compiled with the
3914 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3915 **
3916 ** If two or more threads call one or more of these routines against the same
3917 ** prepared statement and column at the same time then the results are
3918 ** undefined.
3919 **
3920 ** If two or more threads call one or more
3921 ** [sqlite3_column_database_name | column metadata interfaces]
3922 ** for the same [prepared statement] and result column
3923 ** at the same time then the results are undefined.
3924 */
3925 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt*,int);
3926 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt*,int);
3927 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt*,int);
3928 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt*,int);
3929 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt*,int);
3930 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt*,int);
3931 
3932 /*
3933 ** CAPI3REF: Declared Datatype Of A Query Result
3934 ** METHOD: sqlite3_stmt
3935 **
3936 ** ^(The first parameter is a [prepared statement].
3937 ** If this statement is a [SELECT] statement and the Nth column of the
3938 ** returned result set of that [SELECT] is a table column (not an
3939 ** expression or subquery) then the declared type of the table
3940 ** column is returned.)^  ^If the Nth column of the result set is an
3941 ** expression or subquery, then a NULL pointer is returned.
3942 ** ^The returned string is always UTF-8 encoded.
3943 **
3944 ** ^(For example, given the database schema:
3945 **
3946 ** CREATE TABLE t1(c1 VARIANT);
3947 **
3948 ** and the following statement to be compiled:
3949 **
3950 ** SELECT c1 + 1, c1 FROM t1;
3951 **
3952 ** this routine would return the string "VARIANT" for the second result
3953 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3954 **
3955 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3956 ** is declared to contain a particular type does not mean that the
3957 ** data stored in that column is of the declared type.  SQLite is
3958 ** strongly typed, but the typing is dynamic not static.  ^Type
3959 ** is associated with individual values, not with the containers
3960 ** used to hold those values.
3961 */
3962 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt*,int);
3963 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt*,int);
3964 
3965 /*
3966 ** CAPI3REF: Evaluate An SQL Statement
3967 ** METHOD: sqlite3_stmt
3968 **
3969 ** After a [prepared statement] has been prepared using either
3970 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3971 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3972 ** must be called one or more times to evaluate the statement.
3973 **
3974 ** The details of the behavior of the sqlite3_step() interface depend
3975 ** on whether the statement was prepared using the newer "v2" interface
3976 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3977 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3978 ** new "v2" interface is recommended for new applications but the legacy
3979 ** interface will continue to be supported.
3980 **
3981 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3982 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3983 ** ^With the "v2" interface, any of the other [result codes] or
3984 ** [extended result codes] might be returned as well.
3985 **
3986 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3987 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3988 ** or occurs outside of an explicit transaction, then you can retry the
3989 ** statement.  If the statement is not a [COMMIT] and occurs within an
3990 ** explicit transaction then you should rollback the transaction before
3991 ** continuing.
3992 **
3993 ** ^[SQLITE_DONE] means that the statement has finished executing
3994 ** successfully.  sqlite3_step() should not be called again on this virtual
3995 ** machine without first calling [sqlite3_reset()] to reset the virtual
3996 ** machine back to its initial state.
3997 **
3998 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3999 ** is returned each time a new row of data is ready for processing by the
4000 ** caller. The values may be accessed using the [column access functions].
4001 ** sqlite3_step() is called again to retrieve the next row of data.
4002 **
4003 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4004 ** violation) has occurred.  sqlite3_step() should not be called again on
4005 ** the VM. More information may be found by calling [sqlite3_errmsg()].
4006 ** ^With the legacy interface, a more specific error code (for example,
4007 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4008 ** can be obtained by calling [sqlite3_reset()] on the
4009 ** [prepared statement].  ^In the "v2" interface,
4010 ** the more specific error code is returned directly by sqlite3_step().
4011 **
4012 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4013 ** Perhaps it was called on a [prepared statement] that has
4014 ** already been [sqlite3_finalize | finalized] or on one that had
4015 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
4016 ** be the case that the same database connection is being used by two or
4017 ** more threads at the same moment in time.
4018 **
4019 ** For all versions of SQLite up to and including 3.6.23.1, a call to
4020 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
4021 ** other than [SQLITE_ROW] before any subsequent invocation of
4022 ** sqlite3_step().  Failure to reset the prepared statement using
4023 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4024 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
4025 ** calling [sqlite3_reset()] automatically in this circumstance rather
4026 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
4027 ** break because any application that ever receives an SQLITE_MISUSE error
4028 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
4029 ** can be used to restore the legacy behavior.
4030 **
4031 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4032 ** API always returns a generic error code, [SQLITE_ERROR], following any
4033 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4034 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4035 ** specific [error codes] that better describes the error.
4036 ** We admit that this is a goofy design.  The problem has been fixed
4037 ** with the "v2" interface.  If you prepare all of your SQL statements
4038 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4039 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4040 ** then the more specific [error codes] are returned directly
4041 ** by sqlite3_step().  The use of the "v2" interface is recommended.
4042 */
4043 SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt*);
4044 
4045 /*
4046 ** CAPI3REF: Number of columns in a result set
4047 ** METHOD: sqlite3_stmt
4048 **
4049 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
4050 ** current row of the result set of [prepared statement] P.
4051 ** ^If prepared statement P does not have results ready to return
4052 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4053 ** interfaces) then sqlite3_data_count(P) returns 0.
4054 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4055 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4056 ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
4057 ** will return non-zero if previous call to [sqlite3_step](P) returned
4058 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4059 ** where it always returns zero since each step of that multi-step
4060 ** pragma returns 0 columns of data.
4061 **
4062 ** See also: [sqlite3_column_count()]
4063 */
4064 SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt);
4065 
4066 /*
4067 ** CAPI3REF: Fundamental Datatypes
4068 ** KEYWORDS: SQLITE_TEXT
4069 **
4070 ** ^(Every value in SQLite has one of five fundamental datatypes:
4071 **
4072 ** <ul>
4073 ** <li> 64-bit signed integer
4074 ** <li> 64-bit IEEE floating point number
4075 ** <li> string
4076 ** <li> BLOB
4077 ** <li> NULL
4078 ** </ul>)^
4079 **
4080 ** These constants are codes for each of those types.
4081 **
4082 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4083 ** for a completely different meaning.  Software that links against both
4084 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4085 ** SQLITE_TEXT.
4086 */
4087 #define SQLITE_INTEGER  1
4088 #define SQLITE_FLOAT    2
4089 #define SQLITE_BLOB     4
4090 #define SQLITE_NULL     5
4091 #ifdef SQLITE_TEXT
4092 # undef SQLITE_TEXT
4093 #else
4094 # define SQLITE_TEXT     3
4095 #endif
4096 #define SQLITE3_TEXT     3
4097 
4098 /*
4099 ** CAPI3REF: Result Values From A Query
4100 ** KEYWORDS: {column access functions}
4101 ** METHOD: sqlite3_stmt
4102 **
4103 ** These routines form the "result set" interface.
4104 **
4105 ** ^These routines return information about a single column of the current
4106 ** result row of a query.  ^In every case the first argument is a pointer
4107 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4108 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4109 ** and the second argument is the index of the column for which information
4110 ** should be returned. ^The leftmost column of the result set has the index 0.
4111 ** ^The number of columns in the result can be determined using
4112 ** [sqlite3_column_count()].
4113 **
4114 ** If the SQL statement does not currently point to a valid row, or if the
4115 ** column index is out of range, the result is undefined.
4116 ** These routines may only be called when the most recent call to
4117 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4118 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4119 ** If any of these routines are called after [sqlite3_reset()] or
4120 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4121 ** something other than [SQLITE_ROW], the results are undefined.
4122 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4123 ** are called from a different thread while any of these routines
4124 ** are pending, then the results are undefined.
4125 **
4126 ** ^The sqlite3_column_type() routine returns the
4127 ** [SQLITE_INTEGER | datatype code] for the initial data type
4128 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
4129 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4130 ** returned by sqlite3_column_type() is only meaningful if no type
4131 ** conversions have occurred as described below.  After a type conversion,
4132 ** the value returned by sqlite3_column_type() is undefined.  Future
4133 ** versions of SQLite may change the behavior of sqlite3_column_type()
4134 ** following a type conversion.
4135 **
4136 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4137 ** routine returns the number of bytes in that BLOB or string.
4138 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4139 ** the string to UTF-8 and then returns the number of bytes.
4140 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
4141 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4142 ** the number of bytes in that string.
4143 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4144 **
4145 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4146 ** routine returns the number of bytes in that BLOB or string.
4147 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4148 ** the string to UTF-16 and then returns the number of bytes.
4149 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4150 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4151 ** the number of bytes in that string.
4152 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4153 **
4154 ** ^The values returned by [sqlite3_column_bytes()] and
4155 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4156 ** of the string.  ^For clarity: the values returned by
4157 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4158 ** bytes in the string, not the number of characters.
4159 **
4160 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4161 ** even empty strings, are always zero-terminated.  ^The return
4162 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4163 **
4164 ** ^The object returned by [sqlite3_column_value()] is an
4165 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4166 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4167 ** If the [unprotected sqlite3_value] object returned by
4168 ** [sqlite3_column_value()] is used in any other way, including calls
4169 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4170 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4171 **
4172 ** These routines attempt to convert the value where appropriate.  ^For
4173 ** example, if the internal representation is FLOAT and a text result
4174 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4175 ** conversion automatically.  ^(The following table details the conversions
4176 ** that are applied:
4177 **
4178 ** <blockquote>
4179 ** <table border="1">
4180 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4181 **
4182 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4183 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4184 ** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
4185 ** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
4186 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4187 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4188 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4189 ** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
4190 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4191 ** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
4192 ** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
4193 ** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
4194 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4195 ** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
4196 ** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
4197 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4198 ** </table>
4199 ** </blockquote>)^
4200 **
4201 ** The table above makes reference to standard C library functions atoi()
4202 ** and atof().  SQLite does not really use these functions.  It has its
4203 ** own equivalent internal routines.  The atoi() and atof() names are
4204 ** used in the table for brevity and because they are familiar to most
4205 ** C programmers.
4206 **
4207 ** Note that when type conversions occur, pointers returned by prior
4208 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4209 ** sqlite3_column_text16() may be invalidated.
4210 ** Type conversions and pointer invalidations might occur
4211 ** in the following cases:
4212 **
4213 ** <ul>
4214 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4215 **      sqlite3_column_text16() is called.  A zero-terminator might
4216 **      need to be added to the string.</li>
4217 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4218 **      sqlite3_column_text16() is called.  The content must be converted
4219 **      to UTF-16.</li>
4220 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4221 **      sqlite3_column_text() is called.  The content must be converted
4222 **      to UTF-8.</li>
4223 ** </ul>
4224 **
4225 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4226 ** not invalidate a prior pointer, though of course the content of the buffer
4227 ** that the prior pointer references will have been modified.  Other kinds
4228 ** of conversion are done in place when it is possible, but sometimes they
4229 ** are not possible and in those cases prior pointers are invalidated.
4230 **
4231 ** The safest and easiest to remember policy is to invoke these routines
4232 ** in one of the following ways:
4233 **
4234 ** <ul>
4235 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4236 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4237 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4238 ** </ul>
4239 **
4240 ** In other words, you should call sqlite3_column_text(),
4241 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4242 ** into the desired format, then invoke sqlite3_column_bytes() or
4243 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4244 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4245 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4246 ** with calls to sqlite3_column_bytes().
4247 **
4248 ** ^The pointers returned are valid until a type conversion occurs as
4249 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4250 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4251 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4252 ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4253 ** [sqlite3_free()].
4254 **
4255 ** ^(If a memory allocation error occurs during the evaluation of any
4256 ** of these routines, a default value is returned.  The default value
4257 ** is either the integer 0, the floating point number 0.0, or a NULL
4258 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4259 ** [SQLITE_NOMEM].)^
4260 */
4261 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt*, int iCol);
4262 SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4263 SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4264 SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt*, int iCol);
4265 SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt*, int iCol);
4266 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt*, int iCol);
4267 SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt*, int iCol);
4268 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt*, int iCol);
4269 SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt*, int iCol);
4270 SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt*, int iCol);
4271 
4272 /*
4273 ** CAPI3REF: Destroy A Prepared Statement Object
4274 ** DESTRUCTOR: sqlite3_stmt
4275 **
4276 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4277 ** ^If the most recent evaluation of the statement encountered no errors
4278 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4279 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4280 ** sqlite3_finalize(S) returns the appropriate [error code] or
4281 ** [extended error code].
4282 **
4283 ** ^The sqlite3_finalize(S) routine can be called at any point during
4284 ** the life cycle of [prepared statement] S:
4285 ** before statement S is ever evaluated, after
4286 ** one or more calls to [sqlite3_reset()], or after any call
4287 ** to [sqlite3_step()] regardless of whether or not the statement has
4288 ** completed execution.
4289 **
4290 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4291 **
4292 ** The application must finalize every [prepared statement] in order to avoid
4293 ** resource leaks.  It is a grievous error for the application to try to use
4294 ** a prepared statement after it has been finalized.  Any use of a prepared
4295 ** statement after it has been finalized can result in undefined and
4296 ** undesirable behavior such as segfaults and heap corruption.
4297 */
4298 SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt);
4299 
4300 /*
4301 ** CAPI3REF: Reset A Prepared Statement Object
4302 ** METHOD: sqlite3_stmt
4303 **
4304 ** The sqlite3_reset() function is called to reset a [prepared statement]
4305 ** object back to its initial state, ready to be re-executed.
4306 ** ^Any SQL statement variables that had values bound to them using
4307 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4308 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4309 **
4310 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4311 ** back to the beginning of its program.
4312 **
4313 ** ^If the most recent call to [sqlite3_step(S)] for the
4314 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4315 ** or if [sqlite3_step(S)] has never before been called on S,
4316 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4317 **
4318 ** ^If the most recent call to [sqlite3_step(S)] for the
4319 ** [prepared statement] S indicated an error, then
4320 ** [sqlite3_reset(S)] returns an appropriate [error code].
4321 **
4322 ** ^The [sqlite3_reset(S)] interface does not change the values
4323 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4324 */
4325 SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt);
4326 
4327 /*
4328 ** CAPI3REF: Create Or Redefine SQL Functions
4329 ** KEYWORDS: {function creation routines}
4330 ** KEYWORDS: {application-defined SQL function}
4331 ** KEYWORDS: {application-defined SQL functions}
4332 ** METHOD: sqlite3
4333 **
4334 ** ^These functions (collectively known as "function creation routines")
4335 ** are used to add SQL functions or aggregates or to redefine the behavior
4336 ** of existing SQL functions or aggregates.  The only differences between
4337 ** these routines are the text encoding expected for
4338 ** the second parameter (the name of the function being created)
4339 ** and the presence or absence of a destructor callback for
4340 ** the application data pointer.
4341 **
4342 ** ^The first parameter is the [database connection] to which the SQL
4343 ** function is to be added.  ^If an application uses more than one database
4344 ** connection then application-defined SQL functions must be added
4345 ** to each database connection separately.
4346 **
4347 ** ^The second parameter is the name of the SQL function to be created or
4348 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4349 ** representation, exclusive of the zero-terminator.  ^Note that the name
4350 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4351 ** ^Any attempt to create a function with a longer name
4352 ** will result in [SQLITE_MISUSE] being returned.
4353 **
4354 ** ^The third parameter (nArg)
4355 ** is the number of arguments that the SQL function or
4356 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4357 ** aggregate may take any number of arguments between 0 and the limit
4358 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4359 ** parameter is less than -1 or greater than 127 then the behavior is
4360 ** undefined.
4361 **
4362 ** ^The fourth parameter, eTextRep, specifies what
4363 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4364 ** its parameters.  The application should set this parameter to
4365 ** [SQLITE_UTF16LE] if the function implementation invokes
4366 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
4367 ** implementation invokes [sqlite3_value_text16be()] on an input, or
4368 ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
4369 ** otherwise.  ^The same SQL function may be registered multiple times using
4370 ** different preferred text encodings, with different implementations for
4371 ** each encoding.
4372 ** ^When multiple implementations of the same function are available, SQLite
4373 ** will pick the one that involves the least amount of data conversion.
4374 **
4375 ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
4376 ** to signal that the function will always return the same result given
4377 ** the same inputs within a single SQL statement.  Most SQL functions are
4378 ** deterministic.  The built-in [random()] SQL function is an example of a
4379 ** function that is not deterministic.  The SQLite query planner is able to
4380 ** perform additional optimizations on deterministic functions, so use
4381 ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
4382 **
4383 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4384 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4385 **
4386 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4387 ** pointers to C-language functions that implement the SQL function or
4388 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4389 ** callback only; NULL pointers must be passed as the xStep and xFinal
4390 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4391 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4392 ** SQL function or aggregate, pass NULL pointers for all three function
4393 ** callbacks.
4394 **
4395 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4396 ** then it is destructor for the application data pointer.
4397 ** The destructor is invoked when the function is deleted, either by being
4398 ** overloaded or when the database connection closes.)^
4399 ** ^The destructor is also invoked if the call to
4400 ** sqlite3_create_function_v2() fails.
4401 ** ^When the destructor callback of the tenth parameter is invoked, it
4402 ** is passed a single argument which is a copy of the application data
4403 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4404 **
4405 ** ^It is permitted to register multiple implementations of the same
4406 ** functions with the same name but with either differing numbers of
4407 ** arguments or differing preferred text encodings.  ^SQLite will use
4408 ** the implementation that most closely matches the way in which the
4409 ** SQL function is used.  ^A function implementation with a non-negative
4410 ** nArg parameter is a better match than a function implementation with
4411 ** a negative nArg.  ^A function where the preferred text encoding
4412 ** matches the database encoding is a better
4413 ** match than a function where the encoding is different.
4414 ** ^A function where the encoding difference is between UTF16le and UTF16be
4415 ** is a closer match than a function where the encoding difference is
4416 ** between UTF8 and UTF16.
4417 **
4418 ** ^Built-in functions may be overloaded by new application-defined functions.
4419 **
4420 ** ^An application-defined function is permitted to call other
4421 ** SQLite interfaces.  However, such calls must not
4422 ** close the database connection nor finalize or reset the prepared
4423 ** statement in which the function is running.
4424 */
4425 SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
4426   sqlite3 *db,
4427   const char *zFunctionName,
4428   int nArg,
4429   int eTextRep,
4430   void *pApp,
4431   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4432   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4433   void (*xFinal)(sqlite3_context*)
4434 );
4435 SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
4436   sqlite3 *db,
4437   const void *zFunctionName,
4438   int nArg,
4439   int eTextRep,
4440   void *pApp,
4441   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4442   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4443   void (*xFinal)(sqlite3_context*)
4444 );
4445 SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
4446   sqlite3 *db,
4447   const char *zFunctionName,
4448   int nArg,
4449   int eTextRep,
4450   void *pApp,
4451   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4452   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4453   void (*xFinal)(sqlite3_context*),
4454   void(*xDestroy)(void*)
4455 );
4456 
4457 /*
4458 ** CAPI3REF: Text Encodings
4459 **
4460 ** These constant define integer codes that represent the various
4461 ** text encodings supported by SQLite.
4462 */
4463 #define SQLITE_UTF8           1    /* IMP: R-37514-35566 */
4464 #define SQLITE_UTF16LE        2    /* IMP: R-03371-37637 */
4465 #define SQLITE_UTF16BE        3    /* IMP: R-51971-34154 */
4466 #define SQLITE_UTF16          4    /* Use native byte order */
4467 #define SQLITE_ANY            5    /* Deprecated */
4468 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4469 
4470 /*
4471 ** CAPI3REF: Function Flags
4472 **
4473 ** These constants may be ORed together with the
4474 ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
4475 ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
4476 ** [sqlite3_create_function_v2()].
4477 */
4478 #define SQLITE_DETERMINISTIC    0x800
4479 
4480 /*
4481 ** CAPI3REF: Deprecated Functions
4482 ** DEPRECATED
4483 **
4484 ** These functions are [deprecated].  In order to maintain
4485 ** backwards compatibility with older code, these functions continue
4486 ** to be supported.  However, new applications should avoid
4487 ** the use of these functions.  To encourage programmers to avoid
4488 ** these functions, we will not explain what they do.
4489 */
4490 #ifndef SQLITE_OMIT_DEPRECATED
4491 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context*);
4492 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt*);
4493 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4494 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_global_recover(void);
4495 SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_thread_cleanup(void);
4496 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4497                       void*,sqlite3_int64);
4498 #endif
4499 
4500 /*
4501 ** CAPI3REF: Obtaining SQL Function Parameter Values
4502 ** METHOD: sqlite3_value
4503 **
4504 ** The C-language implementation of SQL functions and aggregates uses
4505 ** this set of interface routines to access the parameter values on
4506 ** the function or aggregate.
4507 **
4508 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4509 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4510 ** define callbacks that implement the SQL functions and aggregates.
4511 ** The 3rd parameter to these callbacks is an array of pointers to
4512 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4513 ** each parameter to the SQL function.  These routines are used to
4514 ** extract values from the [sqlite3_value] objects.
4515 **
4516 ** These routines work only with [protected sqlite3_value] objects.
4517 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4518 ** object results in undefined behavior.
4519 **
4520 ** ^These routines work just like the corresponding [column access functions]
4521 ** except that these routines take a single [protected sqlite3_value] object
4522 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4523 **
4524 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4525 ** in the native byte-order of the host machine.  ^The
4526 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4527 ** extract UTF-16 strings as big-endian and little-endian respectively.
4528 **
4529 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4530 ** numeric affinity to the value.  This means that an attempt is
4531 ** made to convert the value to an integer or floating point.  If
4532 ** such a conversion is possible without loss of information (in other
4533 ** words, if the value is a string that looks like a number)
4534 ** then the conversion is performed.  Otherwise no conversion occurs.
4535 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4536 **
4537 ** Please pay particular attention to the fact that the pointer returned
4538 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4539 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4540 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4541 ** or [sqlite3_value_text16()].
4542 **
4543 ** These routines must be called from the same thread as
4544 ** the SQL function that supplied the [sqlite3_value*] parameters.
4545 */
4546 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value*);
4547 SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value*);
4548 SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value*);
4549 SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value*);
4550 SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value*);
4551 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value*);
4552 SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value*);
4553 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value*);
4554 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value*);
4555 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value*);
4556 SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value*);
4557 SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value*);
4558 
4559 /*
4560 ** CAPI3REF: Obtain Aggregate Function Context
4561 ** METHOD: sqlite3_context
4562 **
4563 ** Implementations of aggregate SQL functions use this
4564 ** routine to allocate memory for storing their state.
4565 **
4566 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4567 ** for a particular aggregate function, SQLite
4568 ** allocates N of memory, zeroes out that memory, and returns a pointer
4569 ** to the new memory. ^On second and subsequent calls to
4570 ** sqlite3_aggregate_context() for the same aggregate function instance,
4571 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4572 ** called once for each invocation of the xStep callback and then one
4573 ** last time when the xFinal callback is invoked.  ^(When no rows match
4574 ** an aggregate query, the xStep() callback of the aggregate function
4575 ** implementation is never called and xFinal() is called exactly once.
4576 ** In those cases, sqlite3_aggregate_context() might be called for the
4577 ** first time from within xFinal().)^
4578 **
4579 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4580 ** when first called if N is less than or equal to zero or if a memory
4581 ** allocate error occurs.
4582 **
4583 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4584 ** determined by the N parameter on first successful call.  Changing the
4585 ** value of N in subsequent call to sqlite3_aggregate_context() within
4586 ** the same aggregate function instance will not resize the memory
4587 ** allocation.)^  Within the xFinal callback, it is customary to set
4588 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4589 ** pointless memory allocations occur.
4590 **
4591 ** ^SQLite automatically frees the memory allocated by
4592 ** sqlite3_aggregate_context() when the aggregate query concludes.
4593 **
4594 ** The first parameter must be a copy of the
4595 ** [sqlite3_context | SQL function context] that is the first parameter
4596 ** to the xStep or xFinal callback routine that implements the aggregate
4597 ** function.
4598 **
4599 ** This routine must be called from the same thread in which
4600 ** the aggregate SQL function is running.
4601 */
4602 SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4603 
4604 /*
4605 ** CAPI3REF: User Data For Functions
4606 ** METHOD: sqlite3_context
4607 **
4608 ** ^The sqlite3_user_data() interface returns a copy of
4609 ** the pointer that was the pUserData parameter (the 5th parameter)
4610 ** of the [sqlite3_create_function()]
4611 ** and [sqlite3_create_function16()] routines that originally
4612 ** registered the application defined function.
4613 **
4614 ** This routine must be called from the same thread in which
4615 ** the application-defined function is running.
4616 */
4617 SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context*);
4618 
4619 /*
4620 ** CAPI3REF: Database Connection For Functions
4621 ** METHOD: sqlite3_context
4622 **
4623 ** ^The sqlite3_context_db_handle() interface returns a copy of
4624 ** the pointer to the [database connection] (the 1st parameter)
4625 ** of the [sqlite3_create_function()]
4626 ** and [sqlite3_create_function16()] routines that originally
4627 ** registered the application defined function.
4628 */
4629 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context*);
4630 
4631 /*
4632 ** CAPI3REF: Function Auxiliary Data
4633 ** METHOD: sqlite3_context
4634 **
4635 ** These functions may be used by (non-aggregate) SQL functions to
4636 ** associate metadata with argument values. If the same value is passed to
4637 ** multiple invocations of the same SQL function during query execution, under
4638 ** some circumstances the associated metadata may be preserved.  An example
4639 ** of where this might be useful is in a regular-expression matching
4640 ** function. The compiled version of the regular expression can be stored as
4641 ** metadata associated with the pattern string.
4642 ** Then as long as the pattern string remains the same,
4643 ** the compiled regular expression can be reused on multiple
4644 ** invocations of the same function.
4645 **
4646 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4647 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4648 ** value to the application-defined function. ^If there is no metadata
4649 ** associated with the function argument, this sqlite3_get_auxdata() interface
4650 ** returns a NULL pointer.
4651 **
4652 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
4653 ** argument of the application-defined function.  ^Subsequent
4654 ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
4655 ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
4656 ** NULL if the metadata has been discarded.
4657 ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
4658 ** SQLite will invoke the destructor function X with parameter P exactly
4659 ** once, when the metadata is discarded.
4660 ** SQLite is free to discard the metadata at any time, including: <ul>
4661 ** <li> when the corresponding function parameter changes, or
4662 ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
4663 **      SQL statement, or
4664 ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
4665 ** <li> during the original sqlite3_set_auxdata() call when a memory
4666 **      allocation error occurs. </ul>)^
4667 **
4668 ** Note the last bullet in particular.  The destructor X in
4669 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
4670 ** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
4671 ** should be called near the end of the function implementation and the
4672 ** function implementation should not make any use of P after
4673 ** sqlite3_set_auxdata() has been called.
4674 **
4675 ** ^(In practice, metadata is preserved between function calls for
4676 ** function parameters that are compile-time constants, including literal
4677 ** values and [parameters] and expressions composed from the same.)^
4678 **
4679 ** These routines must be called from the same thread in which
4680 ** the SQL function is running.
4681 */
4682 SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context*, int N);
4683 SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4684 
4685 
4686 /*
4687 ** CAPI3REF: Constants Defining Special Destructor Behavior
4688 **
4689 ** These are special values for the destructor that is passed in as the
4690 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4691 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4692 ** and will never change.  It does not need to be destroyed.  ^The
4693 ** SQLITE_TRANSIENT value means that the content will likely change in
4694 ** the near future and that SQLite should make its own private copy of
4695 ** the content before returning.
4696 **
4697 ** The typedef is necessary to work around problems in certain
4698 ** C++ compilers.
4699 */
4700 typedef void (*sqlite3_destructor_type)(void*);
4701 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4702 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4703 
4704 /*
4705 ** CAPI3REF: Setting The Result Of An SQL Function
4706 ** METHOD: sqlite3_context
4707 **
4708 ** These routines are used by the xFunc or xFinal callbacks that
4709 ** implement SQL functions and aggregates.  See
4710 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4711 ** for additional information.
4712 **
4713 ** These functions work very much like the [parameter binding] family of
4714 ** functions used to bind values to host parameters in prepared statements.
4715 ** Refer to the [SQL parameter] documentation for additional information.
4716 **
4717 ** ^The sqlite3_result_blob() interface sets the result from
4718 ** an application-defined function to be the BLOB whose content is pointed
4719 ** to by the second parameter and which is N bytes long where N is the
4720 ** third parameter.
4721 **
4722 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4723 ** the application-defined function to be a BLOB containing all zero
4724 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4725 **
4726 ** ^The sqlite3_result_double() interface sets the result from
4727 ** an application-defined function to be a floating point value specified
4728 ** by its 2nd argument.
4729 **
4730 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4731 ** cause the implemented SQL function to throw an exception.
4732 ** ^SQLite uses the string pointed to by the
4733 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4734 ** as the text of an error message.  ^SQLite interprets the error
4735 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4736 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4737 ** byte order.  ^If the third parameter to sqlite3_result_error()
4738 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4739 ** message all text up through the first zero character.
4740 ** ^If the third parameter to sqlite3_result_error() or
4741 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4742 ** bytes (not characters) from the 2nd parameter as the error message.
4743 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4744 ** routines make a private copy of the error message text before
4745 ** they return.  Hence, the calling function can deallocate or
4746 ** modify the text after they return without harm.
4747 ** ^The sqlite3_result_error_code() function changes the error code
4748 ** returned by SQLite as a result of an error in a function.  ^By default,
4749 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4750 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4751 **
4752 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4753 ** error indicating that a string or BLOB is too long to represent.
4754 **
4755 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4756 ** error indicating that a memory allocation failed.
4757 **
4758 ** ^The sqlite3_result_int() interface sets the return value
4759 ** of the application-defined function to be the 32-bit signed integer
4760 ** value given in the 2nd argument.
4761 ** ^The sqlite3_result_int64() interface sets the return value
4762 ** of the application-defined function to be the 64-bit signed integer
4763 ** value given in the 2nd argument.
4764 **
4765 ** ^The sqlite3_result_null() interface sets the return value
4766 ** of the application-defined function to be NULL.
4767 **
4768 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4769 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4770 ** set the return value of the application-defined function to be
4771 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4772 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4773 ** ^The sqlite3_result_text64() interface sets the return value of an
4774 ** application-defined function to be a text string in an encoding
4775 ** specified by the fifth (and last) parameter, which must be one
4776 ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
4777 ** ^SQLite takes the text result from the application from
4778 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4779 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4780 ** is negative, then SQLite takes result text from the 2nd parameter
4781 ** through the first zero character.
4782 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4783 ** is non-negative, then as many bytes (not characters) of the text
4784 ** pointed to by the 2nd parameter are taken as the application-defined
4785 ** function result.  If the 3rd parameter is non-negative, then it
4786 ** must be the byte offset into the string where the NUL terminator would
4787 ** appear if the string where NUL terminated.  If any NUL characters occur
4788 ** in the string at a byte offset that is less than the value of the 3rd
4789 ** parameter, then the resulting string will contain embedded NULs and the
4790 ** result of expressions operating on strings with embedded NULs is undefined.
4791 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4792 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4793 ** function as the destructor on the text or BLOB result when it has
4794 ** finished using that result.
4795 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4796 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4797 ** assumes that the text or BLOB result is in constant space and does not
4798 ** copy the content of the parameter nor call a destructor on the content
4799 ** when it has finished using that result.
4800 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4801 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4802 ** then SQLite makes a copy of the result into space obtained from
4803 ** from [sqlite3_malloc()] before it returns.
4804 **
4805 ** ^The sqlite3_result_value() interface sets the result of
4806 ** the application-defined function to be a copy the
4807 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4808 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4809 ** so that the [sqlite3_value] specified in the parameter may change or
4810 ** be deallocated after sqlite3_result_value() returns without harm.
4811 ** ^A [protected sqlite3_value] object may always be used where an
4812 ** [unprotected sqlite3_value] object is required, so either
4813 ** kind of [sqlite3_value] object can be used with this interface.
4814 **
4815 ** If these routines are called from within the different thread
4816 ** than the one containing the application-defined function that received
4817 ** the [sqlite3_context] pointer, the results are undefined.
4818 */
4819 SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4820 SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(sqlite3_context*,const void*,
4821                            sqlite3_uint64,void(*)(void*));
4822 SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context*, double);
4823 SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context*, const char*, int);
4824 SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context*, const void*, int);
4825 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context*);
4826 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context*);
4827 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context*, int);
4828 SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context*, int);
4829 SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4830 SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context*);
4831 SQLITE_API void SQLITE_STDCALL sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4832 SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
4833                            void(*)(void*), unsigned char encoding);
4834 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4835 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4836 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4837 SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4838 SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context*, int n);
4839 
4840 /*
4841 ** CAPI3REF: Define New Collating Sequences
4842 ** METHOD: sqlite3
4843 **
4844 ** ^These functions add, remove, or modify a [collation] associated
4845 ** with the [database connection] specified as the first argument.
4846 **
4847 ** ^The name of the collation is a UTF-8 string
4848 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4849 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4850 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4851 ** considered to be the same name.
4852 **
4853 ** ^(The third argument (eTextRep) must be one of the constants:
4854 ** <ul>
4855 ** <li> [SQLITE_UTF8],
4856 ** <li> [SQLITE_UTF16LE],
4857 ** <li> [SQLITE_UTF16BE],
4858 ** <li> [SQLITE_UTF16], or
4859 ** <li> [SQLITE_UTF16_ALIGNED].
4860 ** </ul>)^
4861 ** ^The eTextRep argument determines the encoding of strings passed
4862 ** to the collating function callback, xCallback.
4863 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4864 ** force strings to be UTF16 with native byte order.
4865 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4866 ** on an even byte address.
4867 **
4868 ** ^The fourth argument, pArg, is an application data pointer that is passed
4869 ** through as the first argument to the collating function callback.
4870 **
4871 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4872 ** ^Multiple collating functions can be registered using the same name but
4873 ** with different eTextRep parameters and SQLite will use whichever
4874 ** function requires the least amount of data transformation.
4875 ** ^If the xCallback argument is NULL then the collating function is
4876 ** deleted.  ^When all collating functions having the same name are deleted,
4877 ** that collation is no longer usable.
4878 **
4879 ** ^The collating function callback is invoked with a copy of the pArg
4880 ** application data pointer and with two strings in the encoding specified
4881 ** by the eTextRep argument.  The collating function must return an
4882 ** integer that is negative, zero, or positive
4883 ** if the first string is less than, equal to, or greater than the second,
4884 ** respectively.  A collating function must always return the same answer
4885 ** given the same inputs.  If two or more collating functions are registered
4886 ** to the same collation name (using different eTextRep values) then all
4887 ** must give an equivalent answer when invoked with equivalent strings.
4888 ** The collating function must obey the following properties for all
4889 ** strings A, B, and C:
4890 **
4891 ** <ol>
4892 ** <li> If A==B then B==A.
4893 ** <li> If A==B and B==C then A==C.
4894 ** <li> If A&lt;B THEN B&gt;A.
4895 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4896 ** </ol>
4897 **
4898 ** If a collating function fails any of the above constraints and that
4899 ** collating function is  registered and used, then the behavior of SQLite
4900 ** is undefined.
4901 **
4902 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4903 ** with the addition that the xDestroy callback is invoked on pArg when
4904 ** the collating function is deleted.
4905 ** ^Collating functions are deleted when they are overridden by later
4906 ** calls to the collation creation functions or when the
4907 ** [database connection] is closed using [sqlite3_close()].
4908 **
4909 ** ^The xDestroy callback is <u>not</u> called if the
4910 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
4911 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
4912 ** check the return code and dispose of the application data pointer
4913 ** themselves rather than expecting SQLite to deal with it for them.
4914 ** This is different from every other SQLite interface.  The inconsistency
4915 ** is unfortunate but cannot be changed without breaking backwards
4916 ** compatibility.
4917 **
4918 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4919 */
4920 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
4921   sqlite3*,
4922   const char *zName,
4923   int eTextRep,
4924   void *pArg,
4925   int(*xCompare)(void*,int,const void*,int,const void*)
4926 );
4927 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
4928   sqlite3*,
4929   const char *zName,
4930   int eTextRep,
4931   void *pArg,
4932   int(*xCompare)(void*,int,const void*,int,const void*),
4933   void(*xDestroy)(void*)
4934 );
4935 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
4936   sqlite3*,
4937   const void *zName,
4938   int eTextRep,
4939   void *pArg,
4940   int(*xCompare)(void*,int,const void*,int,const void*)
4941 );
4942 
4943 /*
4944 ** CAPI3REF: Collation Needed Callbacks
4945 ** METHOD: sqlite3
4946 **
4947 ** ^To avoid having to register all collation sequences before a database
4948 ** can be used, a single callback function may be registered with the
4949 ** [database connection] to be invoked whenever an undefined collation
4950 ** sequence is required.
4951 **
4952 ** ^If the function is registered using the sqlite3_collation_needed() API,
4953 ** then it is passed the names of undefined collation sequences as strings
4954 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4955 ** the names are passed as UTF-16 in machine native byte order.
4956 ** ^A call to either function replaces the existing collation-needed callback.
4957 **
4958 ** ^(When the callback is invoked, the first argument passed is a copy
4959 ** of the second argument to sqlite3_collation_needed() or
4960 ** sqlite3_collation_needed16().  The second argument is the database
4961 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4962 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4963 ** sequence function required.  The fourth parameter is the name of the
4964 ** required collation sequence.)^
4965 **
4966 ** The callback function should register the desired collation using
4967 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4968 ** [sqlite3_create_collation_v2()].
4969 */
4970 SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
4971   sqlite3*,
4972   void*,
4973   void(*)(void*,sqlite3*,int eTextRep,const char*)
4974 );
4975 SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
4976   sqlite3*,
4977   void*,
4978   void(*)(void*,sqlite3*,int eTextRep,const void*)
4979 );
4980 
4981 #ifdef SQLITE_HAS_CODEC
4982 /*
4983 ** Specify the key for an encrypted database.  This routine should be
4984 ** called right after sqlite3_open().
4985 **
4986 ** The code to implement this API is not available in the public release
4987 ** of SQLite.
4988 */
4989 SQLITE_API int SQLITE_STDCALL sqlite3_key(
4990   sqlite3 *db,                   /* Database to be rekeyed */
4991   const void *pKey, int nKey     /* The key */
4992 );
4993 SQLITE_API int SQLITE_STDCALL sqlite3_key_v2(
4994   sqlite3 *db,                   /* Database to be rekeyed */
4995   const char *zDbName,           /* Name of the database */
4996   const void *pKey, int nKey     /* The key */
4997 );
4998 
4999 /*
5000 ** Change the key on an open database.  If the current database is not
5001 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
5002 ** database is decrypted.
5003 **
5004 ** The code to implement this API is not available in the public release
5005 ** of SQLite.
5006 */
5007 SQLITE_API int SQLITE_STDCALL sqlite3_rekey(
5008   sqlite3 *db,                   /* Database to be rekeyed */
5009   const void *pKey, int nKey     /* The new key */
5010 );
5011 SQLITE_API int SQLITE_STDCALL sqlite3_rekey_v2(
5012   sqlite3 *db,                   /* Database to be rekeyed */
5013   const char *zDbName,           /* Name of the database */
5014   const void *pKey, int nKey     /* The new key */
5015 );
5016 
5017 /*
5018 ** Specify the activation key for a SEE database.  Unless
5019 ** activated, none of the SEE routines will work.
5020 */
5021 SQLITE_API void SQLITE_STDCALL sqlite3_activate_see(
5022   const char *zPassPhrase        /* Activation phrase */
5023 );
5024 #endif
5025 
5026 #ifdef SQLITE_ENABLE_CEROD
5027 /*
5028 ** Specify the activation key for a CEROD database.  Unless
5029 ** activated, none of the CEROD routines will work.
5030 */
5031 SQLITE_API void SQLITE_STDCALL sqlite3_activate_cerod(
5032   const char *zPassPhrase        /* Activation phrase */
5033 );
5034 #endif
5035 
5036 /*
5037 ** CAPI3REF: Suspend Execution For A Short Time
5038 **
5039 ** The sqlite3_sleep() function causes the current thread to suspend execution
5040 ** for at least a number of milliseconds specified in its parameter.
5041 **
5042 ** If the operating system does not support sleep requests with
5043 ** millisecond time resolution, then the time will be rounded up to
5044 ** the nearest second. The number of milliseconds of sleep actually
5045 ** requested from the operating system is returned.
5046 **
5047 ** ^SQLite implements this interface by calling the xSleep()
5048 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
5049 ** of the default VFS is not implemented correctly, or not implemented at
5050 ** all, then the behavior of sqlite3_sleep() may deviate from the description
5051 ** in the previous paragraphs.
5052 */
5053 SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int);
5054 
5055 /*
5056 ** CAPI3REF: Name Of The Folder Holding Temporary Files
5057 **
5058 ** ^(If this global variable is made to point to a string which is
5059 ** the name of a folder (a.k.a. directory), then all temporary files
5060 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5061 ** will be placed in that directory.)^  ^If this variable
5062 ** is a NULL pointer, then SQLite performs a search for an appropriate
5063 ** temporary file directory.
5064 **
5065 ** Applications are strongly discouraged from using this global variable.
5066 ** It is required to set a temporary folder on Windows Runtime (WinRT).
5067 ** But for all other platforms, it is highly recommended that applications
5068 ** neither read nor write this variable.  This global variable is a relic
5069 ** that exists for backwards compatibility of legacy applications and should
5070 ** be avoided in new projects.
5071 **
5072 ** It is not safe to read or modify this variable in more than one
5073 ** thread at a time.  It is not safe to read or modify this variable
5074 ** if a [database connection] is being used at the same time in a separate
5075 ** thread.
5076 ** It is intended that this variable be set once
5077 ** as part of process initialization and before any SQLite interface
5078 ** routines have been called and that this variable remain unchanged
5079 ** thereafter.
5080 **
5081 ** ^The [temp_store_directory pragma] may modify this variable and cause
5082 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5083 ** the [temp_store_directory pragma] always assumes that any string
5084 ** that this variable points to is held in memory obtained from
5085 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5086 ** using [sqlite3_free].
5087 ** Hence, if this variable is modified directly, either it should be
5088 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5089 ** or else the use of the [temp_store_directory pragma] should be avoided.
5090 ** Except when requested by the [temp_store_directory pragma], SQLite
5091 ** does not free the memory that sqlite3_temp_directory points to.  If
5092 ** the application wants that memory to be freed, it must do
5093 ** so itself, taking care to only do so after all [database connection]
5094 ** objects have been destroyed.
5095 **
5096 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
5097 ** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
5098 ** features that require the use of temporary files may fail.  Here is an
5099 ** example of how to do this using C++ with the Windows Runtime:
5100 **
5101 ** <blockquote><pre>
5102 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5103 ** &nbsp;     TemporaryFolder->Path->Data();
5104 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
5105 ** memset(zPathBuf, 0, sizeof(zPathBuf));
5106 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5107 ** &nbsp;     NULL, NULL);
5108 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5109 ** </pre></blockquote>
5110 */
5111 SQLITE_API char *sqlite3_temp_directory;
5112 
5113 /*
5114 ** CAPI3REF: Name Of The Folder Holding Database Files
5115 **
5116 ** ^(If this global variable is made to point to a string which is
5117 ** the name of a folder (a.k.a. directory), then all database files
5118 ** specified with a relative pathname and created or accessed by
5119 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5120 ** to be relative to that directory.)^ ^If this variable is a NULL
5121 ** pointer, then SQLite assumes that all database files specified
5122 ** with a relative pathname are relative to the current directory
5123 ** for the process.  Only the windows VFS makes use of this global
5124 ** variable; it is ignored by the unix VFS.
5125 **
5126 ** Changing the value of this variable while a database connection is
5127 ** open can result in a corrupt database.
5128 **
5129 ** It is not safe to read or modify this variable in more than one
5130 ** thread at a time.  It is not safe to read or modify this variable
5131 ** if a [database connection] is being used at the same time in a separate
5132 ** thread.
5133 ** It is intended that this variable be set once
5134 ** as part of process initialization and before any SQLite interface
5135 ** routines have been called and that this variable remain unchanged
5136 ** thereafter.
5137 **
5138 ** ^The [data_store_directory pragma] may modify this variable and cause
5139 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5140 ** the [data_store_directory pragma] always assumes that any string
5141 ** that this variable points to is held in memory obtained from
5142 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5143 ** using [sqlite3_free].
5144 ** Hence, if this variable is modified directly, either it should be
5145 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5146 ** or else the use of the [data_store_directory pragma] should be avoided.
5147 */
5148 SQLITE_API char *sqlite3_data_directory;
5149 
5150 /*
5151 ** CAPI3REF: Test For Auto-Commit Mode
5152 ** KEYWORDS: {autocommit mode}
5153 ** METHOD: sqlite3
5154 **
5155 ** ^The sqlite3_get_autocommit() interface returns non-zero or
5156 ** zero if the given database connection is or is not in autocommit mode,
5157 ** respectively.  ^Autocommit mode is on by default.
5158 ** ^Autocommit mode is disabled by a [BEGIN] statement.
5159 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5160 **
5161 ** If certain kinds of errors occur on a statement within a multi-statement
5162 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5163 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5164 ** transaction might be rolled back automatically.  The only way to
5165 ** find out whether SQLite automatically rolled back the transaction after
5166 ** an error is to use this function.
5167 **
5168 ** If another thread changes the autocommit status of the database
5169 ** connection while this routine is running, then the return value
5170 ** is undefined.
5171 */
5172 SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3*);
5173 
5174 /*
5175 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
5176 ** METHOD: sqlite3_stmt
5177 **
5178 ** ^The sqlite3_db_handle interface returns the [database connection] handle
5179 ** to which a [prepared statement] belongs.  ^The [database connection]
5180 ** returned by sqlite3_db_handle is the same [database connection]
5181 ** that was the first argument
5182 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5183 ** create the statement in the first place.
5184 */
5185 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt*);
5186 
5187 /*
5188 ** CAPI3REF: Return The Filename For A Database Connection
5189 ** METHOD: sqlite3
5190 **
5191 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5192 ** associated with database N of connection D.  ^The main database file
5193 ** has the name "main".  If there is no attached database N on the database
5194 ** connection D, or if database N is a temporary or in-memory database, then
5195 ** a NULL pointer is returned.
5196 **
5197 ** ^The filename returned by this function is the output of the
5198 ** xFullPathname method of the [VFS].  ^In other words, the filename
5199 ** will be an absolute pathname, even if the filename used
5200 ** to open the database originally was a URI or relative pathname.
5201 */
5202 SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5203 
5204 /*
5205 ** CAPI3REF: Determine if a database is read-only
5206 ** METHOD: sqlite3
5207 **
5208 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5209 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5210 ** the name of a database on connection D.
5211 */
5212 SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5213 
5214 /*
5215 ** CAPI3REF: Find the next prepared statement
5216 ** METHOD: sqlite3
5217 **
5218 ** ^This interface returns a pointer to the next [prepared statement] after
5219 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
5220 ** then this interface returns a pointer to the first prepared statement
5221 ** associated with the database connection pDb.  ^If no prepared statement
5222 ** satisfies the conditions of this routine, it returns NULL.
5223 **
5224 ** The [database connection] pointer D in a call to
5225 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5226 ** connection and in particular must not be a NULL pointer.
5227 */
5228 SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5229 
5230 /*
5231 ** CAPI3REF: Commit And Rollback Notification Callbacks
5232 ** METHOD: sqlite3
5233 **
5234 ** ^The sqlite3_commit_hook() interface registers a callback
5235 ** function to be invoked whenever a transaction is [COMMIT | committed].
5236 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5237 ** for the same database connection is overridden.
5238 ** ^The sqlite3_rollback_hook() interface registers a callback
5239 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5240 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5241 ** for the same database connection is overridden.
5242 ** ^The pArg argument is passed through to the callback.
5243 ** ^If the callback on a commit hook function returns non-zero,
5244 ** then the commit is converted into a rollback.
5245 **
5246 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5247 ** return the P argument from the previous call of the same function
5248 ** on the same [database connection] D, or NULL for
5249 ** the first call for each function on D.
5250 **
5251 ** The commit and rollback hook callbacks are not reentrant.
5252 ** The callback implementation must not do anything that will modify
5253 ** the database connection that invoked the callback.  Any actions
5254 ** to modify the database connection must be deferred until after the
5255 ** completion of the [sqlite3_step()] call that triggered the commit
5256 ** or rollback hook in the first place.
5257 ** Note that running any other SQL statements, including SELECT statements,
5258 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5259 ** the database connections for the meaning of "modify" in this paragraph.
5260 **
5261 ** ^Registering a NULL function disables the callback.
5262 **
5263 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5264 ** operation is allowed to continue normally.  ^If the commit hook
5265 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5266 ** ^The rollback hook is invoked on a rollback that results from a commit
5267 ** hook returning non-zero, just as it would be with any other rollback.
5268 **
5269 ** ^For the purposes of this API, a transaction is said to have been
5270 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5271 ** an error or constraint causes an implicit rollback to occur.
5272 ** ^The rollback callback is not invoked if a transaction is
5273 ** automatically rolled back because the database connection is closed.
5274 **
5275 ** See also the [sqlite3_update_hook()] interface.
5276 */
5277 SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5278 SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5279 
5280 /*
5281 ** CAPI3REF: Data Change Notification Callbacks
5282 ** METHOD: sqlite3
5283 **
5284 ** ^The sqlite3_update_hook() interface registers a callback function
5285 ** with the [database connection] identified by the first argument
5286 ** to be invoked whenever a row is updated, inserted or deleted in
5287 ** a rowid table.
5288 ** ^Any callback set by a previous call to this function
5289 ** for the same database connection is overridden.
5290 **
5291 ** ^The second argument is a pointer to the function to invoke when a
5292 ** row is updated, inserted or deleted in a rowid table.
5293 ** ^The first argument to the callback is a copy of the third argument
5294 ** to sqlite3_update_hook().
5295 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5296 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5297 ** to be invoked.
5298 ** ^The third and fourth arguments to the callback contain pointers to the
5299 ** database and table name containing the affected row.
5300 ** ^The final callback parameter is the [rowid] of the row.
5301 ** ^In the case of an update, this is the [rowid] after the update takes place.
5302 **
5303 ** ^(The update hook is not invoked when internal system tables are
5304 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5305 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
5306 **
5307 ** ^In the current implementation, the update hook
5308 ** is not invoked when duplication rows are deleted because of an
5309 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5310 ** invoked when rows are deleted using the [truncate optimization].
5311 ** The exceptions defined in this paragraph might change in a future
5312 ** release of SQLite.
5313 **
5314 ** The update hook implementation must not do anything that will modify
5315 ** the database connection that invoked the update hook.  Any actions
5316 ** to modify the database connection must be deferred until after the
5317 ** completion of the [sqlite3_step()] call that triggered the update hook.
5318 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5319 ** database connections for the meaning of "modify" in this paragraph.
5320 **
5321 ** ^The sqlite3_update_hook(D,C,P) function
5322 ** returns the P argument from the previous call
5323 ** on the same [database connection] D, or NULL for
5324 ** the first call on D.
5325 **
5326 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5327 ** interfaces.
5328 */
5329 SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
5330   sqlite3*,
5331   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5332   void*
5333 );
5334 
5335 /*
5336 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5337 **
5338 ** ^(This routine enables or disables the sharing of the database cache
5339 ** and schema data structures between [database connection | connections]
5340 ** to the same database. Sharing is enabled if the argument is true
5341 ** and disabled if the argument is false.)^
5342 **
5343 ** ^Cache sharing is enabled and disabled for an entire process.
5344 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5345 ** sharing was enabled or disabled for each thread separately.
5346 **
5347 ** ^(The cache sharing mode set by this interface effects all subsequent
5348 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5349 ** Existing database connections continue use the sharing mode
5350 ** that was in effect at the time they were opened.)^
5351 **
5352 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5353 ** successfully.  An [error code] is returned otherwise.)^
5354 **
5355 ** ^Shared cache is disabled by default. But this might change in
5356 ** future releases of SQLite.  Applications that care about shared
5357 ** cache setting should set it explicitly.
5358 **
5359 ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
5360 ** and will always return SQLITE_MISUSE. On those systems,
5361 ** shared cache mode should be enabled per-database connection via
5362 ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
5363 **
5364 ** This interface is threadsafe on processors where writing a
5365 ** 32-bit integer is atomic.
5366 **
5367 ** See Also:  [SQLite Shared-Cache Mode]
5368 */
5369 SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int);
5370 
5371 /*
5372 ** CAPI3REF: Attempt To Free Heap Memory
5373 **
5374 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5375 ** of heap memory by deallocating non-essential memory allocations
5376 ** held by the database library.   Memory used to cache database
5377 ** pages to improve performance is an example of non-essential memory.
5378 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5379 ** which might be more or less than the amount requested.
5380 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5381 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5382 **
5383 ** See also: [sqlite3_db_release_memory()]
5384 */
5385 SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int);
5386 
5387 /*
5388 ** CAPI3REF: Free Memory Used By A Database Connection
5389 ** METHOD: sqlite3
5390 **
5391 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5392 ** memory as possible from database connection D. Unlike the
5393 ** [sqlite3_release_memory()] interface, this interface is in effect even
5394 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5395 ** omitted.
5396 **
5397 ** See also: [sqlite3_release_memory()]
5398 */
5399 SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3*);
5400 
5401 /*
5402 ** CAPI3REF: Impose A Limit On Heap Size
5403 **
5404 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5405 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5406 ** ^SQLite strives to keep heap memory utilization below the soft heap
5407 ** limit by reducing the number of pages held in the page cache
5408 ** as heap memory usages approaches the limit.
5409 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5410 ** below the limit, it will exceed the limit rather than generate
5411 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
5412 ** is advisory only.
5413 **
5414 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5415 ** the soft heap limit prior to the call, or negative in the case of an
5416 ** error.  ^If the argument N is negative
5417 ** then no change is made to the soft heap limit.  Hence, the current
5418 ** size of the soft heap limit can be determined by invoking
5419 ** sqlite3_soft_heap_limit64() with a negative argument.
5420 **
5421 ** ^If the argument N is zero then the soft heap limit is disabled.
5422 **
5423 ** ^(The soft heap limit is not enforced in the current implementation
5424 ** if one or more of following conditions are true:
5425 **
5426 ** <ul>
5427 ** <li> The soft heap limit is set to zero.
5428 ** <li> Memory accounting is disabled using a combination of the
5429 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5430 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5431 ** <li> An alternative page cache implementation is specified using
5432 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5433 ** <li> The page cache allocates from its own memory pool supplied
5434 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5435 **      from the heap.
5436 ** </ul>)^
5437 **
5438 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5439 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5440 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5441 ** the soft heap limit is enforced on every memory allocation.  Without
5442 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5443 ** when memory is allocated by the page cache.  Testing suggests that because
5444 ** the page cache is the predominate memory user in SQLite, most
5445 ** applications will achieve adequate soft heap limit enforcement without
5446 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5447 **
5448 ** The circumstances under which SQLite will enforce the soft heap limit may
5449 ** changes in future releases of SQLite.
5450 */
5451 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 N);
5452 
5453 /*
5454 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5455 ** DEPRECATED
5456 **
5457 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5458 ** interface.  This routine is provided for historical compatibility
5459 ** only.  All new applications should use the
5460 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5461 */
5462 SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_soft_heap_limit(int N);
5463 
5464 
5465 /*
5466 ** CAPI3REF: Extract Metadata About A Column Of A Table
5467 ** METHOD: sqlite3
5468 **
5469 ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
5470 ** information about column C of table T in database D
5471 ** on [database connection] X.)^  ^The sqlite3_table_column_metadata()
5472 ** interface returns SQLITE_OK and fills in the non-NULL pointers in
5473 ** the final five arguments with appropriate values if the specified
5474 ** column exists.  ^The sqlite3_table_column_metadata() interface returns
5475 ** SQLITE_ERROR and if the specified column does not exist.
5476 ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
5477 ** NULL pointer, then this routine simply checks for the existance of the
5478 ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
5479 ** does not.
5480 **
5481 ** ^The column is identified by the second, third and fourth parameters to
5482 ** this function. ^(The second parameter is either the name of the database
5483 ** (i.e. "main", "temp", or an attached database) containing the specified
5484 ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
5485 ** for the table using the same algorithm used by the database engine to
5486 ** resolve unqualified table references.
5487 **
5488 ** ^The third and fourth parameters to this function are the table and column
5489 ** name of the desired column, respectively.
5490 **
5491 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5492 ** and subsequent parameters to this function. ^Any of these arguments may be
5493 ** NULL, in which case the corresponding element of metadata is omitted.
5494 **
5495 ** ^(<blockquote>
5496 ** <table border="1">
5497 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5498 **
5499 ** <tr><td> 5th <td> const char* <td> Data type
5500 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5501 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5502 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5503 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5504 ** </table>
5505 ** </blockquote>)^
5506 **
5507 ** ^The memory pointed to by the character pointers returned for the
5508 ** declaration type and collation sequence is valid until the next
5509 ** call to any SQLite API function.
5510 **
5511 ** ^If the specified table is actually a view, an [error code] is returned.
5512 **
5513 ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
5514 ** is not a [WITHOUT ROWID] table and an
5515 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5516 ** parameters are set for the explicitly declared column. ^(If there is no
5517 ** [INTEGER PRIMARY KEY] column, then the outputs
5518 ** for the [rowid] are set as follows:
5519 **
5520 ** <pre>
5521 **     data type: "INTEGER"
5522 **     collation sequence: "BINARY"
5523 **     not null: 0
5524 **     primary key: 1
5525 **     auto increment: 0
5526 ** </pre>)^
5527 **
5528 ** ^This function causes all database schemas to be read from disk and
5529 ** parsed, if that has not already been done, and returns an error if
5530 ** any errors are encountered while loading the schema.
5531 */
5532 SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
5533   sqlite3 *db,                /* Connection handle */
5534   const char *zDbName,        /* Database name or NULL */
5535   const char *zTableName,     /* Table name */
5536   const char *zColumnName,    /* Column name */
5537   char const **pzDataType,    /* OUTPUT: Declared data type */
5538   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5539   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5540   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5541   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5542 );
5543 
5544 /*
5545 ** CAPI3REF: Load An Extension
5546 ** METHOD: sqlite3
5547 **
5548 ** ^This interface loads an SQLite extension library from the named file.
5549 **
5550 ** ^The sqlite3_load_extension() interface attempts to load an
5551 ** [SQLite extension] library contained in the file zFile.  If
5552 ** the file cannot be loaded directly, attempts are made to load
5553 ** with various operating-system specific extensions added.
5554 ** So for example, if "samplelib" cannot be loaded, then names like
5555 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5556 ** be tried also.
5557 **
5558 ** ^The entry point is zProc.
5559 ** ^(zProc may be 0, in which case SQLite will try to come up with an
5560 ** entry point name on its own.  It first tries "sqlite3_extension_init".
5561 ** If that does not work, it constructs a name "sqlite3_X_init" where the
5562 ** X is consists of the lower-case equivalent of all ASCII alphabetic
5563 ** characters in the filename from the last "/" to the first following
5564 ** "." and omitting any initial "lib".)^
5565 ** ^The sqlite3_load_extension() interface returns
5566 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5567 ** ^If an error occurs and pzErrMsg is not 0, then the
5568 ** [sqlite3_load_extension()] interface shall attempt to
5569 ** fill *pzErrMsg with error message text stored in memory
5570 ** obtained from [sqlite3_malloc()]. The calling function
5571 ** should free this memory by calling [sqlite3_free()].
5572 **
5573 ** ^Extension loading must be enabled using
5574 ** [sqlite3_enable_load_extension()] prior to calling this API,
5575 ** otherwise an error will be returned.
5576 **
5577 ** See also the [load_extension() SQL function].
5578 */
5579 SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
5580   sqlite3 *db,          /* Load the extension into this database connection */
5581   const char *zFile,    /* Name of the shared library containing extension */
5582   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5583   char **pzErrMsg       /* Put error message here if not 0 */
5584 );
5585 
5586 /*
5587 ** CAPI3REF: Enable Or Disable Extension Loading
5588 ** METHOD: sqlite3
5589 **
5590 ** ^So as not to open security holes in older applications that are
5591 ** unprepared to deal with [extension loading], and as a means of disabling
5592 ** [extension loading] while evaluating user-entered SQL, the following API
5593 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5594 **
5595 ** ^Extension loading is off by default.
5596 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5597 ** to turn extension loading on and call it with onoff==0 to turn
5598 ** it back off again.
5599 */
5600 SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5601 
5602 /*
5603 ** CAPI3REF: Automatically Load Statically Linked Extensions
5604 **
5605 ** ^This interface causes the xEntryPoint() function to be invoked for
5606 ** each new [database connection] that is created.  The idea here is that
5607 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5608 ** that is to be automatically loaded into all new database connections.
5609 **
5610 ** ^(Even though the function prototype shows that xEntryPoint() takes
5611 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5612 ** arguments and expects and integer result as if the signature of the
5613 ** entry point where as follows:
5614 **
5615 ** <blockquote><pre>
5616 ** &nbsp;  int xEntryPoint(
5617 ** &nbsp;    sqlite3 *db,
5618 ** &nbsp;    const char **pzErrMsg,
5619 ** &nbsp;    const struct sqlite3_api_routines *pThunk
5620 ** &nbsp;  );
5621 ** </pre></blockquote>)^
5622 **
5623 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5624 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5625 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5626 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5627 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5628 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5629 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5630 **
5631 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5632 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5633 ** will be called more than once for each database connection that is opened.
5634 **
5635 ** See also: [sqlite3_reset_auto_extension()]
5636 ** and [sqlite3_cancel_auto_extension()]
5637 */
5638 SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xEntryPoint)(void));
5639 
5640 /*
5641 ** CAPI3REF: Cancel Automatic Extension Loading
5642 **
5643 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
5644 ** initialization routine X that was registered using a prior call to
5645 ** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
5646 ** routine returns 1 if initialization routine X was successfully
5647 ** unregistered and it returns 0 if X was not on the list of initialization
5648 ** routines.
5649 */
5650 SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
5651 
5652 /*
5653 ** CAPI3REF: Reset Automatic Extension Loading
5654 **
5655 ** ^This interface disables all automatic extensions previously
5656 ** registered using [sqlite3_auto_extension()].
5657 */
5658 SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void);
5659 
5660 /*
5661 ** The interface to the virtual-table mechanism is currently considered
5662 ** to be experimental.  The interface might change in incompatible ways.
5663 ** If this is a problem for you, do not use the interface at this time.
5664 **
5665 ** When the virtual-table mechanism stabilizes, we will declare the
5666 ** interface fixed, support it indefinitely, and remove this comment.
5667 */
5668 
5669 /*
5670 ** Structures used by the virtual table interface
5671 */
5672 typedef struct sqlite3_vtab sqlite3_vtab;
5673 typedef struct sqlite3_index_info sqlite3_index_info;
5674 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5675 typedef struct sqlite3_module sqlite3_module;
5676 
5677 /*
5678 ** CAPI3REF: Virtual Table Object
5679 ** KEYWORDS: sqlite3_module {virtual table module}
5680 **
5681 ** This structure, sometimes called a "virtual table module",
5682 ** defines the implementation of a [virtual tables].
5683 ** This structure consists mostly of methods for the module.
5684 **
5685 ** ^A virtual table module is created by filling in a persistent
5686 ** instance of this structure and passing a pointer to that instance
5687 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5688 ** ^The registration remains valid until it is replaced by a different
5689 ** module or until the [database connection] closes.  The content
5690 ** of this structure must not change while it is registered with
5691 ** any database connection.
5692 */
5693 struct sqlite3_module {
5694   int iVersion;
5695   int (*xCreate)(sqlite3*, void *pAux,
5696                int argc, const char *const*argv,
5697                sqlite3_vtab **ppVTab, char**);
5698   int (*xConnect)(sqlite3*, void *pAux,
5699                int argc, const char *const*argv,
5700                sqlite3_vtab **ppVTab, char**);
5701   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5702   int (*xDisconnect)(sqlite3_vtab *pVTab);
5703   int (*xDestroy)(sqlite3_vtab *pVTab);
5704   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5705   int (*xClose)(sqlite3_vtab_cursor*);
5706   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5707                 int argc, sqlite3_value **argv);
5708   int (*xNext)(sqlite3_vtab_cursor*);
5709   int (*xEof)(sqlite3_vtab_cursor*);
5710   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5711   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5712   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5713   int (*xBegin)(sqlite3_vtab *pVTab);
5714   int (*xSync)(sqlite3_vtab *pVTab);
5715   int (*xCommit)(sqlite3_vtab *pVTab);
5716   int (*xRollback)(sqlite3_vtab *pVTab);
5717   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5718                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5719                        void **ppArg);
5720   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5721   /* The methods above are in version 1 of the sqlite_module object. Those
5722   ** below are for version 2 and greater. */
5723   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5724   int (*xRelease)(sqlite3_vtab *pVTab, int);
5725   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5726 };
5727 
5728 /*
5729 ** CAPI3REF: Virtual Table Indexing Information
5730 ** KEYWORDS: sqlite3_index_info
5731 **
5732 ** The sqlite3_index_info structure and its substructures is used as part
5733 ** of the [virtual table] interface to
5734 ** pass information into and receive the reply from the [xBestIndex]
5735 ** method of a [virtual table module].  The fields under **Inputs** are the
5736 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5737 ** results into the **Outputs** fields.
5738 **
5739 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5740 **
5741 ** <blockquote>column OP expr</blockquote>
5742 **
5743 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5744 ** stored in aConstraint[].op using one of the
5745 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5746 ** ^(The index of the column is stored in
5747 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5748 ** expr on the right-hand side can be evaluated (and thus the constraint
5749 ** is usable) and false if it cannot.)^
5750 **
5751 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5752 ** and makes other simplifications to the WHERE clause in an attempt to
5753 ** get as many WHERE clause terms into the form shown above as possible.
5754 ** ^The aConstraint[] array only reports WHERE clause terms that are
5755 ** relevant to the particular virtual table being queried.
5756 **
5757 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5758 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5759 **
5760 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5761 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5762 ** the right-hand side of the corresponding aConstraint[] is evaluated
5763 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5764 ** is true, then the constraint is assumed to be fully handled by the
5765 ** virtual table and is not checked again by SQLite.)^
5766 **
5767 ** ^The idxNum and idxPtr values are recorded and passed into the
5768 ** [xFilter] method.
5769 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5770 ** needToFreeIdxPtr is true.
5771 **
5772 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5773 ** the correct order to satisfy the ORDER BY clause so that no separate
5774 ** sorting step is required.
5775 **
5776 ** ^The estimatedCost value is an estimate of the cost of a particular
5777 ** strategy. A cost of N indicates that the cost of the strategy is similar
5778 ** to a linear scan of an SQLite table with N rows. A cost of log(N)
5779 ** indicates that the expense of the operation is similar to that of a
5780 ** binary search on a unique indexed field of an SQLite table with N rows.
5781 **
5782 ** ^The estimatedRows value is an estimate of the number of rows that
5783 ** will be returned by the strategy.
5784 **
5785 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
5786 ** structure for SQLite version 3.8.2. If a virtual table extension is
5787 ** used with an SQLite version earlier than 3.8.2, the results of attempting
5788 ** to read or write the estimatedRows field are undefined (but are likely
5789 ** to included crashing the application). The estimatedRows field should
5790 ** therefore only be used if [sqlite3_libversion_number()] returns a
5791 ** value greater than or equal to 3008002.
5792 */
5793 struct sqlite3_index_info {
5794   /* Inputs */
5795   int nConstraint;           /* Number of entries in aConstraint */
5796   struct sqlite3_index_constraint {
5797      int iColumn;              /* Column on left-hand side of constraint */
5798      unsigned char op;         /* Constraint operator */
5799      unsigned char usable;     /* True if this constraint is usable */
5800      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5801   } *aConstraint;            /* Table of WHERE clause constraints */
5802   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5803   struct sqlite3_index_orderby {
5804      int iColumn;              /* Column number */
5805      unsigned char desc;       /* True for DESC.  False for ASC. */
5806   } *aOrderBy;               /* The ORDER BY clause */
5807   /* Outputs */
5808   struct sqlite3_index_constraint_usage {
5809     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5810     unsigned char omit;      /* Do not code a test for this constraint */
5811   } *aConstraintUsage;
5812   int idxNum;                /* Number used to identify the index */
5813   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5814   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5815   int orderByConsumed;       /* True if output is already ordered */
5816   double estimatedCost;           /* Estimated cost of using this index */
5817   /* Fields below are only available in SQLite 3.8.2 and later */
5818   sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
5819 };
5820 
5821 /*
5822 ** CAPI3REF: Virtual Table Constraint Operator Codes
5823 **
5824 ** These macros defined the allowed values for the
5825 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5826 ** an operator that is part of a constraint term in the wHERE clause of
5827 ** a query that uses a [virtual table].
5828 */
5829 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5830 #define SQLITE_INDEX_CONSTRAINT_GT    4
5831 #define SQLITE_INDEX_CONSTRAINT_LE    8
5832 #define SQLITE_INDEX_CONSTRAINT_LT    16
5833 #define SQLITE_INDEX_CONSTRAINT_GE    32
5834 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5835 
5836 /*
5837 ** CAPI3REF: Register A Virtual Table Implementation
5838 ** METHOD: sqlite3
5839 **
5840 ** ^These routines are used to register a new [virtual table module] name.
5841 ** ^Module names must be registered before
5842 ** creating a new [virtual table] using the module and before using a
5843 ** preexisting [virtual table] for the module.
5844 **
5845 ** ^The module name is registered on the [database connection] specified
5846 ** by the first parameter.  ^The name of the module is given by the
5847 ** second parameter.  ^The third parameter is a pointer to
5848 ** the implementation of the [virtual table module].   ^The fourth
5849 ** parameter is an arbitrary client data pointer that is passed through
5850 ** into the [xCreate] and [xConnect] methods of the virtual table module
5851 ** when a new virtual table is be being created or reinitialized.
5852 **
5853 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5854 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5855 ** invoke the destructor function (if it is not NULL) when SQLite
5856 ** no longer needs the pClientData pointer.  ^The destructor will also
5857 ** be invoked if the call to sqlite3_create_module_v2() fails.
5858 ** ^The sqlite3_create_module()
5859 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5860 ** destructor.
5861 */
5862 SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
5863   sqlite3 *db,               /* SQLite connection to register module with */
5864   const char *zName,         /* Name of the module */
5865   const sqlite3_module *p,   /* Methods for the module */
5866   void *pClientData          /* Client data for xCreate/xConnect */
5867 );
5868 SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
5869   sqlite3 *db,               /* SQLite connection to register module with */
5870   const char *zName,         /* Name of the module */
5871   const sqlite3_module *p,   /* Methods for the module */
5872   void *pClientData,         /* Client data for xCreate/xConnect */
5873   void(*xDestroy)(void*)     /* Module destructor function */
5874 );
5875 
5876 /*
5877 ** CAPI3REF: Virtual Table Instance Object
5878 ** KEYWORDS: sqlite3_vtab
5879 **
5880 ** Every [virtual table module] implementation uses a subclass
5881 ** of this object to describe a particular instance
5882 ** of the [virtual table].  Each subclass will
5883 ** be tailored to the specific needs of the module implementation.
5884 ** The purpose of this superclass is to define certain fields that are
5885 ** common to all module implementations.
5886 **
5887 ** ^Virtual tables methods can set an error message by assigning a
5888 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5889 ** take care that any prior string is freed by a call to [sqlite3_free()]
5890 ** prior to assigning a new string to zErrMsg.  ^After the error message
5891 ** is delivered up to the client application, the string will be automatically
5892 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5893 */
5894 struct sqlite3_vtab {
5895   const sqlite3_module *pModule;  /* The module for this virtual table */
5896   int nRef;                       /* Number of open cursors */
5897   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5898   /* Virtual table implementations will typically add additional fields */
5899 };
5900 
5901 /*
5902 ** CAPI3REF: Virtual Table Cursor Object
5903 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5904 **
5905 ** Every [virtual table module] implementation uses a subclass of the
5906 ** following structure to describe cursors that point into the
5907 ** [virtual table] and are used
5908 ** to loop through the virtual table.  Cursors are created using the
5909 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5910 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5911 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5912 ** of the module.  Each module implementation will define
5913 ** the content of a cursor structure to suit its own needs.
5914 **
5915 ** This superclass exists in order to define fields of the cursor that
5916 ** are common to all implementations.
5917 */
5918 struct sqlite3_vtab_cursor {
5919   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5920   /* Virtual table implementations will typically add additional fields */
5921 };
5922 
5923 /*
5924 ** CAPI3REF: Declare The Schema Of A Virtual Table
5925 **
5926 ** ^The [xCreate] and [xConnect] methods of a
5927 ** [virtual table module] call this interface
5928 ** to declare the format (the names and datatypes of the columns) of
5929 ** the virtual tables they implement.
5930 */
5931 SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5932 
5933 /*
5934 ** CAPI3REF: Overload A Function For A Virtual Table
5935 ** METHOD: sqlite3
5936 **
5937 ** ^(Virtual tables can provide alternative implementations of functions
5938 ** using the [xFindFunction] method of the [virtual table module].
5939 ** But global versions of those functions
5940 ** must exist in order to be overloaded.)^
5941 **
5942 ** ^(This API makes sure a global version of a function with a particular
5943 ** name and number of parameters exists.  If no such function exists
5944 ** before this API is called, a new function is created.)^  ^The implementation
5945 ** of the new function always causes an exception to be thrown.  So
5946 ** the new function is not good for anything by itself.  Its only
5947 ** purpose is to be a placeholder function that can be overloaded
5948 ** by a [virtual table].
5949 */
5950 SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5951 
5952 /*
5953 ** The interface to the virtual-table mechanism defined above (back up
5954 ** to a comment remarkably similar to this one) is currently considered
5955 ** to be experimental.  The interface might change in incompatible ways.
5956 ** If this is a problem for you, do not use the interface at this time.
5957 **
5958 ** When the virtual-table mechanism stabilizes, we will declare the
5959 ** interface fixed, support it indefinitely, and remove this comment.
5960 */
5961 
5962 /*
5963 ** CAPI3REF: A Handle To An Open BLOB
5964 ** KEYWORDS: {BLOB handle} {BLOB handles}
5965 **
5966 ** An instance of this object represents an open BLOB on which
5967 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5968 ** ^Objects of this type are created by [sqlite3_blob_open()]
5969 ** and destroyed by [sqlite3_blob_close()].
5970 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5971 ** can be used to read or write small subsections of the BLOB.
5972 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5973 */
5974 typedef struct sqlite3_blob sqlite3_blob;
5975 
5976 /*
5977 ** CAPI3REF: Open A BLOB For Incremental I/O
5978 ** METHOD: sqlite3
5979 ** CONSTRUCTOR: sqlite3_blob
5980 **
5981 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5982 ** in row iRow, column zColumn, table zTable in database zDb;
5983 ** in other words, the same BLOB that would be selected by:
5984 **
5985 ** <pre>
5986 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5987 ** </pre>)^
5988 **
5989 ** ^(Parameter zDb is not the filename that contains the database, but
5990 ** rather the symbolic name of the database. For attached databases, this is
5991 ** the name that appears after the AS keyword in the [ATTACH] statement.
5992 ** For the main database file, the database name is "main". For TEMP
5993 ** tables, the database name is "temp".)^
5994 **
5995 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5996 ** and write access. ^If the flags parameter is zero, the BLOB is opened for
5997 ** read-only access.
5998 **
5999 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
6000 ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
6001 ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
6002 ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
6003 ** on *ppBlob after this function it returns.
6004 **
6005 ** This function fails with SQLITE_ERROR if any of the following are true:
6006 ** <ul>
6007 **   <li> ^(Database zDb does not exist)^,
6008 **   <li> ^(Table zTable does not exist within database zDb)^,
6009 **   <li> ^(Table zTable is a WITHOUT ROWID table)^,
6010 **   <li> ^(Column zColumn does not exist)^,
6011 **   <li> ^(Row iRow is not present in the table)^,
6012 **   <li> ^(The specified column of row iRow contains a value that is not
6013 **         a TEXT or BLOB value)^,
6014 **   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
6015 **         constraint and the blob is being opened for read/write access)^,
6016 **   <li> ^([foreign key constraints | Foreign key constraints] are enabled,
6017 **         column zColumn is part of a [child key] definition and the blob is
6018 **         being opened for read/write access)^.
6019 ** </ul>
6020 **
6021 ** ^Unless it returns SQLITE_MISUSE, this function sets the
6022 ** [database connection] error code and message accessible via
6023 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6024 **
6025 **
6026 ** ^(If the row that a BLOB handle points to is modified by an
6027 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6028 ** then the BLOB handle is marked as "expired".
6029 ** This is true if any column of the row is changed, even a column
6030 ** other than the one the BLOB handle is open on.)^
6031 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6032 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
6033 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
6034 ** rolled back by the expiration of the BLOB.  Such changes will eventually
6035 ** commit if the transaction continues to completion.)^
6036 **
6037 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
6038 ** the opened blob.  ^The size of a blob may not be changed by this
6039 ** interface.  Use the [UPDATE] SQL command to change the size of a
6040 ** blob.
6041 **
6042 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
6043 ** and the built-in [zeroblob] SQL function may be used to create a
6044 ** zero-filled blob to read or write using the incremental-blob interface.
6045 **
6046 ** To avoid a resource leak, every open [BLOB handle] should eventually
6047 ** be released by a call to [sqlite3_blob_close()].
6048 */
6049 SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
6050   sqlite3*,
6051   const char *zDb,
6052   const char *zTable,
6053   const char *zColumn,
6054   sqlite3_int64 iRow,
6055   int flags,
6056   sqlite3_blob **ppBlob
6057 );
6058 
6059 /*
6060 ** CAPI3REF: Move a BLOB Handle to a New Row
6061 ** METHOD: sqlite3_blob
6062 **
6063 ** ^This function is used to move an existing blob handle so that it points
6064 ** to a different row of the same database table. ^The new row is identified
6065 ** by the rowid value passed as the second argument. Only the row can be
6066 ** changed. ^The database, table and column on which the blob handle is open
6067 ** remain the same. Moving an existing blob handle to a new row can be
6068 ** faster than closing the existing handle and opening a new one.
6069 **
6070 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6071 ** it must exist and there must be either a blob or text value stored in
6072 ** the nominated column.)^ ^If the new row is not present in the table, or if
6073 ** it does not contain a blob or text value, or if another error occurs, an
6074 ** SQLite error code is returned and the blob handle is considered aborted.
6075 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6076 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6077 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6078 ** always returns zero.
6079 **
6080 ** ^This function sets the database handle error code and message.
6081 */
6082 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
6083 
6084 /*
6085 ** CAPI3REF: Close A BLOB Handle
6086 ** DESTRUCTOR: sqlite3_blob
6087 **
6088 ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
6089 ** unconditionally.  Even if this routine returns an error code, the
6090 ** handle is still closed.)^
6091 **
6092 ** ^If the blob handle being closed was opened for read-write access, and if
6093 ** the database is in auto-commit mode and there are no other open read-write
6094 ** blob handles or active write statements, the current transaction is
6095 ** committed. ^If an error occurs while committing the transaction, an error
6096 ** code is returned and the transaction rolled back.
6097 **
6098 ** Calling this function with an argument that is not a NULL pointer or an
6099 ** open blob handle results in undefined behaviour. ^Calling this routine
6100 ** with a null pointer (such as would be returned by a failed call to
6101 ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
6102 ** is passed a valid open blob handle, the values returned by the
6103 ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
6104 */
6105 SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *);
6106 
6107 /*
6108 ** CAPI3REF: Return The Size Of An Open BLOB
6109 ** METHOD: sqlite3_blob
6110 **
6111 ** ^Returns the size in bytes of the BLOB accessible via the
6112 ** successfully opened [BLOB handle] in its only argument.  ^The
6113 ** incremental blob I/O routines can only read or overwriting existing
6114 ** blob content; they cannot change the size of a blob.
6115 **
6116 ** This routine only works on a [BLOB handle] which has been created
6117 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6118 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6119 ** to this routine results in undefined and probably undesirable behavior.
6120 */
6121 SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *);
6122 
6123 /*
6124 ** CAPI3REF: Read Data From A BLOB Incrementally
6125 ** METHOD: sqlite3_blob
6126 **
6127 ** ^(This function is used to read data from an open [BLOB handle] into a
6128 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6129 ** from the open BLOB, starting at offset iOffset.)^
6130 **
6131 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6132 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
6133 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6134 ** ^The size of the blob (and hence the maximum value of N+iOffset)
6135 ** can be determined using the [sqlite3_blob_bytes()] interface.
6136 **
6137 ** ^An attempt to read from an expired [BLOB handle] fails with an
6138 ** error code of [SQLITE_ABORT].
6139 **
6140 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6141 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6142 **
6143 ** This routine only works on a [BLOB handle] which has been created
6144 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6145 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6146 ** to this routine results in undefined and probably undesirable behavior.
6147 **
6148 ** See also: [sqlite3_blob_write()].
6149 */
6150 SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6151 
6152 /*
6153 ** CAPI3REF: Write Data Into A BLOB Incrementally
6154 ** METHOD: sqlite3_blob
6155 **
6156 ** ^(This function is used to write data into an open [BLOB handle] from a
6157 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
6158 ** into the open BLOB, starting at offset iOffset.)^
6159 **
6160 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6161 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
6162 ** ^Unless SQLITE_MISUSE is returned, this function sets the
6163 ** [database connection] error code and message accessible via
6164 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6165 **
6166 ** ^If the [BLOB handle] passed as the first argument was not opened for
6167 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6168 ** this function returns [SQLITE_READONLY].
6169 **
6170 ** This function may only modify the contents of the BLOB; it is
6171 ** not possible to increase the size of a BLOB using this API.
6172 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6173 ** [SQLITE_ERROR] is returned and no data is written. The size of the
6174 ** BLOB (and hence the maximum value of N+iOffset) can be determined
6175 ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
6176 ** than zero [SQLITE_ERROR] is returned and no data is written.
6177 **
6178 ** ^An attempt to write to an expired [BLOB handle] fails with an
6179 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
6180 ** before the [BLOB handle] expired are not rolled back by the
6181 ** expiration of the handle, though of course those changes might
6182 ** have been overwritten by the statement that expired the BLOB handle
6183 ** or by other independent statements.
6184 **
6185 ** This routine only works on a [BLOB handle] which has been created
6186 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6187 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6188 ** to this routine results in undefined and probably undesirable behavior.
6189 **
6190 ** See also: [sqlite3_blob_read()].
6191 */
6192 SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6193 
6194 /*
6195 ** CAPI3REF: Virtual File System Objects
6196 **
6197 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6198 ** that SQLite uses to interact
6199 ** with the underlying operating system.  Most SQLite builds come with a
6200 ** single default VFS that is appropriate for the host computer.
6201 ** New VFSes can be registered and existing VFSes can be unregistered.
6202 ** The following interfaces are provided.
6203 **
6204 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6205 ** ^Names are case sensitive.
6206 ** ^Names are zero-terminated UTF-8 strings.
6207 ** ^If there is no match, a NULL pointer is returned.
6208 ** ^If zVfsName is NULL then the default VFS is returned.
6209 **
6210 ** ^New VFSes are registered with sqlite3_vfs_register().
6211 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6212 ** ^The same VFS can be registered multiple times without injury.
6213 ** ^To make an existing VFS into the default VFS, register it again
6214 ** with the makeDflt flag set.  If two different VFSes with the
6215 ** same name are registered, the behavior is undefined.  If a
6216 ** VFS is registered with a name that is NULL or an empty string,
6217 ** then the behavior is undefined.
6218 **
6219 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6220 ** ^(If the default VFS is unregistered, another VFS is chosen as
6221 ** the default.  The choice for the new VFS is arbitrary.)^
6222 */
6223 SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfsName);
6224 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6225 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs*);
6226 
6227 /*
6228 ** CAPI3REF: Mutexes
6229 **
6230 ** The SQLite core uses these routines for thread
6231 ** synchronization. Though they are intended for internal
6232 ** use by SQLite, code that links against SQLite is
6233 ** permitted to use any of these routines.
6234 **
6235 ** The SQLite source code contains multiple implementations
6236 ** of these mutex routines.  An appropriate implementation
6237 ** is selected automatically at compile-time.  The following
6238 ** implementations are available in the SQLite core:
6239 **
6240 ** <ul>
6241 ** <li>   SQLITE_MUTEX_PTHREADS
6242 ** <li>   SQLITE_MUTEX_W32
6243 ** <li>   SQLITE_MUTEX_NOOP
6244 ** </ul>
6245 **
6246 ** The SQLITE_MUTEX_NOOP implementation is a set of routines
6247 ** that does no real locking and is appropriate for use in
6248 ** a single-threaded application.  The SQLITE_MUTEX_PTHREADS and
6249 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6250 ** and Windows.
6251 **
6252 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6253 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6254 ** implementation is included with the library. In this case the
6255 ** application must supply a custom mutex implementation using the
6256 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6257 ** before calling sqlite3_initialize() or any other public sqlite3_
6258 ** function that calls sqlite3_initialize().
6259 **
6260 ** ^The sqlite3_mutex_alloc() routine allocates a new
6261 ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
6262 ** routine returns NULL if it is unable to allocate the requested
6263 ** mutex.  The argument to sqlite3_mutex_alloc() must one of these
6264 ** integer constants:
6265 **
6266 ** <ul>
6267 ** <li>  SQLITE_MUTEX_FAST
6268 ** <li>  SQLITE_MUTEX_RECURSIVE
6269 ** <li>  SQLITE_MUTEX_STATIC_MASTER
6270 ** <li>  SQLITE_MUTEX_STATIC_MEM
6271 ** <li>  SQLITE_MUTEX_STATIC_OPEN
6272 ** <li>  SQLITE_MUTEX_STATIC_PRNG
6273 ** <li>  SQLITE_MUTEX_STATIC_LRU
6274 ** <li>  SQLITE_MUTEX_STATIC_PMEM
6275 ** <li>  SQLITE_MUTEX_STATIC_APP1
6276 ** <li>  SQLITE_MUTEX_STATIC_APP2
6277 ** <li>  SQLITE_MUTEX_STATIC_APP3
6278 ** </ul>
6279 **
6280 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6281 ** cause sqlite3_mutex_alloc() to create
6282 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6283 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6284 ** The mutex implementation does not need to make a distinction
6285 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6286 ** not want to.  SQLite will only request a recursive mutex in
6287 ** cases where it really needs one.  If a faster non-recursive mutex
6288 ** implementation is available on the host platform, the mutex subsystem
6289 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6290 **
6291 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6292 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6293 ** a pointer to a static preexisting mutex.  ^Nine static mutexes are
6294 ** used by the current version of SQLite.  Future versions of SQLite
6295 ** may add additional static mutexes.  Static mutexes are for internal
6296 ** use by SQLite only.  Applications that use SQLite mutexes should
6297 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6298 ** SQLITE_MUTEX_RECURSIVE.
6299 **
6300 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6301 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6302 ** returns a different mutex on every call.  ^For the static
6303 ** mutex types, the same mutex is returned on every call that has
6304 ** the same type number.
6305 **
6306 ** ^The sqlite3_mutex_free() routine deallocates a previously
6307 ** allocated dynamic mutex.  Attempting to deallocate a static
6308 ** mutex results in undefined behavior.
6309 **
6310 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6311 ** to enter a mutex.  ^If another thread is already within the mutex,
6312 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6313 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6314 ** upon successful entry.  ^(Mutexes created using
6315 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6316 ** In such cases, the
6317 ** mutex must be exited an equal number of times before another thread
6318 ** can enter.)^  If the same thread tries to enter any mutex other
6319 ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
6320 **
6321 ** ^(Some systems (for example, Windows 95) do not support the operation
6322 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6323 ** will always return SQLITE_BUSY. The SQLite core only ever uses
6324 ** sqlite3_mutex_try() as an optimization so this is acceptable
6325 ** behavior.)^
6326 **
6327 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6328 ** previously entered by the same thread.   The behavior
6329 ** is undefined if the mutex is not currently entered by the
6330 ** calling thread or is not currently allocated.
6331 **
6332 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6333 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6334 ** behave as no-ops.
6335 **
6336 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6337 */
6338 SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int);
6339 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex*);
6340 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex*);
6341 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex*);
6342 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex*);
6343 
6344 /*
6345 ** CAPI3REF: Mutex Methods Object
6346 **
6347 ** An instance of this structure defines the low-level routines
6348 ** used to allocate and use mutexes.
6349 **
6350 ** Usually, the default mutex implementations provided by SQLite are
6351 ** sufficient, however the application has the option of substituting a custom
6352 ** implementation for specialized deployments or systems for which SQLite
6353 ** does not provide a suitable implementation. In this case, the application
6354 ** creates and populates an instance of this structure to pass
6355 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6356 ** Additionally, an instance of this structure can be used as an
6357 ** output variable when querying the system for the current mutex
6358 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6359 **
6360 ** ^The xMutexInit method defined by this structure is invoked as
6361 ** part of system initialization by the sqlite3_initialize() function.
6362 ** ^The xMutexInit routine is called by SQLite exactly once for each
6363 ** effective call to [sqlite3_initialize()].
6364 **
6365 ** ^The xMutexEnd method defined by this structure is invoked as
6366 ** part of system shutdown by the sqlite3_shutdown() function. The
6367 ** implementation of this method is expected to release all outstanding
6368 ** resources obtained by the mutex methods implementation, especially
6369 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
6370 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6371 **
6372 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6373 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6374 ** xMutexNotheld) implement the following interfaces (respectively):
6375 **
6376 ** <ul>
6377 **   <li>  [sqlite3_mutex_alloc()] </li>
6378 **   <li>  [sqlite3_mutex_free()] </li>
6379 **   <li>  [sqlite3_mutex_enter()] </li>
6380 **   <li>  [sqlite3_mutex_try()] </li>
6381 **   <li>  [sqlite3_mutex_leave()] </li>
6382 **   <li>  [sqlite3_mutex_held()] </li>
6383 **   <li>  [sqlite3_mutex_notheld()] </li>
6384 ** </ul>)^
6385 **
6386 ** The only difference is that the public sqlite3_XXX functions enumerated
6387 ** above silently ignore any invocations that pass a NULL pointer instead
6388 ** of a valid mutex handle. The implementations of the methods defined
6389 ** by this structure are not required to handle this case, the results
6390 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6391 ** (i.e. it is acceptable to provide an implementation that segfaults if
6392 ** it is passed a NULL pointer).
6393 **
6394 ** The xMutexInit() method must be threadsafe.  It must be harmless to
6395 ** invoke xMutexInit() multiple times within the same process and without
6396 ** intervening calls to xMutexEnd().  Second and subsequent calls to
6397 ** xMutexInit() must be no-ops.
6398 **
6399 ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6400 ** and its associates).  Similarly, xMutexAlloc() must not use SQLite memory
6401 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6402 ** memory allocation for a fast or recursive mutex.
6403 **
6404 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6405 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6406 ** If xMutexInit fails in any way, it is expected to clean up after itself
6407 ** prior to returning.
6408 */
6409 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6410 struct sqlite3_mutex_methods {
6411   int (*xMutexInit)(void);
6412   int (*xMutexEnd)(void);
6413   sqlite3_mutex *(*xMutexAlloc)(int);
6414   void (*xMutexFree)(sqlite3_mutex *);
6415   void (*xMutexEnter)(sqlite3_mutex *);
6416   int (*xMutexTry)(sqlite3_mutex *);
6417   void (*xMutexLeave)(sqlite3_mutex *);
6418   int (*xMutexHeld)(sqlite3_mutex *);
6419   int (*xMutexNotheld)(sqlite3_mutex *);
6420 };
6421 
6422 /*
6423 ** CAPI3REF: Mutex Verification Routines
6424 **
6425 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6426 ** are intended for use inside assert() statements.  The SQLite core
6427 ** never uses these routines except inside an assert() and applications
6428 ** are advised to follow the lead of the core.  The SQLite core only
6429 ** provides implementations for these routines when it is compiled
6430 ** with the SQLITE_DEBUG flag.  External mutex implementations
6431 ** are only required to provide these routines if SQLITE_DEBUG is
6432 ** defined and if NDEBUG is not defined.
6433 **
6434 ** These routines should return true if the mutex in their argument
6435 ** is held or not held, respectively, by the calling thread.
6436 **
6437 ** The implementation is not required to provide versions of these
6438 ** routines that actually work. If the implementation does not provide working
6439 ** versions of these routines, it should at least provide stubs that always
6440 ** return true so that one does not get spurious assertion failures.
6441 **
6442 ** If the argument to sqlite3_mutex_held() is a NULL pointer then
6443 ** the routine should return 1.   This seems counter-intuitive since
6444 ** clearly the mutex cannot be held if it does not exist.  But
6445 ** the reason the mutex does not exist is because the build is not
6446 ** using mutexes.  And we do not want the assert() containing the
6447 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6448 ** the appropriate thing to do.  The sqlite3_mutex_notheld()
6449 ** interface should also return 1 when given a NULL pointer.
6450 */
6451 #ifndef NDEBUG
6452 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex*);
6453 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex*);
6454 #endif
6455 
6456 /*
6457 ** CAPI3REF: Mutex Types
6458 **
6459 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6460 ** which is one of these integer constants.
6461 **
6462 ** The set of static mutexes may change from one SQLite release to the
6463 ** next.  Applications that override the built-in mutex logic must be
6464 ** prepared to accommodate additional static mutexes.
6465 */
6466 #define SQLITE_MUTEX_FAST             0
6467 #define SQLITE_MUTEX_RECURSIVE        1
6468 #define SQLITE_MUTEX_STATIC_MASTER    2
6469 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6470 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6471 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6472 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6473 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6474 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6475 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6476 #define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */
6477 #define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */
6478 #define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */
6479 
6480 /*
6481 ** CAPI3REF: Retrieve the mutex for a database connection
6482 ** METHOD: sqlite3
6483 **
6484 ** ^This interface returns a pointer the [sqlite3_mutex] object that
6485 ** serializes access to the [database connection] given in the argument
6486 ** when the [threading mode] is Serialized.
6487 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6488 ** routine returns a NULL pointer.
6489 */
6490 SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3*);
6491 
6492 /*
6493 ** CAPI3REF: Low-Level Control Of Database Files
6494 ** METHOD: sqlite3
6495 **
6496 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6497 ** xFileControl method for the [sqlite3_io_methods] object associated
6498 ** with a particular database identified by the second argument. ^The
6499 ** name of the database is "main" for the main database or "temp" for the
6500 ** TEMP database, or the name that appears after the AS keyword for
6501 ** databases that are added using the [ATTACH] SQL command.
6502 ** ^A NULL pointer can be used in place of "main" to refer to the
6503 ** main database file.
6504 ** ^The third and fourth parameters to this routine
6505 ** are passed directly through to the second and third parameters of
6506 ** the xFileControl method.  ^The return value of the xFileControl
6507 ** method becomes the return value of this routine.
6508 **
6509 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6510 ** a pointer to the underlying [sqlite3_file] object to be written into
6511 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6512 ** case is a short-circuit path which does not actually invoke the
6513 ** underlying sqlite3_io_methods.xFileControl method.
6514 **
6515 ** ^If the second parameter (zDbName) does not match the name of any
6516 ** open database file, then SQLITE_ERROR is returned.  ^This error
6517 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6518 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
6519 ** also return SQLITE_ERROR.  There is no way to distinguish between
6520 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6521 ** xFileControl method.
6522 **
6523 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6524 */
6525 SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6526 
6527 /*
6528 ** CAPI3REF: Testing Interface
6529 **
6530 ** ^The sqlite3_test_control() interface is used to read out internal
6531 ** state of SQLite and to inject faults into SQLite for testing
6532 ** purposes.  ^The first parameter is an operation code that determines
6533 ** the number, meaning, and operation of all subsequent parameters.
6534 **
6535 ** This interface is not for use by applications.  It exists solely
6536 ** for verifying the correct operation of the SQLite library.  Depending
6537 ** on how the SQLite library is compiled, this interface might not exist.
6538 **
6539 ** The details of the operation codes, their meanings, the parameters
6540 ** they take, and what they do are all subject to change without notice.
6541 ** Unlike most of the SQLite API, this function is not guaranteed to
6542 ** operate consistently from one release to the next.
6543 */
6544 SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...);
6545 
6546 /*
6547 ** CAPI3REF: Testing Interface Operation Codes
6548 **
6549 ** These constants are the valid operation code parameters used
6550 ** as the first argument to [sqlite3_test_control()].
6551 **
6552 ** These parameters and their meanings are subject to change
6553 ** without notice.  These values are for testing purposes only.
6554 ** Applications should not use any of these parameters or the
6555 ** [sqlite3_test_control()] interface.
6556 */
6557 #define SQLITE_TESTCTRL_FIRST                    5
6558 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6559 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6560 #define SQLITE_TESTCTRL_PRNG_RESET               7
6561 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6562 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6563 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6564 #define SQLITE_TESTCTRL_PENDING_BYTE            11
6565 #define SQLITE_TESTCTRL_ASSERT                  12
6566 #define SQLITE_TESTCTRL_ALWAYS                  13
6567 #define SQLITE_TESTCTRL_RESERVE                 14
6568 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6569 #define SQLITE_TESTCTRL_ISKEYWORD               16
6570 #define SQLITE_TESTCTRL_SCRATCHMALLOC           17
6571 #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
6572 #define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */
6573 #define SQLITE_TESTCTRL_NEVER_CORRUPT           20
6574 #define SQLITE_TESTCTRL_VDBE_COVERAGE           21
6575 #define SQLITE_TESTCTRL_BYTEORDER               22
6576 #define SQLITE_TESTCTRL_ISINIT                  23
6577 #define SQLITE_TESTCTRL_SORTER_MMAP             24
6578 #define SQLITE_TESTCTRL_IMPOSTER                25
6579 #define SQLITE_TESTCTRL_LAST                    25
6580 
6581 /*
6582 ** CAPI3REF: SQLite Runtime Status
6583 **
6584 ** ^These interfaces are used to retrieve runtime status information
6585 ** about the performance of SQLite, and optionally to reset various
6586 ** highwater marks.  ^The first argument is an integer code for
6587 ** the specific parameter to measure.  ^(Recognized integer codes
6588 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6589 ** ^The current value of the parameter is returned into *pCurrent.
6590 ** ^The highest recorded value is returned in *pHighwater.  ^If the
6591 ** resetFlag is true, then the highest record value is reset after
6592 ** *pHighwater is written.  ^(Some parameters do not record the highest
6593 ** value.  For those parameters
6594 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6595 ** ^(Other parameters record only the highwater mark and not the current
6596 ** value.  For these latter parameters nothing is written into *pCurrent.)^
6597 **
6598 ** ^The sqlite3_status() and sqlite3_status64() routines return
6599 ** SQLITE_OK on success and a non-zero [error code] on failure.
6600 **
6601 ** If either the current value or the highwater mark is too large to
6602 ** be represented by a 32-bit integer, then the values returned by
6603 ** sqlite3_status() are undefined.
6604 **
6605 ** See also: [sqlite3_db_status()]
6606 */
6607 SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6608 SQLITE_API int SQLITE_STDCALL sqlite3_status64(
6609   int op,
6610   sqlite3_int64 *pCurrent,
6611   sqlite3_int64 *pHighwater,
6612   int resetFlag
6613 );
6614 
6615 
6616 /*
6617 ** CAPI3REF: Status Parameters
6618 ** KEYWORDS: {status parameters}
6619 **
6620 ** These integer constants designate various run-time status parameters
6621 ** that can be returned by [sqlite3_status()].
6622 **
6623 ** <dl>
6624 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6625 ** <dd>This parameter is the current amount of memory checked out
6626 ** using [sqlite3_malloc()], either directly or indirectly.  The
6627 ** figure includes calls made to [sqlite3_malloc()] by the application
6628 ** and internal memory usage by the SQLite library.  Scratch memory
6629 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6630 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6631 ** this parameter.  The amount returned is the sum of the allocation
6632 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6633 **
6634 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6635 ** <dd>This parameter records the largest memory allocation request
6636 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6637 ** internal equivalents).  Only the value returned in the
6638 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6639 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6640 **
6641 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6642 ** <dd>This parameter records the number of separate memory allocations
6643 ** currently checked out.</dd>)^
6644 **
6645 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6646 ** <dd>This parameter returns the number of pages used out of the
6647 ** [pagecache memory allocator] that was configured using
6648 ** [SQLITE_CONFIG_PAGECACHE].  The
6649 ** value returned is in pages, not in bytes.</dd>)^
6650 **
6651 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6652 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6653 ** <dd>This parameter returns the number of bytes of page cache
6654 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6655 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6656 ** returned value includes allocations that overflowed because they
6657 ** where too large (they were larger than the "sz" parameter to
6658 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6659 ** no space was left in the page cache.</dd>)^
6660 **
6661 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6662 ** <dd>This parameter records the largest memory allocation request
6663 ** handed to [pagecache memory allocator].  Only the value returned in the
6664 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6665 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6666 **
6667 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6668 ** <dd>This parameter returns the number of allocations used out of the
6669 ** [scratch memory allocator] configured using
6670 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6671 ** in bytes.  Since a single thread may only have one scratch allocation
6672 ** outstanding at time, this parameter also reports the number of threads
6673 ** using scratch memory at the same time.</dd>)^
6674 **
6675 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6676 ** <dd>This parameter returns the number of bytes of scratch memory
6677 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6678 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6679 ** returned include overflows because the requested allocation was too
6680 ** larger (that is, because the requested allocation was larger than the
6681 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6682 ** slots were available.
6683 ** </dd>)^
6684 **
6685 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6686 ** <dd>This parameter records the largest memory allocation request
6687 ** handed to [scratch memory allocator].  Only the value returned in the
6688 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6689 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6690 **
6691 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6692 ** <dd>This parameter records the deepest parser stack.  It is only
6693 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6694 ** </dl>
6695 **
6696 ** New status parameters may be added from time to time.
6697 */
6698 #define SQLITE_STATUS_MEMORY_USED          0
6699 #define SQLITE_STATUS_PAGECACHE_USED       1
6700 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6701 #define SQLITE_STATUS_SCRATCH_USED         3
6702 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6703 #define SQLITE_STATUS_MALLOC_SIZE          5
6704 #define SQLITE_STATUS_PARSER_STACK         6
6705 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6706 #define SQLITE_STATUS_SCRATCH_SIZE         8
6707 #define SQLITE_STATUS_MALLOC_COUNT         9
6708 
6709 /*
6710 ** CAPI3REF: Database Connection Status
6711 ** METHOD: sqlite3
6712 **
6713 ** ^This interface is used to retrieve runtime status information
6714 ** about a single [database connection].  ^The first argument is the
6715 ** database connection object to be interrogated.  ^The second argument
6716 ** is an integer constant, taken from the set of
6717 ** [SQLITE_DBSTATUS options], that
6718 ** determines the parameter to interrogate.  The set of
6719 ** [SQLITE_DBSTATUS options] is likely
6720 ** to grow in future releases of SQLite.
6721 **
6722 ** ^The current value of the requested parameter is written into *pCur
6723 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6724 ** the resetFlg is true, then the highest instantaneous value is
6725 ** reset back down to the current value.
6726 **
6727 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6728 ** non-zero [error code] on failure.
6729 **
6730 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6731 */
6732 SQLITE_API int SQLITE_STDCALL sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6733 
6734 /*
6735 ** CAPI3REF: Status Parameters for database connections
6736 ** KEYWORDS: {SQLITE_DBSTATUS options}
6737 **
6738 ** These constants are the available integer "verbs" that can be passed as
6739 ** the second argument to the [sqlite3_db_status()] interface.
6740 **
6741 ** New verbs may be added in future releases of SQLite. Existing verbs
6742 ** might be discontinued. Applications should check the return code from
6743 ** [sqlite3_db_status()] to make sure that the call worked.
6744 ** The [sqlite3_db_status()] interface will return a non-zero error code
6745 ** if a discontinued or unsupported verb is invoked.
6746 **
6747 ** <dl>
6748 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6749 ** <dd>This parameter returns the number of lookaside memory slots currently
6750 ** checked out.</dd>)^
6751 **
6752 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6753 ** <dd>This parameter returns the number malloc attempts that were
6754 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6755 ** the current value is always zero.)^
6756 **
6757 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6758 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6759 ** <dd>This parameter returns the number malloc attempts that might have
6760 ** been satisfied using lookaside memory but failed due to the amount of
6761 ** memory requested being larger than the lookaside slot size.
6762 ** Only the high-water value is meaningful;
6763 ** the current value is always zero.)^
6764 **
6765 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6766 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6767 ** <dd>This parameter returns the number malloc attempts that might have
6768 ** been satisfied using lookaside memory but failed due to all lookaside
6769 ** memory already being in use.
6770 ** Only the high-water value is meaningful;
6771 ** the current value is always zero.)^
6772 **
6773 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6774 ** <dd>This parameter returns the approximate number of bytes of heap
6775 ** memory used by all pager caches associated with the database connection.)^
6776 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6777 **
6778 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6779 ** <dd>This parameter returns the approximate number of bytes of heap
6780 ** memory used to store the schema for all databases associated
6781 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6782 ** ^The full amount of memory used by the schemas is reported, even if the
6783 ** schema memory is shared with other database connections due to
6784 ** [shared cache mode] being enabled.
6785 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6786 **
6787 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6788 ** <dd>This parameter returns the approximate number of bytes of heap
6789 ** and lookaside memory used by all prepared statements associated with
6790 ** the database connection.)^
6791 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6792 ** </dd>
6793 **
6794 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6795 ** <dd>This parameter returns the number of pager cache hits that have
6796 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
6797 ** is always 0.
6798 ** </dd>
6799 **
6800 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6801 ** <dd>This parameter returns the number of pager cache misses that have
6802 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
6803 ** is always 0.
6804 ** </dd>
6805 **
6806 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6807 ** <dd>This parameter returns the number of dirty cache entries that have
6808 ** been written to disk. Specifically, the number of pages written to the
6809 ** wal file in wal mode databases, or the number of pages written to the
6810 ** database file in rollback mode databases. Any pages written as part of
6811 ** transaction rollback or database recovery operations are not included.
6812 ** If an IO or other error occurs while writing a page to disk, the effect
6813 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6814 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6815 ** </dd>
6816 **
6817 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
6818 ** <dd>This parameter returns zero for the current value if and only if
6819 ** all foreign key constraints (deferred or immediate) have been
6820 ** resolved.)^  ^The highwater mark is always 0.
6821 ** </dd>
6822 ** </dl>
6823 */
6824 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6825 #define SQLITE_DBSTATUS_CACHE_USED           1
6826 #define SQLITE_DBSTATUS_SCHEMA_USED          2
6827 #define SQLITE_DBSTATUS_STMT_USED            3
6828 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6829 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6830 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6831 #define SQLITE_DBSTATUS_CACHE_HIT            7
6832 #define SQLITE_DBSTATUS_CACHE_MISS           8
6833 #define SQLITE_DBSTATUS_CACHE_WRITE          9
6834 #define SQLITE_DBSTATUS_DEFERRED_FKS        10
6835 #define SQLITE_DBSTATUS_MAX                 10   /* Largest defined DBSTATUS */
6836 
6837 
6838 /*
6839 ** CAPI3REF: Prepared Statement Status
6840 ** METHOD: sqlite3_stmt
6841 **
6842 ** ^(Each prepared statement maintains various
6843 ** [SQLITE_STMTSTATUS counters] that measure the number
6844 ** of times it has performed specific operations.)^  These counters can
6845 ** be used to monitor the performance characteristics of the prepared
6846 ** statements.  For example, if the number of table steps greatly exceeds
6847 ** the number of table searches or result rows, that would tend to indicate
6848 ** that the prepared statement is using a full table scan rather than
6849 ** an index.
6850 **
6851 ** ^(This interface is used to retrieve and reset counter values from
6852 ** a [prepared statement].  The first argument is the prepared statement
6853 ** object to be interrogated.  The second argument
6854 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6855 ** to be interrogated.)^
6856 ** ^The current value of the requested counter is returned.
6857 ** ^If the resetFlg is true, then the counter is reset to zero after this
6858 ** interface call returns.
6859 **
6860 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6861 */
6862 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6863 
6864 /*
6865 ** CAPI3REF: Status Parameters for prepared statements
6866 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6867 **
6868 ** These preprocessor macros define integer codes that name counter
6869 ** values associated with the [sqlite3_stmt_status()] interface.
6870 ** The meanings of the various counters are as follows:
6871 **
6872 ** <dl>
6873 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6874 ** <dd>^This is the number of times that SQLite has stepped forward in
6875 ** a table as part of a full table scan.  Large numbers for this counter
6876 ** may indicate opportunities for performance improvement through
6877 ** careful use of indices.</dd>
6878 **
6879 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6880 ** <dd>^This is the number of sort operations that have occurred.
6881 ** A non-zero value in this counter may indicate an opportunity to
6882 ** improvement performance through careful use of indices.</dd>
6883 **
6884 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6885 ** <dd>^This is the number of rows inserted into transient indices that
6886 ** were created automatically in order to help joins run faster.
6887 ** A non-zero value in this counter may indicate an opportunity to
6888 ** improvement performance by adding permanent indices that do not
6889 ** need to be reinitialized each time the statement is run.</dd>
6890 **
6891 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
6892 ** <dd>^This is the number of virtual machine operations executed
6893 ** by the prepared statement if that number is less than or equal
6894 ** to 2147483647.  The number of virtual machine operations can be
6895 ** used as a proxy for the total work done by the prepared statement.
6896 ** If the number of virtual machine operations exceeds 2147483647
6897 ** then the value returned by this statement status code is undefined.
6898 ** </dd>
6899 ** </dl>
6900 */
6901 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6902 #define SQLITE_STMTSTATUS_SORT              2
6903 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6904 #define SQLITE_STMTSTATUS_VM_STEP           4
6905 
6906 /*
6907 ** CAPI3REF: Custom Page Cache Object
6908 **
6909 ** The sqlite3_pcache type is opaque.  It is implemented by
6910 ** the pluggable module.  The SQLite core has no knowledge of
6911 ** its size or internal structure and never deals with the
6912 ** sqlite3_pcache object except by holding and passing pointers
6913 ** to the object.
6914 **
6915 ** See [sqlite3_pcache_methods2] for additional information.
6916 */
6917 typedef struct sqlite3_pcache sqlite3_pcache;
6918 
6919 /*
6920 ** CAPI3REF: Custom Page Cache Object
6921 **
6922 ** The sqlite3_pcache_page object represents a single page in the
6923 ** page cache.  The page cache will allocate instances of this
6924 ** object.  Various methods of the page cache use pointers to instances
6925 ** of this object as parameters or as their return value.
6926 **
6927 ** See [sqlite3_pcache_methods2] for additional information.
6928 */
6929 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6930 struct sqlite3_pcache_page {
6931   void *pBuf;        /* The content of the page */
6932   void *pExtra;      /* Extra information associated with the page */
6933 };
6934 
6935 /*
6936 ** CAPI3REF: Application Defined Page Cache.
6937 ** KEYWORDS: {page cache}
6938 **
6939 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6940 ** register an alternative page cache implementation by passing in an
6941 ** instance of the sqlite3_pcache_methods2 structure.)^
6942 ** In many applications, most of the heap memory allocated by
6943 ** SQLite is used for the page cache.
6944 ** By implementing a
6945 ** custom page cache using this API, an application can better control
6946 ** the amount of memory consumed by SQLite, the way in which
6947 ** that memory is allocated and released, and the policies used to
6948 ** determine exactly which parts of a database file are cached and for
6949 ** how long.
6950 **
6951 ** The alternative page cache mechanism is an
6952 ** extreme measure that is only needed by the most demanding applications.
6953 ** The built-in page cache is recommended for most uses.
6954 **
6955 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6956 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6957 ** the application may discard the parameter after the call to
6958 ** [sqlite3_config()] returns.)^
6959 **
6960 ** [[the xInit() page cache method]]
6961 ** ^(The xInit() method is called once for each effective
6962 ** call to [sqlite3_initialize()])^
6963 ** (usually only once during the lifetime of the process). ^(The xInit()
6964 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6965 ** The intent of the xInit() method is to set up global data structures
6966 ** required by the custom page cache implementation.
6967 ** ^(If the xInit() method is NULL, then the
6968 ** built-in default page cache is used instead of the application defined
6969 ** page cache.)^
6970 **
6971 ** [[the xShutdown() page cache method]]
6972 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6973 ** It can be used to clean up
6974 ** any outstanding resources before process shutdown, if required.
6975 ** ^The xShutdown() method may be NULL.
6976 **
6977 ** ^SQLite automatically serializes calls to the xInit method,
6978 ** so the xInit method need not be threadsafe.  ^The
6979 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6980 ** not need to be threadsafe either.  All other methods must be threadsafe
6981 ** in multithreaded applications.
6982 **
6983 ** ^SQLite will never invoke xInit() more than once without an intervening
6984 ** call to xShutdown().
6985 **
6986 ** [[the xCreate() page cache methods]]
6987 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6988 ** SQLite will typically create one cache instance for each open database file,
6989 ** though this is not guaranteed. ^The
6990 ** first parameter, szPage, is the size in bytes of the pages that must
6991 ** be allocated by the cache.  ^szPage will always a power of two.  ^The
6992 ** second parameter szExtra is a number of bytes of extra storage
6993 ** associated with each page cache entry.  ^The szExtra parameter will
6994 ** a number less than 250.  SQLite will use the
6995 ** extra szExtra bytes on each page to store metadata about the underlying
6996 ** database page on disk.  The value passed into szExtra depends
6997 ** on the SQLite version, the target platform, and how SQLite was compiled.
6998 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
6999 ** created will be used to cache database pages of a file stored on disk, or
7000 ** false if it is used for an in-memory database. The cache implementation
7001 ** does not have to do anything special based with the value of bPurgeable;
7002 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
7003 ** never invoke xUnpin() except to deliberately delete a page.
7004 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
7005 ** false will always have the "discard" flag set to true.
7006 ** ^Hence, a cache created with bPurgeable false will
7007 ** never contain any unpinned pages.
7008 **
7009 ** [[the xCachesize() page cache method]]
7010 ** ^(The xCachesize() method may be called at any time by SQLite to set the
7011 ** suggested maximum cache-size (number of pages stored by) the cache
7012 ** instance passed as the first argument. This is the value configured using
7013 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
7014 ** parameter, the implementation is not required to do anything with this
7015 ** value; it is advisory only.
7016 **
7017 ** [[the xPagecount() page cache methods]]
7018 ** The xPagecount() method must return the number of pages currently
7019 ** stored in the cache, both pinned and unpinned.
7020 **
7021 ** [[the xFetch() page cache methods]]
7022 ** The xFetch() method locates a page in the cache and returns a pointer to
7023 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
7024 ** The pBuf element of the returned sqlite3_pcache_page object will be a
7025 ** pointer to a buffer of szPage bytes used to store the content of a
7026 ** single database page.  The pExtra element of sqlite3_pcache_page will be
7027 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
7028 ** for each entry in the page cache.
7029 **
7030 ** The page to be fetched is determined by the key. ^The minimum key value
7031 ** is 1.  After it has been retrieved using xFetch, the page is considered
7032 ** to be "pinned".
7033 **
7034 ** If the requested page is already in the page cache, then the page cache
7035 ** implementation must return a pointer to the page buffer with its content
7036 ** intact.  If the requested page is not already in the cache, then the
7037 ** cache implementation should use the value of the createFlag
7038 ** parameter to help it determined what action to take:
7039 **
7040 ** <table border=1 width=85% align=center>
7041 ** <tr><th> createFlag <th> Behavior when page is not already in cache
7042 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
7043 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
7044 **                 Otherwise return NULL.
7045 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
7046 **                 NULL if allocating a new page is effectively impossible.
7047 ** </table>
7048 **
7049 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
7050 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
7051 ** failed.)^  In between the to xFetch() calls, SQLite may
7052 ** attempt to unpin one or more cache pages by spilling the content of
7053 ** pinned pages to disk and synching the operating system disk cache.
7054 **
7055 ** [[the xUnpin() page cache method]]
7056 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
7057 ** as its second argument.  If the third parameter, discard, is non-zero,
7058 ** then the page must be evicted from the cache.
7059 ** ^If the discard parameter is
7060 ** zero, then the page may be discarded or retained at the discretion of
7061 ** page cache implementation. ^The page cache implementation
7062 ** may choose to evict unpinned pages at any time.
7063 **
7064 ** The cache must not perform any reference counting. A single
7065 ** call to xUnpin() unpins the page regardless of the number of prior calls
7066 ** to xFetch().
7067 **
7068 ** [[the xRekey() page cache methods]]
7069 ** The xRekey() method is used to change the key value associated with the
7070 ** page passed as the second argument. If the cache
7071 ** previously contains an entry associated with newKey, it must be
7072 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
7073 ** to be pinned.
7074 **
7075 ** When SQLite calls the xTruncate() method, the cache must discard all
7076 ** existing cache entries with page numbers (keys) greater than or equal
7077 ** to the value of the iLimit parameter passed to xTruncate(). If any
7078 ** of these pages are pinned, they are implicitly unpinned, meaning that
7079 ** they can be safely discarded.
7080 **
7081 ** [[the xDestroy() page cache method]]
7082 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
7083 ** All resources associated with the specified cache should be freed. ^After
7084 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7085 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
7086 ** functions.
7087 **
7088 ** [[the xShrink() page cache method]]
7089 ** ^SQLite invokes the xShrink() method when it wants the page cache to
7090 ** free up as much of heap memory as possible.  The page cache implementation
7091 ** is not obligated to free any memory, but well-behaved implementations should
7092 ** do their best.
7093 */
7094 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
7095 struct sqlite3_pcache_methods2 {
7096   int iVersion;
7097   void *pArg;
7098   int (*xInit)(void*);
7099   void (*xShutdown)(void*);
7100   sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
7101   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7102   int (*xPagecount)(sqlite3_pcache*);
7103   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7104   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7105   void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
7106       unsigned oldKey, unsigned newKey);
7107   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7108   void (*xDestroy)(sqlite3_pcache*);
7109   void (*xShrink)(sqlite3_pcache*);
7110 };
7111 
7112 /*
7113 ** This is the obsolete pcache_methods object that has now been replaced
7114 ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
7115 ** retained in the header file for backwards compatibility only.
7116 */
7117 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7118 struct sqlite3_pcache_methods {
7119   void *pArg;
7120   int (*xInit)(void*);
7121   void (*xShutdown)(void*);
7122   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7123   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7124   int (*xPagecount)(sqlite3_pcache*);
7125   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7126   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7127   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7128   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7129   void (*xDestroy)(sqlite3_pcache*);
7130 };
7131 
7132 
7133 /*
7134 ** CAPI3REF: Online Backup Object
7135 **
7136 ** The sqlite3_backup object records state information about an ongoing
7137 ** online backup operation.  ^The sqlite3_backup object is created by
7138 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
7139 ** [sqlite3_backup_finish()].
7140 **
7141 ** See Also: [Using the SQLite Online Backup API]
7142 */
7143 typedef struct sqlite3_backup sqlite3_backup;
7144 
7145 /*
7146 ** CAPI3REF: Online Backup API.
7147 **
7148 ** The backup API copies the content of one database into another.
7149 ** It is useful either for creating backups of databases or
7150 ** for copying in-memory databases to or from persistent files.
7151 **
7152 ** See Also: [Using the SQLite Online Backup API]
7153 **
7154 ** ^SQLite holds a write transaction open on the destination database file
7155 ** for the duration of the backup operation.
7156 ** ^The source database is read-locked only while it is being read;
7157 ** it is not locked continuously for the entire backup operation.
7158 ** ^Thus, the backup may be performed on a live source database without
7159 ** preventing other database connections from
7160 ** reading or writing to the source database while the backup is underway.
7161 **
7162 ** ^(To perform a backup operation:
7163 **   <ol>
7164 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
7165 **         backup,
7166 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
7167 **         the data between the two databases, and finally
7168 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources
7169 **         associated with the backup operation.
7170 **   </ol>)^
7171 ** There should be exactly one call to sqlite3_backup_finish() for each
7172 ** successful call to sqlite3_backup_init().
7173 **
7174 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7175 **
7176 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
7177 ** [database connection] associated with the destination database
7178 ** and the database name, respectively.
7179 ** ^The database name is "main" for the main database, "temp" for the
7180 ** temporary database, or the name specified after the AS keyword in
7181 ** an [ATTACH] statement for an attached database.
7182 ** ^The S and M arguments passed to
7183 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7184 ** and database name of the source database, respectively.
7185 ** ^The source and destination [database connections] (parameters S and D)
7186 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7187 ** an error.
7188 **
7189 ** ^A call to sqlite3_backup_init() will fail, returning SQLITE_ERROR, if
7190 ** there is already a read or read-write transaction open on the
7191 ** destination database.
7192 **
7193 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7194 ** returned and an error code and error message are stored in the
7195 ** destination [database connection] D.
7196 ** ^The error code and message for the failed call to sqlite3_backup_init()
7197 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7198 ** [sqlite3_errmsg16()] functions.
7199 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
7200 ** [sqlite3_backup] object.
7201 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7202 ** sqlite3_backup_finish() functions to perform the specified backup
7203 ** operation.
7204 **
7205 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7206 **
7207 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
7208 ** the source and destination databases specified by [sqlite3_backup] object B.
7209 ** ^If N is negative, all remaining source pages are copied.
7210 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7211 ** are still more pages to be copied, then the function returns [SQLITE_OK].
7212 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7213 ** from source to destination, then it returns [SQLITE_DONE].
7214 ** ^If an error occurs while running sqlite3_backup_step(B,N),
7215 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
7216 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7217 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7218 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7219 **
7220 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7221 ** <ol>
7222 ** <li> the destination database was opened read-only, or
7223 ** <li> the destination database is using write-ahead-log journaling
7224 ** and the destination and source page sizes differ, or
7225 ** <li> the destination database is an in-memory database and the
7226 ** destination and source page sizes differ.
7227 ** </ol>)^
7228 **
7229 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7230 ** the [sqlite3_busy_handler | busy-handler function]
7231 ** is invoked (if one is specified). ^If the
7232 ** busy-handler returns non-zero before the lock is available, then
7233 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7234 ** sqlite3_backup_step() can be retried later. ^If the source
7235 ** [database connection]
7236 ** is being used to write to the source database when sqlite3_backup_step()
7237 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7238 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
7239 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7240 ** [SQLITE_READONLY] is returned, then
7241 ** there is no point in retrying the call to sqlite3_backup_step(). These
7242 ** errors are considered fatal.)^  The application must accept
7243 ** that the backup operation has failed and pass the backup operation handle
7244 ** to the sqlite3_backup_finish() to release associated resources.
7245 **
7246 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7247 ** on the destination file. ^The exclusive lock is not released until either
7248 ** sqlite3_backup_finish() is called or the backup operation is complete
7249 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
7250 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7251 ** lasts for the duration of the sqlite3_backup_step() call.
7252 ** ^Because the source database is not locked between calls to
7253 ** sqlite3_backup_step(), the source database may be modified mid-way
7254 ** through the backup process.  ^If the source database is modified by an
7255 ** external process or via a database connection other than the one being
7256 ** used by the backup operation, then the backup will be automatically
7257 ** restarted by the next call to sqlite3_backup_step(). ^If the source
7258 ** database is modified by the using the same database connection as is used
7259 ** by the backup operation, then the backup database is automatically
7260 ** updated at the same time.
7261 **
7262 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7263 **
7264 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
7265 ** application wishes to abandon the backup operation, the application
7266 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7267 ** ^The sqlite3_backup_finish() interfaces releases all
7268 ** resources associated with the [sqlite3_backup] object.
7269 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7270 ** active write-transaction on the destination database is rolled back.
7271 ** The [sqlite3_backup] object is invalid
7272 ** and may not be used following a call to sqlite3_backup_finish().
7273 **
7274 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7275 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7276 ** sqlite3_backup_step() completed.
7277 ** ^If an out-of-memory condition or IO error occurred during any prior
7278 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7279 ** sqlite3_backup_finish() returns the corresponding [error code].
7280 **
7281 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7282 ** is not a permanent error and does not affect the return value of
7283 ** sqlite3_backup_finish().
7284 **
7285 ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
7286 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7287 **
7288 ** ^The sqlite3_backup_remaining() routine returns the number of pages still
7289 ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
7290 ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
7291 ** in the source database at the conclusion of the most recent
7292 ** sqlite3_backup_step().
7293 ** ^(The values returned by these functions are only updated by
7294 ** sqlite3_backup_step(). If the source database is modified in a way that
7295 ** changes the size of the source database or the number of pages remaining,
7296 ** those changes are not reflected in the output of sqlite3_backup_pagecount()
7297 ** and sqlite3_backup_remaining() until after the next
7298 ** sqlite3_backup_step().)^
7299 **
7300 ** <b>Concurrent Usage of Database Handles</b>
7301 **
7302 ** ^The source [database connection] may be used by the application for other
7303 ** purposes while a backup operation is underway or being initialized.
7304 ** ^If SQLite is compiled and configured to support threadsafe database
7305 ** connections, then the source database connection may be used concurrently
7306 ** from within other threads.
7307 **
7308 ** However, the application must guarantee that the destination
7309 ** [database connection] is not passed to any other API (by any thread) after
7310 ** sqlite3_backup_init() is called and before the corresponding call to
7311 ** sqlite3_backup_finish().  SQLite does not currently check to see
7312 ** if the application incorrectly accesses the destination [database connection]
7313 ** and so no error code is reported, but the operations may malfunction
7314 ** nevertheless.  Use of the destination database connection while a
7315 ** backup is in progress might also also cause a mutex deadlock.
7316 **
7317 ** If running in [shared cache mode], the application must
7318 ** guarantee that the shared cache used by the destination database
7319 ** is not accessed while the backup is running. In practice this means
7320 ** that the application must guarantee that the disk file being
7321 ** backed up to is not accessed by any connection within the process,
7322 ** not just the specific connection that was passed to sqlite3_backup_init().
7323 **
7324 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7325 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7326 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7327 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7328 ** same time as another thread is invoking sqlite3_backup_step() it is
7329 ** possible that they return invalid values.
7330 */
7331 SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
7332   sqlite3 *pDest,                        /* Destination database handle */
7333   const char *zDestName,                 /* Destination database name */
7334   sqlite3 *pSource,                      /* Source database handle */
7335   const char *zSourceName                /* Source database name */
7336 );
7337 SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage);
7338 SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p);
7339 SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p);
7340 SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p);
7341 
7342 /*
7343 ** CAPI3REF: Unlock Notification
7344 ** METHOD: sqlite3
7345 **
7346 ** ^When running in shared-cache mode, a database operation may fail with
7347 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7348 ** individual tables within the shared-cache cannot be obtained. See
7349 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7350 ** ^This API may be used to register a callback that SQLite will invoke
7351 ** when the connection currently holding the required lock relinquishes it.
7352 ** ^This API is only available if the library was compiled with the
7353 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7354 **
7355 ** See Also: [Using the SQLite Unlock Notification Feature].
7356 **
7357 ** ^Shared-cache locks are released when a database connection concludes
7358 ** its current transaction, either by committing it or rolling it back.
7359 **
7360 ** ^When a connection (known as the blocked connection) fails to obtain a
7361 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7362 ** identity of the database connection (the blocking connection) that
7363 ** has locked the required resource is stored internally. ^After an
7364 ** application receives an SQLITE_LOCKED error, it may call the
7365 ** sqlite3_unlock_notify() method with the blocked connection handle as
7366 ** the first argument to register for a callback that will be invoked
7367 ** when the blocking connections current transaction is concluded. ^The
7368 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7369 ** call that concludes the blocking connections transaction.
7370 **
7371 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7372 ** there is a chance that the blocking connection will have already
7373 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7374 ** If this happens, then the specified callback is invoked immediately,
7375 ** from within the call to sqlite3_unlock_notify().)^
7376 **
7377 ** ^If the blocked connection is attempting to obtain a write-lock on a
7378 ** shared-cache table, and more than one other connection currently holds
7379 ** a read-lock on the same table, then SQLite arbitrarily selects one of
7380 ** the other connections to use as the blocking connection.
7381 **
7382 ** ^(There may be at most one unlock-notify callback registered by a
7383 ** blocked connection. If sqlite3_unlock_notify() is called when the
7384 ** blocked connection already has a registered unlock-notify callback,
7385 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7386 ** called with a NULL pointer as its second argument, then any existing
7387 ** unlock-notify callback is canceled. ^The blocked connections
7388 ** unlock-notify callback may also be canceled by closing the blocked
7389 ** connection using [sqlite3_close()].
7390 **
7391 ** The unlock-notify callback is not reentrant. If an application invokes
7392 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7393 ** crash or deadlock may be the result.
7394 **
7395 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7396 ** returns SQLITE_OK.
7397 **
7398 ** <b>Callback Invocation Details</b>
7399 **
7400 ** When an unlock-notify callback is registered, the application provides a
7401 ** single void* pointer that is passed to the callback when it is invoked.
7402 ** However, the signature of the callback function allows SQLite to pass
7403 ** it an array of void* context pointers. The first argument passed to
7404 ** an unlock-notify callback is a pointer to an array of void* pointers,
7405 ** and the second is the number of entries in the array.
7406 **
7407 ** When a blocking connections transaction is concluded, there may be
7408 ** more than one blocked connection that has registered for an unlock-notify
7409 ** callback. ^If two or more such blocked connections have specified the
7410 ** same callback function, then instead of invoking the callback function
7411 ** multiple times, it is invoked once with the set of void* context pointers
7412 ** specified by the blocked connections bundled together into an array.
7413 ** This gives the application an opportunity to prioritize any actions
7414 ** related to the set of unblocked database connections.
7415 **
7416 ** <b>Deadlock Detection</b>
7417 **
7418 ** Assuming that after registering for an unlock-notify callback a
7419 ** database waits for the callback to be issued before taking any further
7420 ** action (a reasonable assumption), then using this API may cause the
7421 ** application to deadlock. For example, if connection X is waiting for
7422 ** connection Y's transaction to be concluded, and similarly connection
7423 ** Y is waiting on connection X's transaction, then neither connection
7424 ** will proceed and the system may remain deadlocked indefinitely.
7425 **
7426 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7427 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7428 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7429 ** unlock-notify callback is registered. The system is said to be in
7430 ** a deadlocked state if connection A has registered for an unlock-notify
7431 ** callback on the conclusion of connection B's transaction, and connection
7432 ** B has itself registered for an unlock-notify callback when connection
7433 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7434 ** the system is also considered to be deadlocked if connection B has
7435 ** registered for an unlock-notify callback on the conclusion of connection
7436 ** C's transaction, where connection C is waiting on connection A. ^Any
7437 ** number of levels of indirection are allowed.
7438 **
7439 ** <b>The "DROP TABLE" Exception</b>
7440 **
7441 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7442 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7443 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7444 ** SQLite checks if there are any currently executing SELECT statements
7445 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7446 ** returned. In this case there is no "blocking connection", so invoking
7447 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7448 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7449 ** or "DROP INDEX" query, an infinite loop might be the result.
7450 **
7451 ** One way around this problem is to check the extended error code returned
7452 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7453 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7454 ** the special "DROP TABLE/INDEX" case, the extended error code is just
7455 ** SQLITE_LOCKED.)^
7456 */
7457 SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
7458   sqlite3 *pBlocked,                          /* Waiting connection */
7459   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7460   void *pNotifyArg                            /* Argument to pass to xNotify */
7461 );
7462 
7463 
7464 /*
7465 ** CAPI3REF: String Comparison
7466 **
7467 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7468 ** and extensions to compare the contents of two buffers containing UTF-8
7469 ** strings in a case-independent fashion, using the same definition of "case
7470 ** independence" that SQLite uses internally when comparing identifiers.
7471 */
7472 SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *, const char *);
7473 SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *, const char *, int);
7474 
7475 /*
7476 ** CAPI3REF: String Globbing
7477 *
7478 ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
7479 ** the glob pattern P, and it returns non-zero if string X does not match
7480 ** the glob pattern P.  ^The definition of glob pattern matching used in
7481 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7482 ** SQL dialect used by SQLite.  ^The sqlite3_strglob(P,X) function is case
7483 ** sensitive.
7484 **
7485 ** Note that this routine returns zero on a match and non-zero if the strings
7486 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7487 */
7488 SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlob, const char *zStr);
7489 
7490 /*
7491 ** CAPI3REF: Error Logging Interface
7492 **
7493 ** ^The [sqlite3_log()] interface writes a message into the [error log]
7494 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7495 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7496 ** used with [sqlite3_snprintf()] to generate the final output string.
7497 **
7498 ** The sqlite3_log() interface is intended for use by extensions such as
7499 ** virtual tables, collating functions, and SQL functions.  While there is
7500 ** nothing to prevent an application from calling sqlite3_log(), doing so
7501 ** is considered bad form.
7502 **
7503 ** The zFormat string must not be NULL.
7504 **
7505 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7506 ** will not use dynamically allocated memory.  The log message is stored in
7507 ** a fixed-length buffer on the stack.  If the log message is longer than
7508 ** a few hundred characters, it will be truncated to the length of the
7509 ** buffer.
7510 */
7511 SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...);
7512 
7513 /*
7514 ** CAPI3REF: Write-Ahead Log Commit Hook
7515 ** METHOD: sqlite3
7516 **
7517 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7518 ** is invoked each time data is committed to a database in wal mode.
7519 **
7520 ** ^(The callback is invoked by SQLite after the commit has taken place and
7521 ** the associated write-lock on the database released)^, so the implementation
7522 ** may read, write or [checkpoint] the database as required.
7523 **
7524 ** ^The first parameter passed to the callback function when it is invoked
7525 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7526 ** registering the callback. ^The second is a copy of the database handle.
7527 ** ^The third parameter is the name of the database that was written to -
7528 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7529 ** is the number of pages currently in the write-ahead log file,
7530 ** including those that were just committed.
7531 **
7532 ** The callback function should normally return [SQLITE_OK].  ^If an error
7533 ** code is returned, that error will propagate back up through the
7534 ** SQLite code base to cause the statement that provoked the callback
7535 ** to report an error, though the commit will have still occurred. If the
7536 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7537 ** that does not correspond to any valid SQLite error code, the results
7538 ** are undefined.
7539 **
7540 ** A single database handle may have at most a single write-ahead log callback
7541 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7542 ** previously registered write-ahead log callback. ^Note that the
7543 ** [sqlite3_wal_autocheckpoint()] interface and the
7544 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7545 ** those overwrite any prior [sqlite3_wal_hook()] settings.
7546 */
7547 SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
7548   sqlite3*,
7549   int(*)(void *,sqlite3*,const char*,int),
7550   void*
7551 );
7552 
7553 /*
7554 ** CAPI3REF: Configure an auto-checkpoint
7555 ** METHOD: sqlite3
7556 **
7557 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7558 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7559 ** to automatically [checkpoint]
7560 ** after committing a transaction if there are N or
7561 ** more frames in the [write-ahead log] file.  ^Passing zero or
7562 ** a negative value as the nFrame parameter disables automatic
7563 ** checkpoints entirely.
7564 **
7565 ** ^The callback registered by this function replaces any existing callback
7566 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7567 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7568 ** configured by this function.
7569 **
7570 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7571 ** from SQL.
7572 **
7573 ** ^Checkpoints initiated by this mechanism are
7574 ** [sqlite3_wal_checkpoint_v2|PASSIVE].
7575 **
7576 ** ^Every new [database connection] defaults to having the auto-checkpoint
7577 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7578 ** pages.  The use of this interface
7579 ** is only necessary if the default setting is found to be suboptimal
7580 ** for a particular application.
7581 */
7582 SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7583 
7584 /*
7585 ** CAPI3REF: Checkpoint a database
7586 ** METHOD: sqlite3
7587 **
7588 ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
7589 ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
7590 **
7591 ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
7592 ** [write-ahead log] for database X on [database connection] D to be
7593 ** transferred into the database file and for the write-ahead log to
7594 ** be reset.  See the [checkpointing] documentation for addition
7595 ** information.
7596 **
7597 ** This interface used to be the only way to cause a checkpoint to
7598 ** occur.  But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
7599 ** interface was added.  This interface is retained for backwards
7600 ** compatibility and as a convenience for applications that need to manually
7601 ** start a callback but which do not need the full power (and corresponding
7602 ** complication) of [sqlite3_wal_checkpoint_v2()].
7603 */
7604 SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7605 
7606 /*
7607 ** CAPI3REF: Checkpoint a database
7608 ** METHOD: sqlite3
7609 **
7610 ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
7611 ** operation on database X of [database connection] D in mode M.  Status
7612 ** information is written back into integers pointed to by L and C.)^
7613 ** ^(The M parameter must be a valid [checkpoint mode]:)^
7614 **
7615 ** <dl>
7616 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7617 **   ^Checkpoint as many frames as possible without waiting for any database
7618 **   readers or writers to finish, then sync the database file if all frames
7619 **   in the log were checkpointed. ^The [busy-handler callback]
7620 **   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
7621 **   ^On the other hand, passive mode might leave the checkpoint unfinished
7622 **   if there are concurrent readers or writers.
7623 **
7624 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7625 **   ^This mode blocks (it invokes the
7626 **   [sqlite3_busy_handler|busy-handler callback]) until there is no
7627 **   database writer and all readers are reading from the most recent database
7628 **   snapshot. ^It then checkpoints all frames in the log file and syncs the
7629 **   database file. ^This mode blocks new database writers while it is pending,
7630 **   but new database readers are allowed to continue unimpeded.
7631 **
7632 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7633 **   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
7634 **   that after checkpointing the log file it blocks (calls the
7635 **   [busy-handler callback])
7636 **   until all readers are reading from the database file only. ^This ensures
7637 **   that the next writer will restart the log file from the beginning.
7638 **   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
7639 **   database writer attempts while it is pending, but does not impede readers.
7640 **
7641 ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
7642 **   ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
7643 **   addition that it also truncates the log file to zero bytes just prior
7644 **   to a successful return.
7645 ** </dl>
7646 **
7647 ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
7648 ** the log file or to -1 if the checkpoint could not run because
7649 ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
7650 ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
7651 ** log file (including any that were already checkpointed before the function
7652 ** was called) or to -1 if the checkpoint could not run due to an error or
7653 ** because the database is not in WAL mode. ^Note that upon successful
7654 ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
7655 ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
7656 **
7657 ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
7658 ** any other process is running a checkpoint operation at the same time, the
7659 ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
7660 ** busy-handler configured, it will not be invoked in this case.
7661 **
7662 ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
7663 ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
7664 ** obtained immediately, and a busy-handler is configured, it is invoked and
7665 ** the writer lock retried until either the busy-handler returns 0 or the lock
7666 ** is successfully obtained. ^The busy-handler is also invoked while waiting for
7667 ** database readers as described above. ^If the busy-handler returns 0 before
7668 ** the writer lock is obtained or while waiting for database readers, the
7669 ** checkpoint operation proceeds from that point in the same way as
7670 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7671 ** without blocking any further. ^SQLITE_BUSY is returned in this case.
7672 **
7673 ** ^If parameter zDb is NULL or points to a zero length string, then the
7674 ** specified operation is attempted on all WAL databases [attached] to
7675 ** [database connection] db.  In this case the
7676 ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
7677 ** an SQLITE_BUSY error is encountered when processing one or more of the
7678 ** attached WAL databases, the operation is still attempted on any remaining
7679 ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
7680 ** error occurs while processing an attached database, processing is abandoned
7681 ** and the error code is returned to the caller immediately. ^If no error
7682 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7683 ** databases, SQLITE_OK is returned.
7684 **
7685 ** ^If database zDb is the name of an attached database that is not in WAL
7686 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
7687 ** zDb is not NULL (or a zero length string) and is not the name of any
7688 ** attached database, SQLITE_ERROR is returned to the caller.
7689 **
7690 ** ^Unless it returns SQLITE_MISUSE,
7691 ** the sqlite3_wal_checkpoint_v2() interface
7692 ** sets the error information that is queried by
7693 ** [sqlite3_errcode()] and [sqlite3_errmsg()].
7694 **
7695 ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
7696 ** from SQL.
7697 */
7698 SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
7699   sqlite3 *db,                    /* Database handle */
7700   const char *zDb,                /* Name of attached database (or NULL) */
7701   int eMode,                      /* SQLITE_CHECKPOINT_* value */
7702   int *pnLog,                     /* OUT: Size of WAL log in frames */
7703   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7704 );
7705 
7706 /*
7707 ** CAPI3REF: Checkpoint Mode Values
7708 ** KEYWORDS: {checkpoint mode}
7709 **
7710 ** These constants define all valid values for the "checkpoint mode" passed
7711 ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
7712 ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
7713 ** meaning of each of these checkpoint modes.
7714 */
7715 #define SQLITE_CHECKPOINT_PASSIVE  0  /* Do as much as possible w/o blocking */
7716 #define SQLITE_CHECKPOINT_FULL     1  /* Wait for writers, then checkpoint */
7717 #define SQLITE_CHECKPOINT_RESTART  2  /* Like FULL but wait for for readers */
7718 #define SQLITE_CHECKPOINT_TRUNCATE 3  /* Like RESTART but also truncate WAL */
7719 
7720 /*
7721 ** CAPI3REF: Virtual Table Interface Configuration
7722 **
7723 ** This function may be called by either the [xConnect] or [xCreate] method
7724 ** of a [virtual table] implementation to configure
7725 ** various facets of the virtual table interface.
7726 **
7727 ** If this interface is invoked outside the context of an xConnect or
7728 ** xCreate virtual table method then the behavior is undefined.
7729 **
7730 ** At present, there is only one option that may be configured using
7731 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7732 ** may be added in the future.
7733 */
7734 SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3*, int op, ...);
7735 
7736 /*
7737 ** CAPI3REF: Virtual Table Configuration Options
7738 **
7739 ** These macros define the various options to the
7740 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7741 ** can use to customize and optimize their behavior.
7742 **
7743 ** <dl>
7744 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7745 ** <dd>Calls of the form
7746 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7747 ** where X is an integer.  If X is zero, then the [virtual table] whose
7748 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7749 ** support constraints.  In this configuration (which is the default) if
7750 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7751 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7752 ** specified as part of the users SQL statement, regardless of the actual
7753 ** ON CONFLICT mode specified.
7754 **
7755 ** If X is non-zero, then the virtual table implementation guarantees
7756 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7757 ** any modifications to internal or persistent data structures have been made.
7758 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
7759 ** is able to roll back a statement or database transaction, and abandon
7760 ** or continue processing the current SQL statement as appropriate.
7761 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7762 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7763 ** had been ABORT.
7764 **
7765 ** Virtual table implementations that are required to handle OR REPLACE
7766 ** must do so within the [xUpdate] method. If a call to the
7767 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
7768 ** CONFLICT policy is REPLACE, the virtual table implementation should
7769 ** silently replace the appropriate rows within the xUpdate callback and
7770 ** return SQLITE_OK. Or, if this is not possible, it may return
7771 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
7772 ** constraint handling.
7773 ** </dl>
7774 */
7775 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7776 
7777 /*
7778 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7779 **
7780 ** This function may only be called from within a call to the [xUpdate] method
7781 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7782 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7783 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7784 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7785 ** [virtual table].
7786 */
7787 SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *);
7788 
7789 /*
7790 ** CAPI3REF: Conflict resolution modes
7791 ** KEYWORDS: {conflict resolution mode}
7792 **
7793 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7794 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7795 ** is for the SQL statement being evaluated.
7796 **
7797 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7798 ** return value from the [sqlite3_set_authorizer()] callback and that
7799 ** [SQLITE_ABORT] is also a [result code].
7800 */
7801 #define SQLITE_ROLLBACK 1
7802 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7803 #define SQLITE_FAIL     3
7804 /* #define SQLITE_ABORT 4  // Also an error code */
7805 #define SQLITE_REPLACE  5
7806 
7807 /*
7808 ** CAPI3REF: Prepared Statement Scan Status Opcodes
7809 ** KEYWORDS: {scanstatus options}
7810 **
7811 ** The following constants can be used for the T parameter to the
7812 ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface.  Each constant designates a
7813 ** different metric for sqlite3_stmt_scanstatus() to return.
7814 **
7815 ** When the value returned to V is a string, space to hold that string is
7816 ** managed by the prepared statement S and will be automatically freed when
7817 ** S is finalized.
7818 **
7819 ** <dl>
7820 ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
7821 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
7822 ** set to the total number of times that the X-th loop has run.</dd>
7823 **
7824 ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
7825 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
7826 ** to the total number of rows examined by all iterations of the X-th loop.</dd>
7827 **
7828 ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
7829 ** <dd>^The "double" variable pointed to by the T parameter will be set to the
7830 ** query planner's estimate for the average number of rows output from each
7831 ** iteration of the X-th loop.  If the query planner's estimates was accurate,
7832 ** then this value will approximate the quotient NVISIT/NLOOP and the
7833 ** product of this value for all prior loops with the same SELECTID will
7834 ** be the NLOOP value for the current loop.
7835 **
7836 ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
7837 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
7838 ** to a zero-terminated UTF-8 string containing the name of the index or table
7839 ** used for the X-th loop.
7840 **
7841 ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
7842 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
7843 ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
7844 ** description for the X-th loop.
7845 **
7846 ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
7847 ** <dd>^The "int" variable pointed to by the T parameter will be set to the
7848 ** "select-id" for the X-th loop.  The select-id identifies which query or
7849 ** subquery the loop is part of.  The main query has a select-id of zero.
7850 ** The select-id is the same value as is output in the first column
7851 ** of an [EXPLAIN QUERY PLAN] query.
7852 ** </dl>
7853 */
7854 #define SQLITE_SCANSTAT_NLOOP    0
7855 #define SQLITE_SCANSTAT_NVISIT   1
7856 #define SQLITE_SCANSTAT_EST      2
7857 #define SQLITE_SCANSTAT_NAME     3
7858 #define SQLITE_SCANSTAT_EXPLAIN  4
7859 #define SQLITE_SCANSTAT_SELECTID 5
7860 
7861 /*
7862 ** CAPI3REF: Prepared Statement Scan Status
7863 ** METHOD: sqlite3_stmt
7864 **
7865 ** This interface returns information about the predicted and measured
7866 ** performance for pStmt.  Advanced applications can use this
7867 ** interface to compare the predicted and the measured performance and
7868 ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
7869 **
7870 ** Since this interface is expected to be rarely used, it is only
7871 ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
7872 ** compile-time option.
7873 **
7874 ** The "iScanStatusOp" parameter determines which status information to return.
7875 ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
7876 ** of this interface is undefined.
7877 ** ^The requested measurement is written into a variable pointed to by
7878 ** the "pOut" parameter.
7879 ** Parameter "idx" identifies the specific loop to retrieve statistics for.
7880 ** Loops are numbered starting from zero. ^If idx is out of range - less than
7881 ** zero or greater than or equal to the total number of loops used to implement
7882 ** the statement - a non-zero value is returned and the variable that pOut
7883 ** points to is unchanged.
7884 **
7885 ** ^Statistics might not be available for all loops in all statements. ^In cases
7886 ** where there exist loops with no available statistics, this function behaves
7887 ** as if the loop did not exist - it returns non-zero and leave the variable
7888 ** that pOut points to unchanged.
7889 **
7890 ** See also: [sqlite3_stmt_scanstatus_reset()]
7891 */
7892 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_stmt_scanstatus(
7893   sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */
7894   int idx,                  /* Index of loop to report on */
7895   int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */
7896   void *pOut                /* Result written here */
7897 );
7898 
7899 /*
7900 ** CAPI3REF: Zero Scan-Status Counters
7901 ** METHOD: sqlite3_stmt
7902 **
7903 ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
7904 **
7905 ** This API is only available if the library is built with pre-processor
7906 ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
7907 */
7908 SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
7909 
7910 
7911 /*
7912 ** Undo the hack that converts floating point types to integer for
7913 ** builds on processors without floating point support.
7914 */
7915 #ifdef SQLITE_OMIT_FLOATING_POINT
7916 # undef double
7917 #endif
7918 
7919 #if 0
7920 }  /* End of the 'extern "C"' block */
7921 #endif
7922 #endif /* _SQLITE3_H_ */
7923 
7924 /*
7925 ** 2010 August 30
7926 **
7927 ** The author disclaims copyright to this source code.  In place of
7928 ** a legal notice, here is a blessing:
7929 **
7930 **    May you do good and not evil.
7931 **    May you find forgiveness for yourself and forgive others.
7932 **    May you share freely, never taking more than you give.
7933 **
7934 *************************************************************************
7935 */
7936 
7937 #ifndef _SQLITE3RTREE_H_
7938 #define _SQLITE3RTREE_H_
7939 
7940 
7941 #if 0
7942 extern "C" {
7943 #endif
7944 
7945 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7946 typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
7947 
7948 /* The double-precision datatype used by RTree depends on the
7949 ** SQLITE_RTREE_INT_ONLY compile-time option.
7950 */
7951 #ifdef SQLITE_RTREE_INT_ONLY
7952   typedef sqlite3_int64 sqlite3_rtree_dbl;
7953 #else
7954   typedef double sqlite3_rtree_dbl;
7955 #endif
7956 
7957 /*
7958 ** Register a geometry callback named zGeom that can be used as part of an
7959 ** R-Tree geometry query as follows:
7960 **
7961 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7962 */
7963 SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
7964   sqlite3 *db,
7965   const char *zGeom,
7966   int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
7967   void *pContext
7968 );
7969 
7970 
7971 /*
7972 ** A pointer to a structure of the following type is passed as the first
7973 ** argument to callbacks registered using rtree_geometry_callback().
7974 */
7975 struct sqlite3_rtree_geometry {
7976   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7977   int nParam;                     /* Size of array aParam[] */
7978   sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */
7979   void *pUser;                    /* Callback implementation user data */
7980   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7981 };
7982 
7983 /*
7984 ** Register a 2nd-generation geometry callback named zScore that can be
7985 ** used as part of an R-Tree geometry query as follows:
7986 **
7987 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
7988 */
7989 SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
7990   sqlite3 *db,
7991   const char *zQueryFunc,
7992   int (*xQueryFunc)(sqlite3_rtree_query_info*),
7993   void *pContext,
7994   void (*xDestructor)(void*)
7995 );
7996 
7997 
7998 /*
7999 ** A pointer to a structure of the following type is passed as the
8000 ** argument to scored geometry callback registered using
8001 ** sqlite3_rtree_query_callback().
8002 **
8003 ** Note that the first 5 fields of this structure are identical to
8004 ** sqlite3_rtree_geometry.  This structure is a subclass of
8005 ** sqlite3_rtree_geometry.
8006 */
8007 struct sqlite3_rtree_query_info {
8008   void *pContext;                   /* pContext from when function registered */
8009   int nParam;                       /* Number of function parameters */
8010   sqlite3_rtree_dbl *aParam;        /* value of function parameters */
8011   void *pUser;                      /* callback can use this, if desired */
8012   void (*xDelUser)(void*);          /* function to free pUser */
8013   sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */
8014   unsigned int *anQueue;            /* Number of pending entries in the queue */
8015   int nCoord;                       /* Number of coordinates */
8016   int iLevel;                       /* Level of current node or entry */
8017   int mxLevel;                      /* The largest iLevel value in the tree */
8018   sqlite3_int64 iRowid;             /* Rowid for current entry */
8019   sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
8020   int eParentWithin;                /* Visibility of parent node */
8021   int eWithin;                      /* OUT: Visiblity */
8022   sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
8023 };
8024 
8025 /*
8026 ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
8027 */
8028 #define NOT_WITHIN       0   /* Object completely outside of query region */
8029 #define PARTLY_WITHIN    1   /* Object partially overlaps query region */
8030 #define FULLY_WITHIN     2   /* Object fully contained within query region */
8031 
8032 
8033 #if 0
8034 }  /* end of the 'extern "C"' block */
8035 #endif
8036 
8037 #endif  /* ifndef _SQLITE3RTREE_H_ */
8038 
8039 
8040 /************** End of sqlite3.h *********************************************/
8041 /************** Continuing where we left off in sqliteInt.h ******************/
8042 
8043 /*
8044 ** Include the configuration header output by 'configure' if we're using the
8045 ** autoconf-based build
8046 */
8047 #ifdef _HAVE_SQLITE_CONFIG_H
8048 #include "config.h"
8049 #endif
8050 
8051 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
8052 /************** Begin file sqliteLimit.h *************************************/
8053 /*
8054 ** 2007 May 7
8055 **
8056 ** The author disclaims copyright to this source code.  In place of
8057 ** a legal notice, here is a blessing:
8058 **
8059 **    May you do good and not evil.
8060 **    May you find forgiveness for yourself and forgive others.
8061 **    May you share freely, never taking more than you give.
8062 **
8063 *************************************************************************
8064 **
8065 ** This file defines various limits of what SQLite can process.
8066 */
8067 
8068 /*
8069 ** The maximum length of a TEXT or BLOB in bytes.   This also
8070 ** limits the size of a row in a table or index.
8071 **
8072 ** The hard limit is the ability of a 32-bit signed integer
8073 ** to count the size: 2^31-1 or 2147483647.
8074 */
8075 #ifndef SQLITE_MAX_LENGTH
8076 # define SQLITE_MAX_LENGTH 1000000000
8077 #endif
8078 
8079 /*
8080 ** This is the maximum number of
8081 **
8082 **    * Columns in a table
8083 **    * Columns in an index
8084 **    * Columns in a view
8085 **    * Terms in the SET clause of an UPDATE statement
8086 **    * Terms in the result set of a SELECT statement
8087 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
8088 **    * Terms in the VALUES clause of an INSERT statement
8089 **
8090 ** The hard upper limit here is 32676.  Most database people will
8091 ** tell you that in a well-normalized database, you usually should
8092 ** not have more than a dozen or so columns in any table.  And if
8093 ** that is the case, there is no point in having more than a few
8094 ** dozen values in any of the other situations described above.
8095 */
8096 #ifndef SQLITE_MAX_COLUMN
8097 # define SQLITE_MAX_COLUMN 2000
8098 #endif
8099 
8100 /*
8101 ** The maximum length of a single SQL statement in bytes.
8102 **
8103 ** It used to be the case that setting this value to zero would
8104 ** turn the limit off.  That is no longer true.  It is not possible
8105 ** to turn this limit off.
8106 */
8107 #ifndef SQLITE_MAX_SQL_LENGTH
8108 # define SQLITE_MAX_SQL_LENGTH 1000000000
8109 #endif
8110 
8111 /*
8112 ** The maximum depth of an expression tree. This is limited to
8113 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
8114 ** want to place more severe limits on the complexity of an
8115 ** expression.
8116 **
8117 ** A value of 0 used to mean that the limit was not enforced.
8118 ** But that is no longer true.  The limit is now strictly enforced
8119 ** at all times.
8120 */
8121 #ifndef SQLITE_MAX_EXPR_DEPTH
8122 # define SQLITE_MAX_EXPR_DEPTH 1000
8123 #endif
8124 
8125 /*
8126 ** The maximum number of terms in a compound SELECT statement.
8127 ** The code generator for compound SELECT statements does one
8128 ** level of recursion for each term.  A stack overflow can result
8129 ** if the number of terms is too large.  In practice, most SQL
8130 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
8131 ** any limit on the number of terms in a compount SELECT.
8132 */
8133 #ifndef SQLITE_MAX_COMPOUND_SELECT
8134 # define SQLITE_MAX_COMPOUND_SELECT 500
8135 #endif
8136 
8137 /*
8138 ** The maximum number of opcodes in a VDBE program.
8139 ** Not currently enforced.
8140 */
8141 #ifndef SQLITE_MAX_VDBE_OP
8142 # define SQLITE_MAX_VDBE_OP 25000
8143 #endif
8144 
8145 /*
8146 ** The maximum number of arguments to an SQL function.
8147 */
8148 #ifndef SQLITE_MAX_FUNCTION_ARG
8149 # define SQLITE_MAX_FUNCTION_ARG 127
8150 #endif
8151 
8152 /*
8153 ** The suggested maximum number of in-memory pages to use for
8154 ** the main database table and for temporary tables.
8155 **
8156 ** IMPLEMENTATION-OF: R-31093-59126 The default suggested cache size
8157 ** is 2000 pages.
8158 ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
8159 ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
8160 */
8161 #ifndef SQLITE_DEFAULT_CACHE_SIZE
8162 # define SQLITE_DEFAULT_CACHE_SIZE  2000
8163 #endif
8164 
8165 /*
8166 ** The default number of frames to accumulate in the log file before
8167 ** checkpointing the database in WAL mode.
8168 */
8169 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
8170 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
8171 #endif
8172 
8173 /*
8174 ** The maximum number of attached databases.  This must be between 0
8175 ** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
8176 ** is used internally to track attached databases.
8177 */
8178 #ifndef SQLITE_MAX_ATTACHED
8179 # define SQLITE_MAX_ATTACHED 10
8180 #endif
8181 
8182 
8183 /*
8184 ** The maximum value of a ?nnn wildcard that the parser will accept.
8185 */
8186 #ifndef SQLITE_MAX_VARIABLE_NUMBER
8187 # define SQLITE_MAX_VARIABLE_NUMBER 999
8188 #endif
8189 
8190 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
8191 ** imposed by the use of 16-bit offsets within each page.
8192 **
8193 ** Earlier versions of SQLite allowed the user to change this value at
8194 ** compile time. This is no longer permitted, on the grounds that it creates
8195 ** a library that is technically incompatible with an SQLite library
8196 ** compiled with a different limit. If a process operating on a database
8197 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
8198 ** compiled with the default page-size limit will not be able to rollback
8199 ** the aborted transaction. This could lead to database corruption.
8200 */
8201 #ifdef SQLITE_MAX_PAGE_SIZE
8202 # undef SQLITE_MAX_PAGE_SIZE
8203 #endif
8204 #define SQLITE_MAX_PAGE_SIZE 65536
8205 
8206 
8207 /*
8208 ** The default size of a database page.
8209 */
8210 #ifndef SQLITE_DEFAULT_PAGE_SIZE
8211 # define SQLITE_DEFAULT_PAGE_SIZE 1024
8212 #endif
8213 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
8214 # undef SQLITE_DEFAULT_PAGE_SIZE
8215 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
8216 #endif
8217 
8218 /*
8219 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
8220 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
8221 ** device characteristics (sector-size and atomic write() support),
8222 ** SQLite may choose a larger value. This constant is the maximum value
8223 ** SQLite will choose on its own.
8224 */
8225 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
8226 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
8227 #endif
8228 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
8229 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
8230 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
8231 #endif
8232 
8233 
8234 /*
8235 ** Maximum number of pages in one database file.
8236 **
8237 ** This is really just the default value for the max_page_count pragma.
8238 ** This value can be lowered (or raised) at run-time using that the
8239 ** max_page_count macro.
8240 */
8241 #ifndef SQLITE_MAX_PAGE_COUNT
8242 # define SQLITE_MAX_PAGE_COUNT 1073741823
8243 #endif
8244 
8245 /*
8246 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
8247 ** operator.
8248 */
8249 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
8250 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
8251 #endif
8252 
8253 /*
8254 ** Maximum depth of recursion for triggers.
8255 **
8256 ** A value of 1 means that a trigger program will not be able to itself
8257 ** fire any triggers. A value of 0 means that no trigger programs at all
8258 ** may be executed.
8259 */
8260 #ifndef SQLITE_MAX_TRIGGER_DEPTH
8261 # define SQLITE_MAX_TRIGGER_DEPTH 1000
8262 #endif
8263 
8264 /************** End of sqliteLimit.h *****************************************/
8265 /************** Continuing where we left off in sqliteInt.h ******************/
8266 
8267 /* Disable nuisance warnings on Borland compilers */
8268 #if defined(__BORLANDC__)
8269 #pragma warn -rch /* unreachable code */
8270 #pragma warn -ccc /* Condition is always true or false */
8271 #pragma warn -aus /* Assigned value is never used */
8272 #pragma warn -csu /* Comparing signed and unsigned */
8273 #pragma warn -spa /* Suspicious pointer arithmetic */
8274 #endif
8275 
8276 /*
8277 ** Include standard header files as necessary
8278 */
8279 #ifdef HAVE_STDINT_H
8280 #include <stdint.h>
8281 #endif
8282 #ifdef HAVE_INTTYPES_H
8283 #include <inttypes.h>
8284 #endif
8285 
8286 /*
8287 ** The following macros are used to cast pointers to integers and
8288 ** integers to pointers.  The way you do this varies from one compiler
8289 ** to the next, so we have developed the following set of #if statements
8290 ** to generate appropriate macros for a wide range of compilers.
8291 **
8292 ** The correct "ANSI" way to do this is to use the intptr_t type.
8293 ** Unfortunately, that typedef is not available on all compilers, or
8294 ** if it is available, it requires an #include of specific headers
8295 ** that vary from one machine to the next.
8296 **
8297 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
8298 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
8299 ** So we have to define the macros in different ways depending on the
8300 ** compiler.
8301 */
8302 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
8303 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
8304 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
8305 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
8306 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
8307 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
8308 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
8309 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
8310 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
8311 #else                          /* Generates a warning - but it always works */
8312 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
8313 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
8314 #endif
8315 
8316 /*
8317 ** A macro to hint to the compiler that a function should not be
8318 ** inlined.
8319 */
8320 #if defined(__GNUC__)
8321 #  define SQLITE_NOINLINE  __attribute__((noinline))
8322 #elif defined(_MSC_VER) && _MSC_VER>=1310
8323 #  define SQLITE_NOINLINE  __declspec(noinline)
8324 #else
8325 #  define SQLITE_NOINLINE
8326 #endif
8327 
8328 /*
8329 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
8330 ** 0 means mutexes are permanently disable and the library is never
8331 ** threadsafe.  1 means the library is serialized which is the highest
8332 ** level of threadsafety.  2 means the library is multithreaded - multiple
8333 ** threads can use SQLite as long as no two threads try to use the same
8334 ** database connection at the same time.
8335 **
8336 ** Older versions of SQLite used an optional THREADSAFE macro.
8337 ** We support that for legacy.
8338 */
8339 #if !defined(SQLITE_THREADSAFE)
8340 # if defined(THREADSAFE)
8341 #   define SQLITE_THREADSAFE THREADSAFE
8342 # else
8343 #   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
8344 # endif
8345 #endif
8346 
8347 /*
8348 ** Powersafe overwrite is on by default.  But can be turned off using
8349 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
8350 */
8351 #ifndef SQLITE_POWERSAFE_OVERWRITE
8352 # define SQLITE_POWERSAFE_OVERWRITE 1
8353 #endif
8354 
8355 /*
8356 ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
8357 ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
8358 ** which case memory allocation statistics are disabled by default.
8359 */
8360 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
8361 # define SQLITE_DEFAULT_MEMSTATUS 1
8362 #endif
8363 
8364 /*
8365 ** Exactly one of the following macros must be defined in order to
8366 ** specify which memory allocation subsystem to use.
8367 **
8368 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
8369 **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
8370 **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
8371 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
8372 **
8373 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
8374 ** assert() macro is enabled, each call into the Win32 native heap subsystem
8375 ** will cause HeapValidate to be called.  If heap validation should fail, an
8376 ** assertion will be triggered.
8377 **
8378 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
8379 ** the default.
8380 */
8381 #if defined(SQLITE_SYSTEM_MALLOC) \
8382   + defined(SQLITE_WIN32_MALLOC) \
8383   + defined(SQLITE_ZERO_MALLOC) \
8384   + defined(SQLITE_MEMDEBUG)>1
8385 # error "Two or more of the following compile-time configuration options\
8386  are defined but at most one is allowed:\
8387  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
8388  SQLITE_ZERO_MALLOC"
8389 #endif
8390 #if defined(SQLITE_SYSTEM_MALLOC) \
8391   + defined(SQLITE_WIN32_MALLOC) \
8392   + defined(SQLITE_ZERO_MALLOC) \
8393   + defined(SQLITE_MEMDEBUG)==0
8394 # define SQLITE_SYSTEM_MALLOC 1
8395 #endif
8396 
8397 /*
8398 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
8399 ** sizes of memory allocations below this value where possible.
8400 */
8401 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
8402 # define SQLITE_MALLOC_SOFT_LIMIT 1024
8403 #endif
8404 
8405 /*
8406 ** We need to define _XOPEN_SOURCE as follows in order to enable
8407 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
8408 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
8409 ** it.
8410 */
8411 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
8412 #  define _XOPEN_SOURCE 600
8413 #endif
8414 
8415 /*
8416 ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
8417 ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
8418 ** make it true by defining or undefining NDEBUG.
8419 **
8420 ** Setting NDEBUG makes the code smaller and faster by disabling the
8421 ** assert() statements in the code.  So we want the default action
8422 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
8423 ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
8424 ** feature.
8425 */
8426 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
8427 # define NDEBUG 1
8428 #endif
8429 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
8430 # undef NDEBUG
8431 #endif
8432 
8433 /*
8434 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
8435 */
8436 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
8437 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
8438 #endif
8439 
8440 /*
8441 ** The testcase() macro is used to aid in coverage testing.  When
8442 ** doing coverage testing, the condition inside the argument to
8443 ** testcase() must be evaluated both true and false in order to
8444 ** get full branch coverage.  The testcase() macro is inserted
8445 ** to help ensure adequate test coverage in places where simple
8446 ** condition/decision coverage is inadequate.  For example, testcase()
8447 ** can be used to make sure boundary values are tested.  For
8448 ** bitmask tests, testcase() can be used to make sure each bit
8449 ** is significant and used at least once.  On switch statements
8450 ** where multiple cases go to the same block of code, testcase()
8451 ** can insure that all cases are evaluated.
8452 **
8453 */
8454 #ifdef SQLITE_COVERAGE_TEST
8455 SQLITE_PRIVATE   void sqlite3Coverage(int);
8456 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
8457 #else
8458 # define testcase(X)
8459 #endif
8460 
8461 /*
8462 ** The TESTONLY macro is used to enclose variable declarations or
8463 ** other bits of code that are needed to support the arguments
8464 ** within testcase() and assert() macros.
8465 */
8466 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
8467 # define TESTONLY(X)  X
8468 #else
8469 # define TESTONLY(X)
8470 #endif
8471 
8472 /*
8473 ** Sometimes we need a small amount of code such as a variable initialization
8474 ** to setup for a later assert() statement.  We do not want this code to
8475 ** appear when assert() is disabled.  The following macro is therefore
8476 ** used to contain that setup code.  The "VVA" acronym stands for
8477 ** "Verification, Validation, and Accreditation".  In other words, the
8478 ** code within VVA_ONLY() will only run during verification processes.
8479 */
8480 #ifndef NDEBUG
8481 # define VVA_ONLY(X)  X
8482 #else
8483 # define VVA_ONLY(X)
8484 #endif
8485 
8486 /*
8487 ** The ALWAYS and NEVER macros surround boolean expressions which
8488 ** are intended to always be true or false, respectively.  Such
8489 ** expressions could be omitted from the code completely.  But they
8490 ** are included in a few cases in order to enhance the resilience
8491 ** of SQLite to unexpected behavior - to make the code "self-healing"
8492 ** or "ductile" rather than being "brittle" and crashing at the first
8493 ** hint of unplanned behavior.
8494 **
8495 ** In other words, ALWAYS and NEVER are added for defensive code.
8496 **
8497 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
8498 ** be true and false so that the unreachable code they specify will
8499 ** not be counted as untested code.
8500 */
8501 #if defined(SQLITE_COVERAGE_TEST)
8502 # define ALWAYS(X)      (1)
8503 # define NEVER(X)       (0)
8504 #elif !defined(NDEBUG)
8505 # define ALWAYS(X)      ((X)?1:(assert(0),0))
8506 # define NEVER(X)       ((X)?(assert(0),1):0)
8507 #else
8508 # define ALWAYS(X)      (X)
8509 # define NEVER(X)       (X)
8510 #endif
8511 
8512 /*
8513 ** Declarations used for tracing the operating system interfaces.
8514 */
8515 #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
8516     (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
8517   extern int sqlite3OSTrace;
8518 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
8519 # define SQLITE_HAVE_OS_TRACE
8520 #else
8521 # define OSTRACE(X)
8522 # undef  SQLITE_HAVE_OS_TRACE
8523 #endif
8524 
8525 /*
8526 ** Is the sqlite3ErrName() function needed in the build?  Currently,
8527 ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
8528 ** OSTRACE is enabled), and by several "test*.c" files (which are
8529 ** compiled using SQLITE_TEST).
8530 */
8531 #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
8532     (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
8533 # define SQLITE_NEED_ERR_NAME
8534 #else
8535 # undef  SQLITE_NEED_ERR_NAME
8536 #endif
8537 
8538 /*
8539 ** Return true (non-zero) if the input is an integer that is too large
8540 ** to fit in 32-bits.  This macro is used inside of various testcase()
8541 ** macros to verify that we have tested SQLite for large-file support.
8542 */
8543 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
8544 
8545 /*
8546 ** The macro unlikely() is a hint that surrounds a boolean
8547 ** expression that is usually false.  Macro likely() surrounds
8548 ** a boolean expression that is usually true.  These hints could,
8549 ** in theory, be used by the compiler to generate better code, but
8550 ** currently they are just comments for human readers.
8551 */
8552 #define likely(X)    (X)
8553 #define unlikely(X)  (X)
8554 
8555 /************** Include hash.h in the middle of sqliteInt.h ******************/
8556 /************** Begin file hash.h ********************************************/
8557 /*
8558 ** 2001 September 22
8559 **
8560 ** The author disclaims copyright to this source code.  In place of
8561 ** a legal notice, here is a blessing:
8562 **
8563 **    May you do good and not evil.
8564 **    May you find forgiveness for yourself and forgive others.
8565 **    May you share freely, never taking more than you give.
8566 **
8567 *************************************************************************
8568 ** This is the header file for the generic hash-table implementation
8569 ** used in SQLite.
8570 */
8571 #ifndef _SQLITE_HASH_H_
8572 #define _SQLITE_HASH_H_
8573 
8574 /* Forward declarations of structures. */
8575 typedef struct Hash Hash;
8576 typedef struct HashElem HashElem;
8577 
8578 /* A complete hash table is an instance of the following structure.
8579 ** The internals of this structure are intended to be opaque -- client
8580 ** code should not attempt to access or modify the fields of this structure
8581 ** directly.  Change this structure only by using the routines below.
8582 ** However, some of the "procedures" and "functions" for modifying and
8583 ** accessing this structure are really macros, so we can't really make
8584 ** this structure opaque.
8585 **
8586 ** All elements of the hash table are on a single doubly-linked list.
8587 ** Hash.first points to the head of this list.
8588 **
8589 ** There are Hash.htsize buckets.  Each bucket points to a spot in
8590 ** the global doubly-linked list.  The contents of the bucket are the
8591 ** element pointed to plus the next _ht.count-1 elements in the list.
8592 **
8593 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
8594 ** by a linear search of the global list.  For small tables, the
8595 ** Hash.ht table is never allocated because if there are few elements
8596 ** in the table, it is faster to do a linear search than to manage
8597 ** the hash table.
8598 */
8599 struct Hash {
8600   unsigned int htsize;      /* Number of buckets in the hash table */
8601   unsigned int count;       /* Number of entries in this table */
8602   HashElem *first;          /* The first element of the array */
8603   struct _ht {              /* the hash table */
8604     int count;                 /* Number of entries with this hash */
8605     HashElem *chain;           /* Pointer to first entry with this hash */
8606   } *ht;
8607 };
8608 
8609 /* Each element in the hash table is an instance of the following
8610 ** structure.  All elements are stored on a single doubly-linked list.
8611 **
8612 ** Again, this structure is intended to be opaque, but it can't really
8613 ** be opaque because it is used by macros.
8614 */
8615 struct HashElem {
8616   HashElem *next, *prev;       /* Next and previous elements in the table */
8617   void *data;                  /* Data associated with this element */
8618   const char *pKey;            /* Key associated with this element */
8619 };
8620 
8621 /*
8622 ** Access routines.  To delete, insert a NULL pointer.
8623 */
8624 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
8625 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
8626 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
8627 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
8628 
8629 /*
8630 ** Macros for looping over all elements of a hash table.  The idiom is
8631 ** like this:
8632 **
8633 **   Hash h;
8634 **   HashElem *p;
8635 **   ...
8636 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
8637 **     SomeStructure *pData = sqliteHashData(p);
8638 **     // do something with pData
8639 **   }
8640 */
8641 #define sqliteHashFirst(H)  ((H)->first)
8642 #define sqliteHashNext(E)   ((E)->next)
8643 #define sqliteHashData(E)   ((E)->data)
8644 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
8645 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
8646 
8647 /*
8648 ** Number of entries in a hash table
8649 */
8650 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
8651 
8652 #endif /* _SQLITE_HASH_H_ */
8653 
8654 /************** End of hash.h ************************************************/
8655 /************** Continuing where we left off in sqliteInt.h ******************/
8656 /************** Include parse.h in the middle of sqliteInt.h *****************/
8657 /************** Begin file parse.h *******************************************/
8658 #define TK_SEMI                             1
8659 #define TK_EXPLAIN                          2
8660 #define TK_QUERY                            3
8661 #define TK_PLAN                             4
8662 #define TK_BEGIN                            5
8663 #define TK_TRANSACTION                      6
8664 #define TK_DEFERRED                         7
8665 #define TK_IMMEDIATE                        8
8666 #define TK_EXCLUSIVE                        9
8667 #define TK_COMMIT                          10
8668 #define TK_END                             11
8669 #define TK_ROLLBACK                        12
8670 #define TK_SAVEPOINT                       13
8671 #define TK_RELEASE                         14
8672 #define TK_TO                              15
8673 #define TK_TABLE                           16
8674 #define TK_CREATE                          17
8675 #define TK_IF                              18
8676 #define TK_NOT                             19
8677 #define TK_EXISTS                          20
8678 #define TK_TEMP                            21
8679 #define TK_LP                              22
8680 #define TK_RP                              23
8681 #define TK_AS                              24
8682 #define TK_WITHOUT                         25
8683 #define TK_COMMA                           26
8684 #define TK_ID                              27
8685 #define TK_INDEXED                         28
8686 #define TK_ABORT                           29
8687 #define TK_ACTION                          30
8688 #define TK_AFTER                           31
8689 #define TK_ANALYZE                         32
8690 #define TK_ASC                             33
8691 #define TK_ATTACH                          34
8692 #define TK_BEFORE                          35
8693 #define TK_BY                              36
8694 #define TK_CASCADE                         37
8695 #define TK_CAST                            38
8696 #define TK_COLUMNKW                        39
8697 #define TK_CONFLICT                        40
8698 #define TK_DATABASE                        41
8699 #define TK_DESC                            42
8700 #define TK_DETACH                          43
8701 #define TK_EACH                            44
8702 #define TK_FAIL                            45
8703 #define TK_FOR                             46
8704 #define TK_IGNORE                          47
8705 #define TK_INITIALLY                       48
8706 #define TK_INSTEAD                         49
8707 #define TK_LIKE_KW                         50
8708 #define TK_MATCH                           51
8709 #define TK_NO                              52
8710 #define TK_KEY                             53
8711 #define TK_OF                              54
8712 #define TK_OFFSET                          55
8713 #define TK_PRAGMA                          56
8714 #define TK_RAISE                           57
8715 #define TK_RECURSIVE                       58
8716 #define TK_REPLACE                         59
8717 #define TK_RESTRICT                        60
8718 #define TK_ROW                             61
8719 #define TK_TRIGGER                         62
8720 #define TK_VACUUM                          63
8721 #define TK_VIEW                            64
8722 #define TK_VIRTUAL                         65
8723 #define TK_WITH                            66
8724 #define TK_REINDEX                         67
8725 #define TK_RENAME                          68
8726 #define TK_CTIME_KW                        69
8727 #define TK_ANY                             70
8728 #define TK_OR                              71
8729 #define TK_AND                             72
8730 #define TK_IS                              73
8731 #define TK_BETWEEN                         74
8732 #define TK_IN                              75
8733 #define TK_ISNULL                          76
8734 #define TK_NOTNULL                         77
8735 #define TK_NE                              78
8736 #define TK_EQ                              79
8737 #define TK_GT                              80
8738 #define TK_LE                              81
8739 #define TK_LT                              82
8740 #define TK_GE                              83
8741 #define TK_ESCAPE                          84
8742 #define TK_BITAND                          85
8743 #define TK_BITOR                           86
8744 #define TK_LSHIFT                          87
8745 #define TK_RSHIFT                          88
8746 #define TK_PLUS                            89
8747 #define TK_MINUS                           90
8748 #define TK_STAR                            91
8749 #define TK_SLASH                           92
8750 #define TK_REM                             93
8751 #define TK_CONCAT                          94
8752 #define TK_COLLATE                         95
8753 #define TK_BITNOT                          96
8754 #define TK_STRING                          97
8755 #define TK_JOIN_KW                         98
8756 #define TK_CONSTRAINT                      99
8757 #define TK_DEFAULT                        100
8758 #define TK_NULL                           101
8759 #define TK_PRIMARY                        102
8760 #define TK_UNIQUE                         103
8761 #define TK_CHECK                          104
8762 #define TK_REFERENCES                     105
8763 #define TK_AUTOINCR                       106
8764 #define TK_ON                             107
8765 #define TK_INSERT                         108
8766 #define TK_DELETE                         109
8767 #define TK_UPDATE                         110
8768 #define TK_SET                            111
8769 #define TK_DEFERRABLE                     112
8770 #define TK_FOREIGN                        113
8771 #define TK_DROP                           114
8772 #define TK_UNION                          115
8773 #define TK_ALL                            116
8774 #define TK_EXCEPT                         117
8775 #define TK_INTERSECT                      118
8776 #define TK_SELECT                         119
8777 #define TK_VALUES                         120
8778 #define TK_DISTINCT                       121
8779 #define TK_DOT                            122
8780 #define TK_FROM                           123
8781 #define TK_JOIN                           124
8782 #define TK_USING                          125
8783 #define TK_ORDER                          126
8784 #define TK_GROUP                          127
8785 #define TK_HAVING                         128
8786 #define TK_LIMIT                          129
8787 #define TK_WHERE                          130
8788 #define TK_INTO                           131
8789 #define TK_INTEGER                        132
8790 #define TK_FLOAT                          133
8791 #define TK_BLOB                           134
8792 #define TK_VARIABLE                       135
8793 #define TK_CASE                           136
8794 #define TK_WHEN                           137
8795 #define TK_THEN                           138
8796 #define TK_ELSE                           139
8797 #define TK_INDEX                          140
8798 #define TK_ALTER                          141
8799 #define TK_ADD                            142
8800 #define TK_TO_TEXT                        143
8801 #define TK_TO_BLOB                        144
8802 #define TK_TO_NUMERIC                     145
8803 #define TK_TO_INT                         146
8804 #define TK_TO_REAL                        147
8805 #define TK_ISNOT                          148
8806 #define TK_END_OF_FILE                    149
8807 #define TK_ILLEGAL                        150
8808 #define TK_SPACE                          151
8809 #define TK_UNCLOSED_STRING                152
8810 #define TK_FUNCTION                       153
8811 #define TK_COLUMN                         154
8812 #define TK_AGG_FUNCTION                   155
8813 #define TK_AGG_COLUMN                     156
8814 #define TK_UMINUS                         157
8815 #define TK_UPLUS                          158
8816 #define TK_REGISTER                       159
8817 
8818 /************** End of parse.h ***********************************************/
8819 /************** Continuing where we left off in sqliteInt.h ******************/
8820 #include <stdio.h>
8821 #include <stdlib.h>
8822 #include <string.h>
8823 #include <assert.h>
8824 #include <stddef.h>
8825 
8826 /*
8827 ** If compiling for a processor that lacks floating point support,
8828 ** substitute integer for floating-point
8829 */
8830 #ifdef SQLITE_OMIT_FLOATING_POINT
8831 # define double sqlite_int64
8832 # define float sqlite_int64
8833 # define LONGDOUBLE_TYPE sqlite_int64
8834 # ifndef SQLITE_BIG_DBL
8835 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
8836 # endif
8837 # define SQLITE_OMIT_DATETIME_FUNCS 1
8838 # define SQLITE_OMIT_TRACE 1
8839 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
8840 # undef SQLITE_HAVE_ISNAN
8841 #endif
8842 #ifndef SQLITE_BIG_DBL
8843 # define SQLITE_BIG_DBL (1e99)
8844 #endif
8845 
8846 /*
8847 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
8848 ** afterward. Having this macro allows us to cause the C compiler
8849 ** to omit code used by TEMP tables without messy #ifndef statements.
8850 */
8851 #ifdef SQLITE_OMIT_TEMPDB
8852 #define OMIT_TEMPDB 1
8853 #else
8854 #define OMIT_TEMPDB 0
8855 #endif
8856 
8857 /*
8858 ** The "file format" number is an integer that is incremented whenever
8859 ** the VDBE-level file format changes.  The following macros define the
8860 ** the default file format for new databases and the maximum file format
8861 ** that the library can read.
8862 */
8863 #define SQLITE_MAX_FILE_FORMAT 4
8864 #ifndef SQLITE_DEFAULT_FILE_FORMAT
8865 # define SQLITE_DEFAULT_FILE_FORMAT 4
8866 #endif
8867 
8868 /*
8869 ** Determine whether triggers are recursive by default.  This can be
8870 ** changed at run-time using a pragma.
8871 */
8872 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
8873 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
8874 #endif
8875 
8876 /*
8877 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
8878 ** on the command-line
8879 */
8880 #ifndef SQLITE_TEMP_STORE
8881 # define SQLITE_TEMP_STORE 1
8882 # define SQLITE_TEMP_STORE_xc 1  /* Exclude from ctime.c */
8883 #endif
8884 
8885 /*
8886 ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
8887 ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
8888 ** to zero.
8889 */
8890 #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
8891 # undef SQLITE_MAX_WORKER_THREADS
8892 # define SQLITE_MAX_WORKER_THREADS 0
8893 #endif
8894 #ifndef SQLITE_MAX_WORKER_THREADS
8895 # define SQLITE_MAX_WORKER_THREADS 8
8896 #endif
8897 #ifndef SQLITE_DEFAULT_WORKER_THREADS
8898 # define SQLITE_DEFAULT_WORKER_THREADS 0
8899 #endif
8900 #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
8901 # undef SQLITE_MAX_WORKER_THREADS
8902 # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
8903 #endif
8904 
8905 
8906 /*
8907 ** GCC does not define the offsetof() macro so we'll have to do it
8908 ** ourselves.
8909 */
8910 #ifndef offsetof
8911 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8912 #endif
8913 
8914 /*
8915 ** Macros to compute minimum and maximum of two numbers.
8916 */
8917 #define MIN(A,B) ((A)<(B)?(A):(B))
8918 #define MAX(A,B) ((A)>(B)?(A):(B))
8919 
8920 /*
8921 ** Swap two objects of type TYPE.
8922 */
8923 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
8924 
8925 /*
8926 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
8927 ** not, there are still machines out there that use EBCDIC.)
8928 */
8929 #if 'A' == '\301'
8930 # define SQLITE_EBCDIC 1
8931 #else
8932 # define SQLITE_ASCII 1
8933 #endif
8934 
8935 /*
8936 ** Integers of known sizes.  These typedefs might change for architectures
8937 ** where the sizes very.  Preprocessor macros are available so that the
8938 ** types can be conveniently redefined at compile-type.  Like this:
8939 **
8940 **         cc '-DUINTPTR_TYPE=long long int' ...
8941 */
8942 #ifndef UINT32_TYPE
8943 # ifdef HAVE_UINT32_T
8944 #  define UINT32_TYPE uint32_t
8945 # else
8946 #  define UINT32_TYPE unsigned int
8947 # endif
8948 #endif
8949 #ifndef UINT16_TYPE
8950 # ifdef HAVE_UINT16_T
8951 #  define UINT16_TYPE uint16_t
8952 # else
8953 #  define UINT16_TYPE unsigned short int
8954 # endif
8955 #endif
8956 #ifndef INT16_TYPE
8957 # ifdef HAVE_INT16_T
8958 #  define INT16_TYPE int16_t
8959 # else
8960 #  define INT16_TYPE short int
8961 # endif
8962 #endif
8963 #ifndef UINT8_TYPE
8964 # ifdef HAVE_UINT8_T
8965 #  define UINT8_TYPE uint8_t
8966 # else
8967 #  define UINT8_TYPE unsigned char
8968 # endif
8969 #endif
8970 #ifndef INT8_TYPE
8971 # ifdef HAVE_INT8_T
8972 #  define INT8_TYPE int8_t
8973 # else
8974 #  define INT8_TYPE signed char
8975 # endif
8976 #endif
8977 #ifndef LONGDOUBLE_TYPE
8978 # define LONGDOUBLE_TYPE long double
8979 #endif
8980 typedef sqlite_int64 i64;          /* 8-byte signed integer */
8981 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
8982 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
8983 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
8984 typedef INT16_TYPE i16;            /* 2-byte signed integer */
8985 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
8986 typedef INT8_TYPE i8;              /* 1-byte signed integer */
8987 
8988 /*
8989 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
8990 ** that can be stored in a u32 without loss of data.  The value
8991 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
8992 ** have to specify the value in the less intuitive manner shown:
8993 */
8994 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
8995 
8996 /*
8997 ** The datatype used to store estimates of the number of rows in a
8998 ** table or index.  This is an unsigned integer type.  For 99.9% of
8999 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
9000 ** can be used at compile-time if desired.
9001 */
9002 #ifdef SQLITE_64BIT_STATS
9003  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
9004 #else
9005  typedef u32 tRowcnt;    /* 32-bit is the default */
9006 #endif
9007 
9008 /*
9009 ** Estimated quantities used for query planning are stored as 16-bit
9010 ** logarithms.  For quantity X, the value stored is 10*log2(X).  This
9011 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
9012 ** But the allowed values are "grainy".  Not every value is representable.
9013 ** For example, quantities 16 and 17 are both represented by a LogEst
9014 ** of 40.  However, since LogEst quantities are suppose to be estimates,
9015 ** not exact values, this imprecision is not a problem.
9016 **
9017 ** "LogEst" is short for "Logarithmic Estimate".
9018 **
9019 ** Examples:
9020 **      1 -> 0              20 -> 43          10000 -> 132
9021 **      2 -> 10             25 -> 46          25000 -> 146
9022 **      3 -> 16            100 -> 66        1000000 -> 199
9023 **      4 -> 20           1000 -> 99        1048576 -> 200
9024 **     10 -> 33           1024 -> 100    4294967296 -> 320
9025 **
9026 ** The LogEst can be negative to indicate fractional values.
9027 ** Examples:
9028 **
9029 **    0.5 -> -10           0.1 -> -33        0.0625 -> -40
9030 */
9031 typedef INT16_TYPE LogEst;
9032 
9033 /*
9034 ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
9035 */
9036 #ifndef SQLITE_PTRSIZE
9037 # if defined(__SIZEOF_POINTER__)
9038 #   define SQLITE_PTRSIZE __SIZEOF_POINTER__
9039 # elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
9040        defined(_M_ARM)   || defined(__arm__)    || defined(__x86)
9041 #   define SQLITE_PTRSIZE 4
9042 # else
9043 #   define SQLITE_PTRSIZE 8
9044 # endif
9045 #endif
9046 
9047 /*
9048 ** Macros to determine whether the machine is big or little endian,
9049 ** and whether or not that determination is run-time or compile-time.
9050 **
9051 ** For best performance, an attempt is made to guess at the byte-order
9052 ** using C-preprocessor macros.  If that is unsuccessful, or if
9053 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
9054 ** at run-time.
9055 */
9056 #ifdef SQLITE_AMALGAMATION
9057 SQLITE_PRIVATE const int sqlite3one = 1;
9058 #else
9059 SQLITE_PRIVATE const int sqlite3one;
9060 #endif
9061 #if (defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
9062      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
9063      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
9064      defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
9065 # define SQLITE_BYTEORDER    1234
9066 # define SQLITE_BIGENDIAN    0
9067 # define SQLITE_LITTLEENDIAN 1
9068 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
9069 #endif
9070 #if (defined(sparc)    || defined(__ppc__))  \
9071     && !defined(SQLITE_RUNTIME_BYTEORDER)
9072 # define SQLITE_BYTEORDER    4321
9073 # define SQLITE_BIGENDIAN    1
9074 # define SQLITE_LITTLEENDIAN 0
9075 # define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
9076 #endif
9077 #if !defined(SQLITE_BYTEORDER)
9078 # define SQLITE_BYTEORDER    0     /* 0 means "unknown at compile-time" */
9079 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
9080 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
9081 # define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
9082 #endif
9083 
9084 /*
9085 ** Constants for the largest and smallest possible 64-bit signed integers.
9086 ** These macros are designed to work correctly on both 32-bit and 64-bit
9087 ** compilers.
9088 */
9089 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
9090 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
9091 
9092 /*
9093 ** Round up a number to the next larger multiple of 8.  This is used
9094 ** to force 8-byte alignment on 64-bit architectures.
9095 */
9096 #define ROUND8(x)     (((x)+7)&~7)
9097 
9098 /*
9099 ** Round down to the nearest multiple of 8
9100 */
9101 #define ROUNDDOWN8(x) ((x)&~7)
9102 
9103 /*
9104 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
9105 ** macro is used only within assert() to verify that the code gets
9106 ** all alignment restrictions correct.
9107 **
9108 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
9109 ** underlying malloc() implementation might return us 4-byte aligned
9110 ** pointers.  In that case, only verify 4-byte alignment.
9111 */
9112 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
9113 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
9114 #else
9115 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
9116 #endif
9117 
9118 /*
9119 ** Disable MMAP on platforms where it is known to not work
9120 */
9121 #if defined(__OpenBSD__) || defined(__QNXNTO__)
9122 # undef SQLITE_MAX_MMAP_SIZE
9123 # define SQLITE_MAX_MMAP_SIZE 0
9124 #endif
9125 
9126 /*
9127 ** Default maximum size of memory used by memory-mapped I/O in the VFS
9128 */
9129 #ifdef __APPLE__
9130 # include <TargetConditionals.h>
9131 # if TARGET_OS_IPHONE
9132 #   undef SQLITE_MAX_MMAP_SIZE
9133 #   define SQLITE_MAX_MMAP_SIZE 0
9134 # endif
9135 #endif
9136 #ifndef SQLITE_MAX_MMAP_SIZE
9137 # if defined(__linux__) \
9138   || defined(_WIN32) \
9139   || (defined(__APPLE__) && defined(__MACH__)) \
9140   || defined(__sun)
9141 #   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
9142 # else
9143 #   define SQLITE_MAX_MMAP_SIZE 0
9144 # endif
9145 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
9146 #endif
9147 
9148 /*
9149 ** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
9150 ** default MMAP_SIZE is specified at compile-time, make sure that it does
9151 ** not exceed the maximum mmap size.
9152 */
9153 #ifndef SQLITE_DEFAULT_MMAP_SIZE
9154 # define SQLITE_DEFAULT_MMAP_SIZE 0
9155 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1  /* Exclude from ctime.c */
9156 #endif
9157 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
9158 # undef SQLITE_DEFAULT_MMAP_SIZE
9159 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
9160 #endif
9161 
9162 /*
9163 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
9164 ** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
9165 ** define SQLITE_ENABLE_STAT3_OR_STAT4
9166 */
9167 #ifdef SQLITE_ENABLE_STAT4
9168 # undef SQLITE_ENABLE_STAT3
9169 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
9170 #elif SQLITE_ENABLE_STAT3
9171 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
9172 #elif SQLITE_ENABLE_STAT3_OR_STAT4
9173 # undef SQLITE_ENABLE_STAT3_OR_STAT4
9174 #endif
9175 
9176 /*
9177 ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
9178 ** the Select query generator tracing logic is turned on.
9179 */
9180 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
9181 # define SELECTTRACE_ENABLED 1
9182 #else
9183 # define SELECTTRACE_ENABLED 0
9184 #endif
9185 
9186 /*
9187 ** An instance of the following structure is used to store the busy-handler
9188 ** callback for a given sqlite handle.
9189 **
9190 ** The sqlite.busyHandler member of the sqlite struct contains the busy
9191 ** callback for the database handle. Each pager opened via the sqlite
9192 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
9193 ** callback is currently invoked only from within pager.c.
9194 */
9195 typedef struct BusyHandler BusyHandler;
9196 struct BusyHandler {
9197   int (*xFunc)(void *,int);  /* The busy callback */
9198   void *pArg;                /* First arg to busy callback */
9199   int nBusy;                 /* Incremented with each busy call */
9200 };
9201 
9202 /*
9203 ** Name of the master database table.  The master database table
9204 ** is a special table that holds the names and attributes of all
9205 ** user tables and indices.
9206 */
9207 #define MASTER_NAME       "sqlite_master"
9208 #define TEMP_MASTER_NAME  "sqlite_temp_master"
9209 
9210 /*
9211 ** The root-page of the master database table.
9212 */
9213 #define MASTER_ROOT       1
9214 
9215 /*
9216 ** The name of the schema table.
9217 */
9218 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
9219 
9220 /*
9221 ** A convenience macro that returns the number of elements in
9222 ** an array.
9223 */
9224 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
9225 
9226 /*
9227 ** Determine if the argument is a power of two
9228 */
9229 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
9230 
9231 /*
9232 ** The following value as a destructor means to use sqlite3DbFree().
9233 ** The sqlite3DbFree() routine requires two parameters instead of the
9234 ** one parameter that destructors normally want.  So we have to introduce
9235 ** this magic value that the code knows to handle differently.  Any
9236 ** pointer will work here as long as it is distinct from SQLITE_STATIC
9237 ** and SQLITE_TRANSIENT.
9238 */
9239 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
9240 
9241 /*
9242 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
9243 ** not support Writable Static Data (WSD) such as global and static variables.
9244 ** All variables must either be on the stack or dynamically allocated from
9245 ** the heap.  When WSD is unsupported, the variable declarations scattered
9246 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
9247 ** macro is used for this purpose.  And instead of referencing the variable
9248 ** directly, we use its constant as a key to lookup the run-time allocated
9249 ** buffer that holds real variable.  The constant is also the initializer
9250 ** for the run-time allocated buffer.
9251 **
9252 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
9253 ** macros become no-ops and have zero performance impact.
9254 */
9255 #ifdef SQLITE_OMIT_WSD
9256   #define SQLITE_WSD const
9257   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
9258   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
9259 SQLITE_API int SQLITE_STDCALL sqlite3_wsd_init(int N, int J);
9260 SQLITE_API void *SQLITE_STDCALL sqlite3_wsd_find(void *K, int L);
9261 #else
9262   #define SQLITE_WSD
9263   #define GLOBAL(t,v) v
9264   #define sqlite3GlobalConfig sqlite3Config
9265 #endif
9266 
9267 /*
9268 ** The following macros are used to suppress compiler warnings and to
9269 ** make it clear to human readers when a function parameter is deliberately
9270 ** left unused within the body of a function. This usually happens when
9271 ** a function is called via a function pointer. For example the
9272 ** implementation of an SQL aggregate step callback may not use the
9273 ** parameter indicating the number of arguments passed to the aggregate,
9274 ** if it knows that this is enforced elsewhere.
9275 **
9276 ** When a function parameter is not used at all within the body of a function,
9277 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
9278 ** However, these macros may also be used to suppress warnings related to
9279 ** parameters that may or may not be used depending on compilation options.
9280 ** For example those parameters only used in assert() statements. In these
9281 ** cases the parameters are named as per the usual conventions.
9282 */
9283 #define UNUSED_PARAMETER(x) (void)(x)
9284 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
9285 
9286 /*
9287 ** Forward references to structures
9288 */
9289 typedef struct AggInfo AggInfo;
9290 typedef struct AuthContext AuthContext;
9291 typedef struct AutoincInfo AutoincInfo;
9292 typedef struct Bitvec Bitvec;
9293 typedef struct CollSeq CollSeq;
9294 typedef struct Column Column;
9295 typedef struct Db Db;
9296 typedef struct Schema Schema;
9297 typedef struct Expr Expr;
9298 typedef struct ExprList ExprList;
9299 typedef struct ExprSpan ExprSpan;
9300 typedef struct FKey FKey;
9301 typedef struct FuncDestructor FuncDestructor;
9302 typedef struct FuncDef FuncDef;
9303 typedef struct FuncDefHash FuncDefHash;
9304 typedef struct IdList IdList;
9305 typedef struct Index Index;
9306 typedef struct IndexSample IndexSample;
9307 typedef struct KeyClass KeyClass;
9308 typedef struct KeyInfo KeyInfo;
9309 typedef struct Lookaside Lookaside;
9310 typedef struct LookasideSlot LookasideSlot;
9311 typedef struct Module Module;
9312 typedef struct NameContext NameContext;
9313 typedef struct Parse Parse;
9314 typedef struct PrintfArguments PrintfArguments;
9315 typedef struct RowSet RowSet;
9316 typedef struct Savepoint Savepoint;
9317 typedef struct Select Select;
9318 typedef struct SQLiteThread SQLiteThread;
9319 typedef struct SelectDest SelectDest;
9320 typedef struct SrcList SrcList;
9321 typedef struct StrAccum StrAccum;
9322 typedef struct Table Table;
9323 typedef struct TableLock TableLock;
9324 typedef struct Token Token;
9325 typedef struct TreeView TreeView;
9326 typedef struct Trigger Trigger;
9327 typedef struct TriggerPrg TriggerPrg;
9328 typedef struct TriggerStep TriggerStep;
9329 typedef struct UnpackedRecord UnpackedRecord;
9330 typedef struct VTable VTable;
9331 typedef struct VtabCtx VtabCtx;
9332 typedef struct Walker Walker;
9333 typedef struct WhereInfo WhereInfo;
9334 typedef struct With With;
9335 
9336 /*
9337 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
9338 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
9339 ** pointer types (i.e. FuncDef) defined above.
9340 */
9341 /************** Include btree.h in the middle of sqliteInt.h *****************/
9342 /************** Begin file btree.h *******************************************/
9343 /*
9344 ** 2001 September 15
9345 **
9346 ** The author disclaims copyright to this source code.  In place of
9347 ** a legal notice, here is a blessing:
9348 **
9349 **    May you do good and not evil.
9350 **    May you find forgiveness for yourself and forgive others.
9351 **    May you share freely, never taking more than you give.
9352 **
9353 *************************************************************************
9354 ** This header file defines the interface that the sqlite B-Tree file
9355 ** subsystem.  See comments in the source code for a detailed description
9356 ** of what each interface routine does.
9357 */
9358 #ifndef _BTREE_H_
9359 #define _BTREE_H_
9360 
9361 /* TODO: This definition is just included so other modules compile. It
9362 ** needs to be revisited.
9363 */
9364 #define SQLITE_N_BTREE_META 16
9365 
9366 /*
9367 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
9368 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
9369 */
9370 #ifndef SQLITE_DEFAULT_AUTOVACUUM
9371   #define SQLITE_DEFAULT_AUTOVACUUM 0
9372 #endif
9373 
9374 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
9375 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
9376 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
9377 
9378 /*
9379 ** Forward declarations of structure
9380 */
9381 typedef struct Btree Btree;
9382 typedef struct BtCursor BtCursor;
9383 typedef struct BtShared BtShared;
9384 
9385 
9386 SQLITE_PRIVATE int sqlite3BtreeOpen(
9387   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
9388   const char *zFilename,   /* Name of database file to open */
9389   sqlite3 *db,             /* Associated database connection */
9390   Btree **ppBtree,         /* Return open Btree* here */
9391   int flags,               /* Flags */
9392   int vfsFlags             /* Flags passed through to VFS open */
9393 );
9394 
9395 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
9396 ** following values.
9397 **
9398 ** NOTE:  These values must match the corresponding PAGER_ values in
9399 ** pager.h.
9400 */
9401 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
9402 #define BTREE_MEMORY        2  /* This is an in-memory DB */
9403 #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
9404 #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
9405 
9406 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
9407 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
9408 #if SQLITE_MAX_MMAP_SIZE>0
9409 SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
9410 #endif
9411 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
9412 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
9413 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
9414 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
9415 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
9416 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
9417 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
9418 SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
9419 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
9420 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
9421 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
9422 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
9423 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
9424 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
9425 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
9426 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
9427 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
9428 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
9429 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
9430 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
9431 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
9432 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
9433 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
9434 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
9435 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
9436 
9437 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
9438 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
9439 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
9440 
9441 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
9442 
9443 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
9444 ** of the flags shown below.
9445 **
9446 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
9447 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
9448 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
9449 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
9450 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
9451 ** indices.)
9452 */
9453 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
9454 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
9455 
9456 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
9457 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
9458 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
9459 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
9460 
9461 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
9462 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
9463 
9464 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
9465 
9466 /*
9467 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
9468 ** should be one of the following values. The integer values are assigned
9469 ** to constants so that the offset of the corresponding field in an
9470 ** SQLite database header may be found using the following formula:
9471 **
9472 **   offset = 36 + (idx * 4)
9473 **
9474 ** For example, the free-page-count field is located at byte offset 36 of
9475 ** the database file header. The incr-vacuum-flag field is located at
9476 ** byte offset 64 (== 36+4*7).
9477 **
9478 ** The BTREE_DATA_VERSION value is not really a value stored in the header.
9479 ** It is a read-only number computed by the pager.  But we merge it with
9480 ** the header value access routines since its access pattern is the same.
9481 ** Call it a "virtual meta value".
9482 */
9483 #define BTREE_FREE_PAGE_COUNT     0
9484 #define BTREE_SCHEMA_VERSION      1
9485 #define BTREE_FILE_FORMAT         2
9486 #define BTREE_DEFAULT_CACHE_SIZE  3
9487 #define BTREE_LARGEST_ROOT_PAGE   4
9488 #define BTREE_TEXT_ENCODING       5
9489 #define BTREE_USER_VERSION        6
9490 #define BTREE_INCR_VACUUM         7
9491 #define BTREE_APPLICATION_ID      8
9492 #define BTREE_DATA_VERSION        15  /* A virtual meta-value */
9493 
9494 /*
9495 ** Values that may be OR'd together to form the second argument of an
9496 ** sqlite3BtreeCursorHints() call.
9497 **
9498 ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
9499 ** to be filled with content that is already in sorted order.
9500 **
9501 ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
9502 ** OP_SeekLE opcodes for a range search, but where the range of entries
9503 ** selected will all have the same key.  In other words, the cursor will
9504 ** be used only for equality key searches.
9505 **
9506 */
9507 #define BTREE_BULKLOAD 0x00000001  /* Used to full index in sorted order */
9508 #define BTREE_SEEK_EQ  0x00000002  /* EQ seeks only - no range seeks */
9509 
9510 SQLITE_PRIVATE int sqlite3BtreeCursor(
9511   Btree*,                              /* BTree containing table to open */
9512   int iTable,                          /* Index of root page */
9513   int wrFlag,                          /* 1 for writing.  0 for read-only */
9514   struct KeyInfo*,                     /* First argument to compare function */
9515   BtCursor *pCursor                    /* Space to write cursor structure */
9516 );
9517 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
9518 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
9519 
9520 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
9521 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
9522   BtCursor*,
9523   UnpackedRecord *pUnKey,
9524   i64 intKey,
9525   int bias,
9526   int *pRes
9527 );
9528 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
9529 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
9530 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
9531 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
9532                                   const void *pData, int nData,
9533                                   int nZero, int bias, int seekResult);
9534 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
9535 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
9536 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
9537 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
9538 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
9539 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
9540 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
9541 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
9542 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
9543 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
9544 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
9545 
9546 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
9547 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
9548 
9549 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
9550 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
9551 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
9552 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
9553 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
9554 #ifdef SQLITE_DEBUG
9555 SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
9556 #endif
9557 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
9558 SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
9559 
9560 #ifndef NDEBUG
9561 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
9562 #endif
9563 
9564 #ifndef SQLITE_OMIT_BTREECOUNT
9565 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
9566 #endif
9567 
9568 #ifdef SQLITE_TEST
9569 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
9570 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
9571 #endif
9572 
9573 #ifndef SQLITE_OMIT_WAL
9574 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
9575 #endif
9576 
9577 /*
9578 ** If we are not using shared cache, then there is no need to
9579 ** use mutexes to access the BtShared structures.  So make the
9580 ** Enter and Leave procedures no-ops.
9581 */
9582 #ifndef SQLITE_OMIT_SHARED_CACHE
9583 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
9584 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
9585 #else
9586 # define sqlite3BtreeEnter(X)
9587 # define sqlite3BtreeEnterAll(X)
9588 #endif
9589 
9590 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
9591 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
9592 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
9593 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
9594 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
9595 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
9596 #ifndef NDEBUG
9597   /* These routines are used inside assert() statements only. */
9598 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
9599 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
9600 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
9601 #endif
9602 #else
9603 
9604 # define sqlite3BtreeSharable(X) 0
9605 # define sqlite3BtreeLeave(X)
9606 # define sqlite3BtreeEnterCursor(X)
9607 # define sqlite3BtreeLeaveCursor(X)
9608 # define sqlite3BtreeLeaveAll(X)
9609 
9610 # define sqlite3BtreeHoldsMutex(X) 1
9611 # define sqlite3BtreeHoldsAllMutexes(X) 1
9612 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
9613 #endif
9614 
9615 
9616 #endif /* _BTREE_H_ */
9617 
9618 /************** End of btree.h ***********************************************/
9619 /************** Continuing where we left off in sqliteInt.h ******************/
9620 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
9621 /************** Begin file vdbe.h ********************************************/
9622 /*
9623 ** 2001 September 15
9624 **
9625 ** The author disclaims copyright to this source code.  In place of
9626 ** a legal notice, here is a blessing:
9627 **
9628 **    May you do good and not evil.
9629 **    May you find forgiveness for yourself and forgive others.
9630 **    May you share freely, never taking more than you give.
9631 **
9632 *************************************************************************
9633 ** Header file for the Virtual DataBase Engine (VDBE)
9634 **
9635 ** This header defines the interface to the virtual database engine
9636 ** or VDBE.  The VDBE implements an abstract machine that runs a
9637 ** simple program to access and modify the underlying database.
9638 */
9639 #ifndef _SQLITE_VDBE_H_
9640 #define _SQLITE_VDBE_H_
9641 /* #include <stdio.h> */
9642 
9643 /*
9644 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
9645 ** in the source file sqliteVdbe.c are allowed to see the insides
9646 ** of this structure.
9647 */
9648 typedef struct Vdbe Vdbe;
9649 
9650 /*
9651 ** The names of the following types declared in vdbeInt.h are required
9652 ** for the VdbeOp definition.
9653 */
9654 typedef struct Mem Mem;
9655 typedef struct SubProgram SubProgram;
9656 
9657 /*
9658 ** A single instruction of the virtual machine has an opcode
9659 ** and as many as three operands.  The instruction is recorded
9660 ** as an instance of the following structure:
9661 */
9662 struct VdbeOp {
9663   u8 opcode;          /* What operation to perform */
9664   signed char p4type; /* One of the P4_xxx constants for p4 */
9665   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
9666   u8 p5;              /* Fifth parameter is an unsigned character */
9667   int p1;             /* First operand */
9668   int p2;             /* Second parameter (often the jump destination) */
9669   int p3;             /* The third parameter */
9670   union {             /* fourth parameter */
9671     int i;                 /* Integer value if p4type==P4_INT32 */
9672     void *p;               /* Generic pointer */
9673     char *z;               /* Pointer to data for string (char array) types */
9674     i64 *pI64;             /* Used when p4type is P4_INT64 */
9675     double *pReal;         /* Used when p4type is P4_REAL */
9676     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
9677     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
9678     Mem *pMem;             /* Used when p4type is P4_MEM */
9679     VTable *pVtab;         /* Used when p4type is P4_VTAB */
9680     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
9681     int *ai;               /* Used when p4type is P4_INTARRAY */
9682     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
9683     int (*xAdvance)(BtCursor *, int *);
9684   } p4;
9685 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
9686   char *zComment;          /* Comment to improve readability */
9687 #endif
9688 #ifdef VDBE_PROFILE
9689   u32 cnt;                 /* Number of times this instruction was executed */
9690   u64 cycles;              /* Total time spent executing this instruction */
9691 #endif
9692 #ifdef SQLITE_VDBE_COVERAGE
9693   int iSrcLine;            /* Source-code line that generated this opcode */
9694 #endif
9695 };
9696 typedef struct VdbeOp VdbeOp;
9697 
9698 
9699 /*
9700 ** A sub-routine used to implement a trigger program.
9701 */
9702 struct SubProgram {
9703   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
9704   int nOp;                      /* Elements in aOp[] */
9705   int nMem;                     /* Number of memory cells required */
9706   int nCsr;                     /* Number of cursors required */
9707   int nOnce;                    /* Number of OP_Once instructions */
9708   void *token;                  /* id that may be used to recursive triggers */
9709   SubProgram *pNext;            /* Next sub-program already visited */
9710 };
9711 
9712 /*
9713 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
9714 ** it takes up less space.
9715 */
9716 struct VdbeOpList {
9717   u8 opcode;          /* What operation to perform */
9718   signed char p1;     /* First operand */
9719   signed char p2;     /* Second parameter (often the jump destination) */
9720   signed char p3;     /* Third parameter */
9721 };
9722 typedef struct VdbeOpList VdbeOpList;
9723 
9724 /*
9725 ** Allowed values of VdbeOp.p4type
9726 */
9727 #define P4_NOTUSED    0   /* The P4 parameter is not used */
9728 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
9729 #define P4_STATIC   (-2)  /* Pointer to a static string */
9730 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
9731 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
9732 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
9733 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
9734 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
9735 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
9736 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
9737 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
9738 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
9739 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
9740 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
9741 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
9742 #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
9743 
9744 /* Error message codes for OP_Halt */
9745 #define P5_ConstraintNotNull 1
9746 #define P5_ConstraintUnique  2
9747 #define P5_ConstraintCheck   3
9748 #define P5_ConstraintFK      4
9749 
9750 /*
9751 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
9752 ** number of columns of data returned by the statement.
9753 */
9754 #define COLNAME_NAME     0
9755 #define COLNAME_DECLTYPE 1
9756 #define COLNAME_DATABASE 2
9757 #define COLNAME_TABLE    3
9758 #define COLNAME_COLUMN   4
9759 #ifdef SQLITE_ENABLE_COLUMN_METADATA
9760 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
9761 #else
9762 # ifdef SQLITE_OMIT_DECLTYPE
9763 #   define COLNAME_N      1      /* Store only the name */
9764 # else
9765 #   define COLNAME_N      2      /* Store the name and decltype */
9766 # endif
9767 #endif
9768 
9769 /*
9770 ** The following macro converts a relative address in the p2 field
9771 ** of a VdbeOp structure into a negative number so that
9772 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
9773 ** the macro again restores the address.
9774 */
9775 #define ADDR(X)  (-1-(X))
9776 
9777 /*
9778 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
9779 ** header file that defines a number for each opcode used by the VDBE.
9780 */
9781 /************** Include opcodes.h in the middle of vdbe.h ********************/
9782 /************** Begin file opcodes.h *****************************************/
9783 /* Automatically generated.  Do not edit */
9784 /* See the mkopcodeh.awk script for details */
9785 #define OP_Function        1 /* synopsis: r[P3]=func(r[P2@P5])             */
9786 #define OP_Savepoint       2
9787 #define OP_AutoCommit      3
9788 #define OP_Transaction     4
9789 #define OP_SorterNext      5
9790 #define OP_PrevIfOpen      6
9791 #define OP_NextIfOpen      7
9792 #define OP_Prev            8
9793 #define OP_Next            9
9794 #define OP_AggStep        10 /* synopsis: accum=r[P3] step(r[P2@P5])       */
9795 #define OP_Checkpoint     11
9796 #define OP_JournalMode    12
9797 #define OP_Vacuum         13
9798 #define OP_VFilter        14 /* synopsis: iplan=r[P3] zplan='P4'           */
9799 #define OP_VUpdate        15 /* synopsis: data=r[P3@P2]                    */
9800 #define OP_Goto           16
9801 #define OP_Gosub          17
9802 #define OP_Return         18
9803 #define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
9804 #define OP_InitCoroutine  20
9805 #define OP_EndCoroutine   21
9806 #define OP_Yield          22
9807 #define OP_HaltIfNull     23 /* synopsis: if r[P3]=null halt               */
9808 #define OP_Halt           24
9809 #define OP_Integer        25 /* synopsis: r[P2]=P1                         */
9810 #define OP_Int64          26 /* synopsis: r[P2]=P4                         */
9811 #define OP_String         27 /* synopsis: r[P2]='P4' (len=P1)              */
9812 #define OP_Null           28 /* synopsis: r[P2..P3]=NULL                   */
9813 #define OP_SoftNull       29 /* synopsis: r[P1]=NULL                       */
9814 #define OP_Blob           30 /* synopsis: r[P2]=P4 (len=P1)                */
9815 #define OP_Variable       31 /* synopsis: r[P2]=parameter(P1,P4)           */
9816 #define OP_Move           32 /* synopsis: r[P2@P3]=r[P1@P3]                */
9817 #define OP_Copy           33 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
9818 #define OP_SCopy          34 /* synopsis: r[P2]=r[P1]                      */
9819 #define OP_ResultRow      35 /* synopsis: output=r[P1@P2]                  */
9820 #define OP_CollSeq        36
9821 #define OP_AddImm         37 /* synopsis: r[P1]=r[P1]+P2                   */
9822 #define OP_MustBeInt      38
9823 #define OP_RealAffinity   39
9824 #define OP_Cast           40 /* synopsis: affinity(r[P1])                  */
9825 #define OP_Permutation    41
9826 #define OP_Compare        42 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
9827 #define OP_Jump           43
9828 #define OP_Once           44
9829 #define OP_If             45
9830 #define OP_IfNot          46
9831 #define OP_Column         47 /* synopsis: r[P3]=PX                         */
9832 #define OP_Affinity       48 /* synopsis: affinity(r[P1@P2])               */
9833 #define OP_MakeRecord     49 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
9834 #define OP_Count          50 /* synopsis: r[P2]=count()                    */
9835 #define OP_ReadCookie     51
9836 #define OP_SetCookie      52
9837 #define OP_ReopenIdx      53 /* synopsis: root=P2 iDb=P3                   */
9838 #define OP_OpenRead       54 /* synopsis: root=P2 iDb=P3                   */
9839 #define OP_OpenWrite      55 /* synopsis: root=P2 iDb=P3                   */
9840 #define OP_OpenAutoindex  56 /* synopsis: nColumn=P2                       */
9841 #define OP_OpenEphemeral  57 /* synopsis: nColumn=P2                       */
9842 #define OP_SorterOpen     58
9843 #define OP_SequenceTest   59 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
9844 #define OP_OpenPseudo     60 /* synopsis: P3 columns in r[P2]              */
9845 #define OP_Close          61
9846 #define OP_SeekLT         62 /* synopsis: key=r[P3@P4]                     */
9847 #define OP_SeekLE         63 /* synopsis: key=r[P3@P4]                     */
9848 #define OP_SeekGE         64 /* synopsis: key=r[P3@P4]                     */
9849 #define OP_SeekGT         65 /* synopsis: key=r[P3@P4]                     */
9850 #define OP_Seek           66 /* synopsis: intkey=r[P2]                     */
9851 #define OP_NoConflict     67 /* synopsis: key=r[P3@P4]                     */
9852 #define OP_NotFound       68 /* synopsis: key=r[P3@P4]                     */
9853 #define OP_Found          69 /* synopsis: key=r[P3@P4]                     */
9854 #define OP_NotExists      70 /* synopsis: intkey=r[P3]                     */
9855 #define OP_Or             71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
9856 #define OP_And            72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
9857 #define OP_Sequence       73 /* synopsis: r[P2]=cursor[P1].ctr++           */
9858 #define OP_NewRowid       74 /* synopsis: r[P2]=rowid                      */
9859 #define OP_Insert         75 /* synopsis: intkey=r[P3] data=r[P2]          */
9860 #define OP_IsNull         76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
9861 #define OP_NotNull        77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
9862 #define OP_Ne             78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
9863 #define OP_Eq             79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
9864 #define OP_Gt             80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
9865 #define OP_Le             81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
9866 #define OP_Lt             82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
9867 #define OP_Ge             83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
9868 #define OP_InsertInt      84 /* synopsis: intkey=P3 data=r[P2]             */
9869 #define OP_BitAnd         85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
9870 #define OP_BitOr          86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
9871 #define OP_ShiftLeft      87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
9872 #define OP_ShiftRight     88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
9873 #define OP_Add            89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
9874 #define OP_Subtract       90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
9875 #define OP_Multiply       91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
9876 #define OP_Divide         92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
9877 #define OP_Remainder      93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
9878 #define OP_Concat         94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
9879 #define OP_Delete         95
9880 #define OP_BitNot         96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
9881 #define OP_String8        97 /* same as TK_STRING, synopsis: r[P2]='P4'    */
9882 #define OP_ResetCount     98
9883 #define OP_SorterCompare  99 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
9884 #define OP_SorterData    100 /* synopsis: r[P2]=data                       */
9885 #define OP_RowKey        101 /* synopsis: r[P2]=key                        */
9886 #define OP_RowData       102 /* synopsis: r[P2]=data                       */
9887 #define OP_Rowid         103 /* synopsis: r[P2]=rowid                      */
9888 #define OP_NullRow       104
9889 #define OP_Last          105
9890 #define OP_SorterSort    106
9891 #define OP_Sort          107
9892 #define OP_Rewind        108
9893 #define OP_SorterInsert  109
9894 #define OP_IdxInsert     110 /* synopsis: key=r[P2]                        */
9895 #define OP_IdxDelete     111 /* synopsis: key=r[P2@P3]                     */
9896 #define OP_IdxRowid      112 /* synopsis: r[P2]=rowid                      */
9897 #define OP_IdxLE         113 /* synopsis: key=r[P3@P4]                     */
9898 #define OP_IdxGT         114 /* synopsis: key=r[P3@P4]                     */
9899 #define OP_IdxLT         115 /* synopsis: key=r[P3@P4]                     */
9900 #define OP_IdxGE         116 /* synopsis: key=r[P3@P4]                     */
9901 #define OP_Destroy       117
9902 #define OP_Clear         118
9903 #define OP_ResetSorter   119
9904 #define OP_CreateIndex   120 /* synopsis: r[P2]=root iDb=P1                */
9905 #define OP_CreateTable   121 /* synopsis: r[P2]=root iDb=P1                */
9906 #define OP_ParseSchema   122
9907 #define OP_LoadAnalysis  123
9908 #define OP_DropTable     124
9909 #define OP_DropIndex     125
9910 #define OP_DropTrigger   126
9911 #define OP_IntegrityCk   127
9912 #define OP_RowSetAdd     128 /* synopsis: rowset(P1)=r[P2]                 */
9913 #define OP_RowSetRead    129 /* synopsis: r[P3]=rowset(P1)                 */
9914 #define OP_RowSetTest    130 /* synopsis: if r[P3] in rowset(P1) goto P2   */
9915 #define OP_Program       131
9916 #define OP_Param         132
9917 #define OP_Real          133 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
9918 #define OP_FkCounter     134 /* synopsis: fkctr[P1]+=P2                    */
9919 #define OP_FkIfZero      135 /* synopsis: if fkctr[P1]==0 goto P2          */
9920 #define OP_MemMax        136 /* synopsis: r[P1]=max(r[P1],r[P2])           */
9921 #define OP_IfPos         137 /* synopsis: if r[P1]>0 goto P2               */
9922 #define OP_IfNeg         138 /* synopsis: r[P1]+=P3, if r[P1]<0 goto P2    */
9923 #define OP_IfNotZero     139 /* synopsis: if r[P1]!=0 then r[P1]+=P3, goto P2 */
9924 #define OP_DecrJumpZero  140 /* synopsis: if (--r[P1])==0 goto P2          */
9925 #define OP_JumpZeroIncr  141 /* synopsis: if (r[P1]++)==0 ) goto P2        */
9926 #define OP_AggFinal      142 /* synopsis: accum=r[P1] N=P2                 */
9927 #define OP_IncrVacuum    143
9928 #define OP_Expire        144
9929 #define OP_TableLock     145 /* synopsis: iDb=P1 root=P2 write=P3          */
9930 #define OP_VBegin        146
9931 #define OP_VCreate       147
9932 #define OP_VDestroy      148
9933 #define OP_VOpen         149
9934 #define OP_VColumn       150 /* synopsis: r[P3]=vcolumn(P2)                */
9935 #define OP_VNext         151
9936 #define OP_VRename       152
9937 #define OP_Pagecount     153
9938 #define OP_MaxPgcnt      154
9939 #define OP_Init          155 /* synopsis: Start at P2                      */
9940 #define OP_Noop          156
9941 #define OP_Explain       157
9942 
9943 
9944 /* Properties such as "out2" or "jump" that are specified in
9945 ** comments following the "case" for each opcode in the vdbe.c
9946 ** are encoded into bitvectors as follows:
9947 */
9948 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
9949 #define OPFLG_IN1             0x0002  /* in1:   P1 is an input */
9950 #define OPFLG_IN2             0x0004  /* in2:   P2 is an input */
9951 #define OPFLG_IN3             0x0008  /* in3:   P3 is an input */
9952 #define OPFLG_OUT2            0x0010  /* out2:  P2 is an output */
9953 #define OPFLG_OUT3            0x0020  /* out3:  P3 is an output */
9954 #define OPFLG_INITIALIZER {\
9955 /*   0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
9956 /*   8 */ 0x01, 0x01, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00,\
9957 /*  16 */ 0x01, 0x01, 0x02, 0x12, 0x01, 0x02, 0x03, 0x08,\
9958 /*  24 */ 0x00, 0x10, 0x10, 0x10, 0x10, 0x00, 0x10, 0x10,\
9959 /*  32 */ 0x00, 0x00, 0x10, 0x00, 0x00, 0x02, 0x03, 0x02,\
9960 /*  40 */ 0x02, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03, 0x00,\
9961 /*  48 */ 0x00, 0x00, 0x10, 0x10, 0x08, 0x00, 0x00, 0x00,\
9962 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x09,\
9963 /*  64 */ 0x09, 0x09, 0x04, 0x09, 0x09, 0x09, 0x09, 0x26,\
9964 /*  72 */ 0x26, 0x10, 0x10, 0x00, 0x03, 0x03, 0x0b, 0x0b,\
9965 /*  80 */ 0x0b, 0x0b, 0x0b, 0x0b, 0x00, 0x26, 0x26, 0x26,\
9966 /*  88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\
9967 /*  96 */ 0x12, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\
9968 /* 104 */ 0x00, 0x01, 0x01, 0x01, 0x01, 0x04, 0x04, 0x00,\
9969 /* 112 */ 0x10, 0x01, 0x01, 0x01, 0x01, 0x10, 0x00, 0x00,\
9970 /* 120 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
9971 /* 128 */ 0x06, 0x23, 0x0b, 0x01, 0x10, 0x10, 0x00, 0x01,\
9972 /* 136 */ 0x04, 0x03, 0x03, 0x03, 0x03, 0x03, 0x00, 0x01,\
9973 /* 144 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,\
9974 /* 152 */ 0x00, 0x10, 0x10, 0x01, 0x00, 0x00,}
9975 
9976 /************** End of opcodes.h *********************************************/
9977 /************** Continuing where we left off in vdbe.h ***********************/
9978 
9979 /*
9980 ** Prototypes for the VDBE interface.  See comments on the implementation
9981 ** for a description of what each of these routines does.
9982 */
9983 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
9984 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
9985 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
9986 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
9987 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
9988 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
9989 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
9990 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
9991 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
9992 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
9993 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
9994 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
9995 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
9996 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
9997 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
9998 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
9999 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
10000 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
10001 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
10002 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
10003 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
10004 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
10005 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
10006 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
10007 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
10008 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
10009 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
10010 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
10011 #ifdef SQLITE_DEBUG
10012 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
10013 #endif
10014 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
10015 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
10016 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
10017 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
10018 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
10019 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
10020 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
10021 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
10022 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
10023 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
10024 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
10025 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
10026 #ifndef SQLITE_OMIT_TRACE
10027 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
10028 #endif
10029 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
10030 
10031 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
10032 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
10033 SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
10034 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
10035 
10036 typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
10037 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
10038 
10039 #ifndef SQLITE_OMIT_TRIGGER
10040 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
10041 #endif
10042 
10043 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
10044 ** each VDBE opcode.
10045 **
10046 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
10047 ** comments in VDBE programs that show key decision points in the code
10048 ** generator.
10049 */
10050 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
10051 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
10052 # define VdbeComment(X)  sqlite3VdbeComment X
10053 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
10054 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
10055 # ifdef SQLITE_ENABLE_MODULE_COMMENTS
10056 #   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
10057 # else
10058 #   define VdbeModuleComment(X)
10059 # endif
10060 #else
10061 # define VdbeComment(X)
10062 # define VdbeNoopComment(X)
10063 # define VdbeModuleComment(X)
10064 #endif
10065 
10066 /*
10067 ** The VdbeCoverage macros are used to set a coverage testing point
10068 ** for VDBE branch instructions.  The coverage testing points are line
10069 ** numbers in the sqlite3.c source file.  VDBE branch coverage testing
10070 ** only works with an amalagmation build.  That's ok since a VDBE branch
10071 ** coverage build designed for testing the test suite only.  No application
10072 ** should ever ship with VDBE branch coverage measuring turned on.
10073 **
10074 **    VdbeCoverage(v)                  // Mark the previously coded instruction
10075 **                                     // as a branch
10076 **
10077 **    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
10078 **
10079 **    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
10080 **
10081 **    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
10082 **
10083 ** Every VDBE branch operation must be tagged with one of the macros above.
10084 ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
10085 ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
10086 ** routine in vdbe.c, alerting the developer to the missed tag.
10087 */
10088 #ifdef SQLITE_VDBE_COVERAGE
10089 SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);
10090 # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
10091 # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
10092 # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
10093 # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
10094 # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
10095 #else
10096 # define VdbeCoverage(v)
10097 # define VdbeCoverageIf(v,x)
10098 # define VdbeCoverageAlwaysTaken(v)
10099 # define VdbeCoverageNeverTaken(v)
10100 # define VDBE_OFFSET_LINENO(x) 0
10101 #endif
10102 
10103 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
10104 SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
10105 #else
10106 # define sqlite3VdbeScanStatus(a,b,c,d,e)
10107 #endif
10108 
10109 #endif
10110 
10111 /************** End of vdbe.h ************************************************/
10112 /************** Continuing where we left off in sqliteInt.h ******************/
10113 /************** Include pager.h in the middle of sqliteInt.h *****************/
10114 /************** Begin file pager.h *******************************************/
10115 /*
10116 ** 2001 September 15
10117 **
10118 ** The author disclaims copyright to this source code.  In place of
10119 ** a legal notice, here is a blessing:
10120 **
10121 **    May you do good and not evil.
10122 **    May you find forgiveness for yourself and forgive others.
10123 **    May you share freely, never taking more than you give.
10124 **
10125 *************************************************************************
10126 ** This header file defines the interface that the sqlite page cache
10127 ** subsystem.  The page cache subsystem reads and writes a file a page
10128 ** at a time and provides a journal for rollback.
10129 */
10130 
10131 #ifndef _PAGER_H_
10132 #define _PAGER_H_
10133 
10134 /*
10135 ** Default maximum size for persistent journal files. A negative
10136 ** value means no limit. This value may be overridden using the
10137 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
10138 */
10139 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
10140   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
10141 #endif
10142 
10143 /*
10144 ** The type used to represent a page number.  The first page in a file
10145 ** is called page 1.  0 is used to represent "not a page".
10146 */
10147 typedef u32 Pgno;
10148 
10149 /*
10150 ** Each open file is managed by a separate instance of the "Pager" structure.
10151 */
10152 typedef struct Pager Pager;
10153 
10154 /*
10155 ** Handle type for pages.
10156 */
10157 typedef struct PgHdr DbPage;
10158 
10159 /*
10160 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
10161 ** reserved for working around a windows/posix incompatibility). It is
10162 ** used in the journal to signify that the remainder of the journal file
10163 ** is devoted to storing a master journal name - there are no more pages to
10164 ** roll back. See comments for function writeMasterJournal() in pager.c
10165 ** for details.
10166 */
10167 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
10168 
10169 /*
10170 ** Allowed values for the flags parameter to sqlite3PagerOpen().
10171 **
10172 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
10173 */
10174 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
10175 #define PAGER_MEMORY        0x0002    /* In-memory database */
10176 
10177 /*
10178 ** Valid values for the second argument to sqlite3PagerLockingMode().
10179 */
10180 #define PAGER_LOCKINGMODE_QUERY      -1
10181 #define PAGER_LOCKINGMODE_NORMAL      0
10182 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
10183 
10184 /*
10185 ** Numeric constants that encode the journalmode.
10186 */
10187 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
10188 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
10189 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
10190 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
10191 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
10192 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
10193 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
10194 
10195 /*
10196 ** Flags that make up the mask passed to sqlite3PagerAcquire().
10197 */
10198 #define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
10199 #define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
10200 
10201 /*
10202 ** Flags for sqlite3PagerSetFlags()
10203 */
10204 #define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
10205 #define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
10206 #define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
10207 #define PAGER_SYNCHRONOUS_MASK      0x03  /* Mask for three values above */
10208 #define PAGER_FULLFSYNC             0x04  /* PRAGMA fullfsync=ON */
10209 #define PAGER_CKPT_FULLFSYNC        0x08  /* PRAGMA checkpoint_fullfsync=ON */
10210 #define PAGER_CACHESPILL            0x10  /* PRAGMA cache_spill=ON */
10211 #define PAGER_FLAGS_MASK            0x1c  /* All above except SYNCHRONOUS */
10212 
10213 /*
10214 ** The remainder of this file contains the declarations of the functions
10215 ** that make up the Pager sub-system API. See source code comments for
10216 ** a detailed description of each routine.
10217 */
10218 
10219 /* Open and close a Pager connection. */
10220 SQLITE_PRIVATE int sqlite3PagerOpen(
10221   sqlite3_vfs*,
10222   Pager **ppPager,
10223   const char*,
10224   int,
10225   int,
10226   int,
10227   void(*)(DbPage*)
10228 );
10229 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
10230 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
10231 
10232 /* Functions used to configure a Pager object. */
10233 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
10234 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
10235 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
10236 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
10237 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
10238 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
10239 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
10240 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
10241 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
10242 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
10243 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
10244 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
10245 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
10246 
10247 /* Functions used to obtain and release page references. */
10248 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
10249 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
10250 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
10251 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
10252 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
10253 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
10254 
10255 /* Operations on page references. */
10256 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
10257 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
10258 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
10259 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
10260 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
10261 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
10262 
10263 /* Functions used to manage pager transactions and savepoints. */
10264 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
10265 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
10266 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
10267 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
10268 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
10269 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
10270 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
10271 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
10272 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
10273 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
10274 
10275 #ifndef SQLITE_OMIT_WAL
10276 SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
10277 SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
10278 SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
10279 SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
10280 SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager);
10281 #endif
10282 
10283 #ifdef SQLITE_ENABLE_ZIPVFS
10284 SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
10285 #endif
10286 
10287 /* Functions used to query pager state and configuration. */
10288 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
10289 SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
10290 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
10291 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
10292 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
10293 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
10294 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
10295 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
10296 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
10297 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
10298 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
10299 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
10300 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
10301 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
10302 
10303 /* Functions used to truncate the database file. */
10304 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
10305 
10306 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
10307 
10308 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
10309 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
10310 #endif
10311 
10312 /* Functions to support testing and debugging. */
10313 #if !defined(NDEBUG) || defined(SQLITE_TEST)
10314 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
10315 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
10316 #endif
10317 #ifdef SQLITE_TEST
10318 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
10319 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
10320   void disable_simulated_io_errors(void);
10321   void enable_simulated_io_errors(void);
10322 #else
10323 # define disable_simulated_io_errors()
10324 # define enable_simulated_io_errors()
10325 #endif
10326 
10327 #endif /* _PAGER_H_ */
10328 
10329 /************** End of pager.h ***********************************************/
10330 /************** Continuing where we left off in sqliteInt.h ******************/
10331 /************** Include pcache.h in the middle of sqliteInt.h ****************/
10332 /************** Begin file pcache.h ******************************************/
10333 /*
10334 ** 2008 August 05
10335 **
10336 ** The author disclaims copyright to this source code.  In place of
10337 ** a legal notice, here is a blessing:
10338 **
10339 **    May you do good and not evil.
10340 **    May you find forgiveness for yourself and forgive others.
10341 **    May you share freely, never taking more than you give.
10342 **
10343 *************************************************************************
10344 ** This header file defines the interface that the sqlite page cache
10345 ** subsystem.
10346 */
10347 
10348 #ifndef _PCACHE_H_
10349 
10350 typedef struct PgHdr PgHdr;
10351 typedef struct PCache PCache;
10352 
10353 /*
10354 ** Every page in the cache is controlled by an instance of the following
10355 ** structure.
10356 */
10357 struct PgHdr {
10358   sqlite3_pcache_page *pPage;    /* Pcache object page handle */
10359   void *pData;                   /* Page data */
10360   void *pExtra;                  /* Extra content */
10361   PgHdr *pDirty;                 /* Transient list of dirty pages */
10362   Pager *pPager;                 /* The pager this page is part of */
10363   Pgno pgno;                     /* Page number for this page */
10364 #ifdef SQLITE_CHECK_PAGES
10365   u32 pageHash;                  /* Hash of page content */
10366 #endif
10367   u16 flags;                     /* PGHDR flags defined below */
10368 
10369   /**********************************************************************
10370   ** Elements above are public.  All that follows is private to pcache.c
10371   ** and should not be accessed by other modules.
10372   */
10373   i16 nRef;                      /* Number of users of this page */
10374   PCache *pCache;                /* Cache that owns this page */
10375 
10376   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
10377   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
10378 };
10379 
10380 /* Bit values for PgHdr.flags */
10381 #define PGHDR_DIRTY             0x002  /* Page has changed */
10382 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
10383                                        ** writing this page to the database */
10384 #define PGHDR_NEED_READ         0x008  /* Content is unread */
10385 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
10386 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
10387 
10388 #define PGHDR_MMAP              0x040  /* This is an mmap page object */
10389 
10390 /* Initialize and shutdown the page cache subsystem */
10391 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
10392 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
10393 
10394 /* Page cache buffer management:
10395 ** These routines implement SQLITE_CONFIG_PAGECACHE.
10396 */
10397 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
10398 
10399 /* Create a new pager cache.
10400 ** Under memory stress, invoke xStress to try to make pages clean.
10401 ** Only clean and unpinned pages can be reclaimed.
10402 */
10403 SQLITE_PRIVATE int sqlite3PcacheOpen(
10404   int szPage,                    /* Size of every page */
10405   int szExtra,                   /* Extra space associated with each page */
10406   int bPurgeable,                /* True if pages are on backing store */
10407   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
10408   void *pStress,                 /* Argument to xStress */
10409   PCache *pToInit                /* Preallocated space for the PCache */
10410 );
10411 
10412 /* Modify the page-size after the cache has been created. */
10413 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
10414 
10415 /* Return the size in bytes of a PCache object.  Used to preallocate
10416 ** storage space.
10417 */
10418 SQLITE_PRIVATE int sqlite3PcacheSize(void);
10419 
10420 /* One release per successful fetch.  Page is pinned until released.
10421 ** Reference counted.
10422 */
10423 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
10424 SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
10425 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
10426 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
10427 
10428 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
10429 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
10430 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
10431 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
10432 
10433 /* Change a page number.  Used by incr-vacuum. */
10434 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
10435 
10436 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
10437 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
10438 
10439 /* Get a list of all dirty pages in the cache, sorted by page number */
10440 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
10441 
10442 /* Reset and close the cache object */
10443 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
10444 
10445 /* Clear flags from pages of the page cache */
10446 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
10447 
10448 /* Discard the contents of the cache */
10449 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
10450 
10451 /* Return the total number of outstanding page references */
10452 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
10453 
10454 /* Increment the reference count of an existing page */
10455 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
10456 
10457 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
10458 
10459 /* Return the total number of pages stored in the cache */
10460 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
10461 
10462 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
10463 /* Iterate through all dirty pages currently stored in the cache. This
10464 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
10465 ** library is built.
10466 */
10467 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
10468 #endif
10469 
10470 /* Set and get the suggested cache-size for the specified pager-cache.
10471 **
10472 ** If no global maximum is configured, then the system attempts to limit
10473 ** the total number of pages cached by purgeable pager-caches to the sum
10474 ** of the suggested cache-sizes.
10475 */
10476 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
10477 #ifdef SQLITE_TEST
10478 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
10479 #endif
10480 
10481 /* Free up as much memory as possible from the page cache */
10482 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
10483 
10484 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
10485 /* Try to return memory used by the pcache module to the main memory heap */
10486 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
10487 #endif
10488 
10489 #ifdef SQLITE_TEST
10490 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
10491 #endif
10492 
10493 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
10494 
10495 /* Return the header size */
10496 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
10497 SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
10498 
10499 #endif /* _PCACHE_H_ */
10500 
10501 /************** End of pcache.h **********************************************/
10502 /************** Continuing where we left off in sqliteInt.h ******************/
10503 
10504 /************** Include os.h in the middle of sqliteInt.h ********************/
10505 /************** Begin file os.h **********************************************/
10506 /*
10507 ** 2001 September 16
10508 **
10509 ** The author disclaims copyright to this source code.  In place of
10510 ** a legal notice, here is a blessing:
10511 **
10512 **    May you do good and not evil.
10513 **    May you find forgiveness for yourself and forgive others.
10514 **    May you share freely, never taking more than you give.
10515 **
10516 ******************************************************************************
10517 **
10518 ** This header file (together with is companion C source-code file
10519 ** "os.c") attempt to abstract the underlying operating system so that
10520 ** the SQLite library will work on both POSIX and windows systems.
10521 **
10522 ** This header file is #include-ed by sqliteInt.h and thus ends up
10523 ** being included by every source file.
10524 */
10525 #ifndef _SQLITE_OS_H_
10526 #define _SQLITE_OS_H_
10527 
10528 /*
10529 ** Attempt to automatically detect the operating system and setup the
10530 ** necessary pre-processor macros for it.
10531 */
10532 /************** Include os_setup.h in the middle of os.h *********************/
10533 /************** Begin file os_setup.h ****************************************/
10534 /*
10535 ** 2013 November 25
10536 **
10537 ** The author disclaims copyright to this source code.  In place of
10538 ** a legal notice, here is a blessing:
10539 **
10540 **    May you do good and not evil.
10541 **    May you find forgiveness for yourself and forgive others.
10542 **    May you share freely, never taking more than you give.
10543 **
10544 ******************************************************************************
10545 **
10546 ** This file contains pre-processor directives related to operating system
10547 ** detection and/or setup.
10548 */
10549 #ifndef _OS_SETUP_H_
10550 #define _OS_SETUP_H_
10551 
10552 /*
10553 ** Figure out if we are dealing with Unix, Windows, or some other operating
10554 ** system.
10555 **
10556 ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
10557 ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0.  One of
10558 ** the three will be 1.  The other two will be 0.
10559 */
10560 #if defined(SQLITE_OS_OTHER)
10561 #  if SQLITE_OS_OTHER==1
10562 #    undef SQLITE_OS_UNIX
10563 #    define SQLITE_OS_UNIX 0
10564 #    undef SQLITE_OS_WIN
10565 #    define SQLITE_OS_WIN 0
10566 #  else
10567 #    undef SQLITE_OS_OTHER
10568 #  endif
10569 #endif
10570 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
10571 #  define SQLITE_OS_OTHER 0
10572 #  ifndef SQLITE_OS_WIN
10573 #    if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
10574         defined(__MINGW32__) || defined(__BORLANDC__)
10575 #      define SQLITE_OS_WIN 1
10576 #      define SQLITE_OS_UNIX 0
10577 #    else
10578 #      define SQLITE_OS_WIN 0
10579 #      define SQLITE_OS_UNIX 1
10580 #    endif
10581 #  else
10582 #    define SQLITE_OS_UNIX 0
10583 #  endif
10584 #else
10585 #  ifndef SQLITE_OS_WIN
10586 #    define SQLITE_OS_WIN 0
10587 #  endif
10588 #endif
10589 
10590 #endif /* _OS_SETUP_H_ */
10591 
10592 /************** End of os_setup.h ********************************************/
10593 /************** Continuing where we left off in os.h *************************/
10594 
10595 /* If the SET_FULLSYNC macro is not defined above, then make it
10596 ** a no-op
10597 */
10598 #ifndef SET_FULLSYNC
10599 # define SET_FULLSYNC(x,y)
10600 #endif
10601 
10602 /*
10603 ** The default size of a disk sector
10604 */
10605 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
10606 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
10607 #endif
10608 
10609 /*
10610 ** Temporary files are named starting with this prefix followed by 16 random
10611 ** alphanumeric characters, and no file extension. They are stored in the
10612 ** OS's standard temporary file directory, and are deleted prior to exit.
10613 ** If sqlite is being embedded in another program, you may wish to change the
10614 ** prefix to reflect your program's name, so that if your program exits
10615 ** prematurely, old temporary files can be easily identified. This can be done
10616 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
10617 **
10618 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
10619 ** Mcafee started using SQLite in their anti-virus product and it
10620 ** started putting files with the "sqlite" name in the c:/temp folder.
10621 ** This annoyed many windows users.  Those users would then do a
10622 ** Google search for "sqlite", find the telephone numbers of the
10623 ** developers and call to wake them up at night and complain.
10624 ** For this reason, the default name prefix is changed to be "sqlite"
10625 ** spelled backwards.  So the temp files are still identified, but
10626 ** anybody smart enough to figure out the code is also likely smart
10627 ** enough to know that calling the developer will not help get rid
10628 ** of the file.
10629 */
10630 #ifndef SQLITE_TEMP_FILE_PREFIX
10631 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
10632 #endif
10633 
10634 /*
10635 ** The following values may be passed as the second argument to
10636 ** sqlite3OsLock(). The various locks exhibit the following semantics:
10637 **
10638 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
10639 ** RESERVED:  A single process may hold a RESERVED lock on a file at
10640 **            any time. Other processes may hold and obtain new SHARED locks.
10641 ** PENDING:   A single process may hold a PENDING lock on a file at
10642 **            any one time. Existing SHARED locks may persist, but no new
10643 **            SHARED locks may be obtained by other processes.
10644 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
10645 **
10646 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
10647 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
10648 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
10649 ** sqlite3OsLock().
10650 */
10651 #define NO_LOCK         0
10652 #define SHARED_LOCK     1
10653 #define RESERVED_LOCK   2
10654 #define PENDING_LOCK    3
10655 #define EXCLUSIVE_LOCK  4
10656 
10657 /*
10658 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
10659 **
10660 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
10661 ** those functions are not available.  So we use only LockFile() and
10662 ** UnlockFile().
10663 **
10664 ** LockFile() prevents not just writing but also reading by other processes.
10665 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
10666 ** byte out of a specific range of bytes. The lock byte is obtained at
10667 ** random so two separate readers can probably access the file at the
10668 ** same time, unless they are unlucky and choose the same lock byte.
10669 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
10670 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
10671 ** a single byte of the file that is designated as the reserved lock byte.
10672 ** A PENDING_LOCK is obtained by locking a designated byte different from
10673 ** the RESERVED_LOCK byte.
10674 **
10675 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
10676 ** which means we can use reader/writer locks.  When reader/writer locks
10677 ** are used, the lock is placed on the same range of bytes that is used
10678 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
10679 ** will support two or more Win95 readers or two or more WinNT readers.
10680 ** But a single Win95 reader will lock out all WinNT readers and a single
10681 ** WinNT reader will lock out all other Win95 readers.
10682 **
10683 ** The following #defines specify the range of bytes used for locking.
10684 ** SHARED_SIZE is the number of bytes available in the pool from which
10685 ** a random byte is selected for a shared lock.  The pool of bytes for
10686 ** shared locks begins at SHARED_FIRST.
10687 **
10688 ** The same locking strategy and
10689 ** byte ranges are used for Unix.  This leaves open the possibility of having
10690 ** clients on win95, winNT, and unix all talking to the same shared file
10691 ** and all locking correctly.  To do so would require that samba (or whatever
10692 ** tool is being used for file sharing) implements locks correctly between
10693 ** windows and unix.  I'm guessing that isn't likely to happen, but by
10694 ** using the same locking range we are at least open to the possibility.
10695 **
10696 ** Locking in windows is manditory.  For this reason, we cannot store
10697 ** actual data in the bytes used for locking.  The pager never allocates
10698 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
10699 ** that all locks will fit on a single page even at the minimum page size.
10700 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
10701 ** is set high so that we don't have to allocate an unused page except
10702 ** for very large databases.  But one should test the page skipping logic
10703 ** by setting PENDING_BYTE low and running the entire regression suite.
10704 **
10705 ** Changing the value of PENDING_BYTE results in a subtly incompatible
10706 ** file format.  Depending on how it is changed, you might not notice
10707 ** the incompatibility right away, even running a full regression test.
10708 ** The default location of PENDING_BYTE is the first byte past the
10709 ** 1GB boundary.
10710 **
10711 */
10712 #ifdef SQLITE_OMIT_WSD
10713 # define PENDING_BYTE     (0x40000000)
10714 #else
10715 # define PENDING_BYTE      sqlite3PendingByte
10716 #endif
10717 #define RESERVED_BYTE     (PENDING_BYTE+1)
10718 #define SHARED_FIRST      (PENDING_BYTE+2)
10719 #define SHARED_SIZE       510
10720 
10721 /*
10722 ** Wrapper around OS specific sqlite3_os_init() function.
10723 */
10724 SQLITE_PRIVATE int sqlite3OsInit(void);
10725 
10726 /*
10727 ** Functions for accessing sqlite3_file methods
10728 */
10729 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
10730 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
10731 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
10732 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
10733 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
10734 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
10735 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
10736 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
10737 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
10738 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
10739 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
10740 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
10741 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
10742 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
10743 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
10744 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
10745 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
10746 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
10747 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
10748 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
10749 
10750 
10751 /*
10752 ** Functions for accessing sqlite3_vfs methods
10753 */
10754 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
10755 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
10756 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
10757 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
10758 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10759 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
10760 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
10761 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
10762 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
10763 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
10764 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
10765 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
10766 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
10767 
10768 /*
10769 ** Convenience functions for opening and closing files using
10770 ** sqlite3_malloc() to obtain space for the file-handle structure.
10771 */
10772 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
10773 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
10774 
10775 #endif /* _SQLITE_OS_H_ */
10776 
10777 /************** End of os.h **************************************************/
10778 /************** Continuing where we left off in sqliteInt.h ******************/
10779 /************** Include mutex.h in the middle of sqliteInt.h *****************/
10780 /************** Begin file mutex.h *******************************************/
10781 /*
10782 ** 2007 August 28
10783 **
10784 ** The author disclaims copyright to this source code.  In place of
10785 ** a legal notice, here is a blessing:
10786 **
10787 **    May you do good and not evil.
10788 **    May you find forgiveness for yourself and forgive others.
10789 **    May you share freely, never taking more than you give.
10790 **
10791 *************************************************************************
10792 **
10793 ** This file contains the common header for all mutex implementations.
10794 ** The sqliteInt.h header #includes this file so that it is available
10795 ** to all source files.  We break it out in an effort to keep the code
10796 ** better organized.
10797 **
10798 ** NOTE:  source files should *not* #include this header file directly.
10799 ** Source files should #include the sqliteInt.h file and let that file
10800 ** include this one indirectly.
10801 */
10802 
10803 
10804 /*
10805 ** Figure out what version of the code to use.  The choices are
10806 **
10807 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
10808 **                             mutexes implementation cannot be overridden
10809 **                             at start-time.
10810 **
10811 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
10812 **                             mutual exclusion is provided.  But this
10813 **                             implementation can be overridden at
10814 **                             start-time.
10815 **
10816 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
10817 **
10818 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
10819 */
10820 #if !SQLITE_THREADSAFE
10821 # define SQLITE_MUTEX_OMIT
10822 #endif
10823 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
10824 #  if SQLITE_OS_UNIX
10825 #    define SQLITE_MUTEX_PTHREADS
10826 #  elif SQLITE_OS_WIN
10827 #    define SQLITE_MUTEX_W32
10828 #  else
10829 #    define SQLITE_MUTEX_NOOP
10830 #  endif
10831 #endif
10832 
10833 #ifdef SQLITE_MUTEX_OMIT
10834 /*
10835 ** If this is a no-op implementation, implement everything as macros.
10836 */
10837 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
10838 #define sqlite3_mutex_free(X)
10839 #define sqlite3_mutex_enter(X)
10840 #define sqlite3_mutex_try(X)      SQLITE_OK
10841 #define sqlite3_mutex_leave(X)
10842 #define sqlite3_mutex_held(X)     ((void)(X),1)
10843 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
10844 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
10845 #define sqlite3MutexInit()        SQLITE_OK
10846 #define sqlite3MutexEnd()
10847 #define MUTEX_LOGIC(X)
10848 #else
10849 #define MUTEX_LOGIC(X)            X
10850 #endif /* defined(SQLITE_MUTEX_OMIT) */
10851 
10852 /************** End of mutex.h ***********************************************/
10853 /************** Continuing where we left off in sqliteInt.h ******************/
10854 
10855 
10856 /*
10857 ** Each database file to be accessed by the system is an instance
10858 ** of the following structure.  There are normally two of these structures
10859 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
10860 ** aDb[1] is the database file used to hold temporary tables.  Additional
10861 ** databases may be attached.
10862 */
10863 struct Db {
10864   char *zName;         /* Name of this database */
10865   Btree *pBt;          /* The B*Tree structure for this database file */
10866   u8 safety_level;     /* How aggressive at syncing data to disk */
10867   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
10868 };
10869 
10870 /*
10871 ** An instance of the following structure stores a database schema.
10872 **
10873 ** Most Schema objects are associated with a Btree.  The exception is
10874 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
10875 ** In shared cache mode, a single Schema object can be shared by multiple
10876 ** Btrees that refer to the same underlying BtShared object.
10877 **
10878 ** Schema objects are automatically deallocated when the last Btree that
10879 ** references them is destroyed.   The TEMP Schema is manually freed by
10880 ** sqlite3_close().
10881 *
10882 ** A thread must be holding a mutex on the corresponding Btree in order
10883 ** to access Schema content.  This implies that the thread must also be
10884 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
10885 ** For a TEMP Schema, only the connection mutex is required.
10886 */
10887 struct Schema {
10888   int schema_cookie;   /* Database schema version number for this file */
10889   int iGeneration;     /* Generation counter.  Incremented with each change */
10890   Hash tblHash;        /* All tables indexed by name */
10891   Hash idxHash;        /* All (named) indices indexed by name */
10892   Hash trigHash;       /* All triggers indexed by name */
10893   Hash fkeyHash;       /* All foreign keys by referenced table name */
10894   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
10895   u8 file_format;      /* Schema format version for this file */
10896   u8 enc;              /* Text encoding used by this database */
10897   u16 schemaFlags;     /* Flags associated with this schema */
10898   int cache_size;      /* Number of pages to use in the cache */
10899 };
10900 
10901 /*
10902 ** These macros can be used to test, set, or clear bits in the
10903 ** Db.pSchema->flags field.
10904 */
10905 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
10906 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
10907 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
10908 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
10909 
10910 /*
10911 ** Allowed values for the DB.pSchema->flags field.
10912 **
10913 ** The DB_SchemaLoaded flag is set after the database schema has been
10914 ** read into internal hash tables.
10915 **
10916 ** DB_UnresetViews means that one or more views have column names that
10917 ** have been filled out.  If the schema changes, these column names might
10918 ** changes and so the view will need to be reset.
10919 */
10920 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
10921 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
10922 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
10923 
10924 /*
10925 ** The number of different kinds of things that can be limited
10926 ** using the sqlite3_limit() interface.
10927 */
10928 #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
10929 
10930 /*
10931 ** Lookaside malloc is a set of fixed-size buffers that can be used
10932 ** to satisfy small transient memory allocation requests for objects
10933 ** associated with a particular database connection.  The use of
10934 ** lookaside malloc provides a significant performance enhancement
10935 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
10936 ** SQL statements.
10937 **
10938 ** The Lookaside structure holds configuration information about the
10939 ** lookaside malloc subsystem.  Each available memory allocation in
10940 ** the lookaside subsystem is stored on a linked list of LookasideSlot
10941 ** objects.
10942 **
10943 ** Lookaside allocations are only allowed for objects that are associated
10944 ** with a particular database connection.  Hence, schema information cannot
10945 ** be stored in lookaside because in shared cache mode the schema information
10946 ** is shared by multiple database connections.  Therefore, while parsing
10947 ** schema information, the Lookaside.bEnabled flag is cleared so that
10948 ** lookaside allocations are not used to construct the schema objects.
10949 */
10950 struct Lookaside {
10951   u16 sz;                 /* Size of each buffer in bytes */
10952   u8 bEnabled;            /* False to disable new lookaside allocations */
10953   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
10954   int nOut;               /* Number of buffers currently checked out */
10955   int mxOut;              /* Highwater mark for nOut */
10956   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
10957   LookasideSlot *pFree;   /* List of available buffers */
10958   void *pStart;           /* First byte of available memory space */
10959   void *pEnd;             /* First byte past end of available space */
10960 };
10961 struct LookasideSlot {
10962   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
10963 };
10964 
10965 /*
10966 ** A hash table for function definitions.
10967 **
10968 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
10969 ** Collisions are on the FuncDef.pHash chain.
10970 */
10971 struct FuncDefHash {
10972   FuncDef *a[23];       /* Hash table for functions */
10973 };
10974 
10975 #ifdef SQLITE_USER_AUTHENTICATION
10976 /*
10977 ** Information held in the "sqlite3" database connection object and used
10978 ** to manage user authentication.
10979 */
10980 typedef struct sqlite3_userauth sqlite3_userauth;
10981 struct sqlite3_userauth {
10982   u8 authLevel;                 /* Current authentication level */
10983   int nAuthPW;                  /* Size of the zAuthPW in bytes */
10984   char *zAuthPW;                /* Password used to authenticate */
10985   char *zAuthUser;              /* User name used to authenticate */
10986 };
10987 
10988 /* Allowed values for sqlite3_userauth.authLevel */
10989 #define UAUTH_Unknown     0     /* Authentication not yet checked */
10990 #define UAUTH_Fail        1     /* User authentication failed */
10991 #define UAUTH_User        2     /* Authenticated as a normal user */
10992 #define UAUTH_Admin       3     /* Authenticated as an administrator */
10993 
10994 /* Functions used only by user authorization logic */
10995 SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
10996 SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
10997 SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
10998 SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
10999 
11000 #endif /* SQLITE_USER_AUTHENTICATION */
11001 
11002 /*
11003 ** typedef for the authorization callback function.
11004 */
11005 #ifdef SQLITE_USER_AUTHENTICATION
11006   typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
11007                                const char*, const char*);
11008 #else
11009   typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
11010                                const char*);
11011 #endif
11012 
11013 
11014 /*
11015 ** Each database connection is an instance of the following structure.
11016 */
11017 struct sqlite3 {
11018   sqlite3_vfs *pVfs;            /* OS Interface */
11019   struct Vdbe *pVdbe;           /* List of active virtual machines */
11020   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
11021   sqlite3_mutex *mutex;         /* Connection mutex */
11022   Db *aDb;                      /* All backends */
11023   int nDb;                      /* Number of backends currently in use */
11024   int flags;                    /* Miscellaneous flags. See below */
11025   i64 lastRowid;                /* ROWID of most recent insert (see above) */
11026   i64 szMmap;                   /* Default mmap_size setting */
11027   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
11028   int errCode;                  /* Most recent error code (SQLITE_*) */
11029   int errMask;                  /* & result codes with this before returning */
11030   u16 dbOptFlags;               /* Flags to enable/disable optimizations */
11031   u8 enc;                       /* Text encoding */
11032   u8 autoCommit;                /* The auto-commit flag. */
11033   u8 temp_store;                /* 1: file 2: memory 0: default */
11034   u8 mallocFailed;              /* True if we have seen a malloc failure */
11035   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
11036   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
11037   u8 suppressErr;               /* Do not issue error messages if true */
11038   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
11039   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
11040   int nextPagesize;             /* Pagesize after VACUUM if >0 */
11041   u32 magic;                    /* Magic number for detect library misuse */
11042   int nChange;                  /* Value returned by sqlite3_changes() */
11043   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
11044   int aLimit[SQLITE_N_LIMIT];   /* Limits */
11045   int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
11046   struct sqlite3InitInfo {      /* Information used during initialization */
11047     int newTnum;                /* Rootpage of table being initialized */
11048     u8 iDb;                     /* Which db file is being initialized */
11049     u8 busy;                    /* TRUE if currently initializing */
11050     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
11051     u8 imposterTable;           /* Building an imposter table */
11052   } init;
11053   int nVdbeActive;              /* Number of VDBEs currently running */
11054   int nVdbeRead;                /* Number of active VDBEs that read or write */
11055   int nVdbeWrite;               /* Number of active VDBEs that read and write */
11056   int nVdbeExec;                /* Number of nested calls to VdbeExec() */
11057   int nVDestroy;                /* Number of active OP_VDestroy operations */
11058   int nExtension;               /* Number of loaded extensions */
11059   void **aExtension;            /* Array of shared library handles */
11060   void (*xTrace)(void*,const char*);        /* Trace function */
11061   void *pTraceArg;                          /* Argument to the trace function */
11062   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
11063   void *pProfileArg;                        /* Argument to profile function */
11064   void *pCommitArg;                 /* Argument to xCommitCallback() */
11065   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
11066   void *pRollbackArg;               /* Argument to xRollbackCallback() */
11067   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
11068   void *pUpdateArg;
11069   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
11070 #ifndef SQLITE_OMIT_WAL
11071   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
11072   void *pWalArg;
11073 #endif
11074   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
11075   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
11076   void *pCollNeededArg;
11077   sqlite3_value *pErr;          /* Most recent error message */
11078   union {
11079     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
11080     double notUsed1;            /* Spacer */
11081   } u1;
11082   Lookaside lookaside;          /* Lookaside malloc configuration */
11083 #ifndef SQLITE_OMIT_AUTHORIZATION
11084   sqlite3_xauth xAuth;          /* Access authorization function */
11085   void *pAuthArg;               /* 1st argument to the access auth function */
11086 #endif
11087 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
11088   int (*xProgress)(void *);     /* The progress callback */
11089   void *pProgressArg;           /* Argument to the progress callback */
11090   unsigned nProgressOps;        /* Number of opcodes for progress callback */
11091 #endif
11092 #ifndef SQLITE_OMIT_VIRTUALTABLE
11093   int nVTrans;                  /* Allocated size of aVTrans */
11094   Hash aModule;                 /* populated by sqlite3_create_module() */
11095   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
11096   VTable **aVTrans;             /* Virtual tables with open transactions */
11097   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
11098 #endif
11099   FuncDefHash aFunc;            /* Hash table of connection functions */
11100   Hash aCollSeq;                /* All collating sequences */
11101   BusyHandler busyHandler;      /* Busy callback */
11102   Db aDbStatic[2];              /* Static space for the 2 default backends */
11103   Savepoint *pSavepoint;        /* List of active savepoints */
11104   int busyTimeout;              /* Busy handler timeout, in msec */
11105   int nSavepoint;               /* Number of non-transaction savepoints */
11106   int nStatement;               /* Number of nested statement-transactions  */
11107   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
11108   i64 nDeferredImmCons;         /* Net deferred immediate constraints */
11109   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
11110 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11111   /* The following variables are all protected by the STATIC_MASTER
11112   ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
11113   **
11114   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
11115   ** unlock so that it can proceed.
11116   **
11117   ** When X.pBlockingConnection==Y, that means that something that X tried
11118   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
11119   ** held by Y.
11120   */
11121   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
11122   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
11123   void *pUnlockArg;                     /* Argument to xUnlockNotify */
11124   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
11125   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
11126 #endif
11127 #ifdef SQLITE_USER_AUTHENTICATION
11128   sqlite3_userauth auth;        /* User authentication information */
11129 #endif
11130 };
11131 
11132 /*
11133 ** A macro to discover the encoding of a database.
11134 */
11135 #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
11136 #define ENC(db)        ((db)->enc)
11137 
11138 /*
11139 ** Possible values for the sqlite3.flags.
11140 */
11141 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
11142 #define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
11143 #define SQLITE_FullFSync      0x00000004  /* Use full fsync on the backend */
11144 #define SQLITE_CkptFullFSync  0x00000008  /* Use full fsync for checkpoint */
11145 #define SQLITE_CacheSpill     0x00000010  /* OK to spill pager cache */
11146 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
11147 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
11148 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
11149                                           /*   DELETE, or UPDATE and return */
11150                                           /*   the count using a callback. */
11151 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
11152                                           /*   result set is empty */
11153 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
11154 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
11155 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
11156 #define SQLITE_VdbeAddopTrace 0x00001000  /* Trace sqlite3VdbeAddOp() calls */
11157 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
11158 #define SQLITE_ReadUncommitted 0x0004000  /* For shared-cache mode */
11159 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
11160 #define SQLITE_RecoveryMode   0x00010000  /* Ignore schema errors */
11161 #define SQLITE_ReverseOrder   0x00020000  /* Reverse unordered SELECTs */
11162 #define SQLITE_RecTriggers    0x00040000  /* Enable recursive triggers */
11163 #define SQLITE_ForeignKeys    0x00080000  /* Enforce foreign key constraints  */
11164 #define SQLITE_AutoIndex      0x00100000  /* Enable automatic indexes */
11165 #define SQLITE_PreferBuiltin  0x00200000  /* Preference to built-in funcs */
11166 #define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
11167 #define SQLITE_EnableTrigger  0x00800000  /* True to enable triggers */
11168 #define SQLITE_DeferFKs       0x01000000  /* Defer all FK constraints */
11169 #define SQLITE_QueryOnly      0x02000000  /* Disable database changes */
11170 #define SQLITE_VdbeEQP        0x04000000  /* Debug EXPLAIN QUERY PLAN */
11171 #define SQLITE_Vacuum         0x08000000  /* Currently in a VACUUM */
11172 
11173 
11174 /*
11175 ** Bits of the sqlite3.dbOptFlags field that are used by the
11176 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
11177 ** selectively disable various optimizations.
11178 */
11179 #define SQLITE_QueryFlattener 0x0001   /* Query flattening */
11180 #define SQLITE_ColumnCache    0x0002   /* Column cache */
11181 #define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
11182 #define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
11183 /*                not used    0x0010   // Was: SQLITE_IdxRealAsInt */
11184 #define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
11185 #define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
11186 #define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
11187 #define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
11188 #define SQLITE_Transitive     0x0200   /* Transitive constraints */
11189 #define SQLITE_OmitNoopJoin   0x0400   /* Omit unused tables in joins */
11190 #define SQLITE_Stat34         0x0800   /* Use STAT3 or STAT4 data */
11191 #define SQLITE_AllOpts        0xffff   /* All optimizations */
11192 
11193 /*
11194 ** Macros for testing whether or not optimizations are enabled or disabled.
11195 */
11196 #ifndef SQLITE_OMIT_BUILTIN_TEST
11197 #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
11198 #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
11199 #else
11200 #define OptimizationDisabled(db, mask)  0
11201 #define OptimizationEnabled(db, mask)   1
11202 #endif
11203 
11204 /*
11205 ** Return true if it OK to factor constant expressions into the initialization
11206 ** code. The argument is a Parse object for the code generator.
11207 */
11208 #define ConstFactorOk(P) ((P)->okConstFactor)
11209 
11210 /*
11211 ** Possible values for the sqlite.magic field.
11212 ** The numbers are obtained at random and have no special meaning, other
11213 ** than being distinct from one another.
11214 */
11215 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
11216 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
11217 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
11218 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
11219 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
11220 #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
11221 
11222 /*
11223 ** Each SQL function is defined by an instance of the following
11224 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
11225 ** hash table.  When multiple functions have the same name, the hash table
11226 ** points to a linked list of these structures.
11227 */
11228 struct FuncDef {
11229   i16 nArg;            /* Number of arguments.  -1 means unlimited */
11230   u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
11231   void *pUserData;     /* User data parameter */
11232   FuncDef *pNext;      /* Next function with same name */
11233   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
11234   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
11235   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
11236   char *zName;         /* SQL name of the function. */
11237   FuncDef *pHash;      /* Next with a different name but the same hash */
11238   FuncDestructor *pDestructor;   /* Reference counted destructor function */
11239 };
11240 
11241 /*
11242 ** This structure encapsulates a user-function destructor callback (as
11243 ** configured using create_function_v2()) and a reference counter. When
11244 ** create_function_v2() is called to create a function with a destructor,
11245 ** a single object of this type is allocated. FuncDestructor.nRef is set to
11246 ** the number of FuncDef objects created (either 1 or 3, depending on whether
11247 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
11248 ** member of each of the new FuncDef objects is set to point to the allocated
11249 ** FuncDestructor.
11250 **
11251 ** Thereafter, when one of the FuncDef objects is deleted, the reference
11252 ** count on this object is decremented. When it reaches 0, the destructor
11253 ** is invoked and the FuncDestructor structure freed.
11254 */
11255 struct FuncDestructor {
11256   int nRef;
11257   void (*xDestroy)(void *);
11258   void *pUserData;
11259 };
11260 
11261 /*
11262 ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
11263 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
11264 ** are assert() statements in the code to verify this.
11265 */
11266 #define SQLITE_FUNC_ENCMASK  0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
11267 #define SQLITE_FUNC_LIKE     0x004 /* Candidate for the LIKE optimization */
11268 #define SQLITE_FUNC_CASE     0x008 /* Case-sensitive LIKE-type function */
11269 #define SQLITE_FUNC_EPHEM    0x010 /* Ephemeral.  Delete with VDBE */
11270 #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
11271 #define SQLITE_FUNC_LENGTH   0x040 /* Built-in length() function */
11272 #define SQLITE_FUNC_TYPEOF   0x080 /* Built-in typeof() function */
11273 #define SQLITE_FUNC_COUNT    0x100 /* Built-in count(*) aggregate */
11274 #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
11275 #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
11276 #define SQLITE_FUNC_CONSTANT 0x800 /* Constant inputs give a constant output */
11277 #define SQLITE_FUNC_MINMAX  0x1000 /* True for min() and max() aggregates */
11278 
11279 /*
11280 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
11281 ** used to create the initializers for the FuncDef structures.
11282 **
11283 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
11284 **     Used to create a scalar function definition of a function zName
11285 **     implemented by C function xFunc that accepts nArg arguments. The
11286 **     value passed as iArg is cast to a (void*) and made available
11287 **     as the user-data (sqlite3_user_data()) for the function. If
11288 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
11289 **
11290 **   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
11291 **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
11292 **
11293 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
11294 **     Used to create an aggregate function definition implemented by
11295 **     the C functions xStep and xFinal. The first four parameters
11296 **     are interpreted in the same way as the first 4 parameters to
11297 **     FUNCTION().
11298 **
11299 **   LIKEFUNC(zName, nArg, pArg, flags)
11300 **     Used to create a scalar function definition of a function zName
11301 **     that accepts nArg arguments and is implemented by a call to C
11302 **     function likeFunc. Argument pArg is cast to a (void *) and made
11303 **     available as the function user-data (sqlite3_user_data()). The
11304 **     FuncDef.flags variable is set to the value passed as the flags
11305 **     parameter.
11306 */
11307 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
11308   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
11309    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
11310 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
11311   {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
11312    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
11313 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
11314   {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
11315    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
11316 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
11317   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
11318    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
11319 #define LIKEFUNC(zName, nArg, arg, flags) \
11320   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
11321    (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
11322 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
11323   {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
11324    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
11325 #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
11326   {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
11327    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
11328 
11329 /*
11330 ** All current savepoints are stored in a linked list starting at
11331 ** sqlite3.pSavepoint. The first element in the list is the most recently
11332 ** opened savepoint. Savepoints are added to the list by the vdbe
11333 ** OP_Savepoint instruction.
11334 */
11335 struct Savepoint {
11336   char *zName;                        /* Savepoint name (nul-terminated) */
11337   i64 nDeferredCons;                  /* Number of deferred fk violations */
11338   i64 nDeferredImmCons;               /* Number of deferred imm fk. */
11339   Savepoint *pNext;                   /* Parent savepoint (if any) */
11340 };
11341 
11342 /*
11343 ** The following are used as the second parameter to sqlite3Savepoint(),
11344 ** and as the P1 argument to the OP_Savepoint instruction.
11345 */
11346 #define SAVEPOINT_BEGIN      0
11347 #define SAVEPOINT_RELEASE    1
11348 #define SAVEPOINT_ROLLBACK   2
11349 
11350 
11351 /*
11352 ** Each SQLite module (virtual table definition) is defined by an
11353 ** instance of the following structure, stored in the sqlite3.aModule
11354 ** hash table.
11355 */
11356 struct Module {
11357   const sqlite3_module *pModule;       /* Callback pointers */
11358   const char *zName;                   /* Name passed to create_module() */
11359   void *pAux;                          /* pAux passed to create_module() */
11360   void (*xDestroy)(void *);            /* Module destructor function */
11361 };
11362 
11363 /*
11364 ** information about each column of an SQL table is held in an instance
11365 ** of this structure.
11366 */
11367 struct Column {
11368   char *zName;     /* Name of this column */
11369   Expr *pDflt;     /* Default value of this column */
11370   char *zDflt;     /* Original text of the default value */
11371   char *zType;     /* Data type for this column */
11372   char *zColl;     /* Collating sequence.  If NULL, use the default */
11373   u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
11374   char affinity;   /* One of the SQLITE_AFF_... values */
11375   u8 szEst;        /* Estimated size of this column.  INT==1 */
11376   u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
11377 };
11378 
11379 /* Allowed values for Column.colFlags:
11380 */
11381 #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
11382 #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
11383 
11384 /*
11385 ** A "Collating Sequence" is defined by an instance of the following
11386 ** structure. Conceptually, a collating sequence consists of a name and
11387 ** a comparison routine that defines the order of that sequence.
11388 **
11389 ** If CollSeq.xCmp is NULL, it means that the
11390 ** collating sequence is undefined.  Indices built on an undefined
11391 ** collating sequence may not be read or written.
11392 */
11393 struct CollSeq {
11394   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
11395   u8 enc;               /* Text encoding handled by xCmp() */
11396   void *pUser;          /* First argument to xCmp() */
11397   int (*xCmp)(void*,int, const void*, int, const void*);
11398   void (*xDel)(void*);  /* Destructor for pUser */
11399 };
11400 
11401 /*
11402 ** A sort order can be either ASC or DESC.
11403 */
11404 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
11405 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
11406 
11407 /*
11408 ** Column affinity types.
11409 **
11410 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
11411 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
11412 ** the speed a little by numbering the values consecutively.
11413 **
11414 ** But rather than start with 0 or 1, we begin with 'A'.  That way,
11415 ** when multiple affinity types are concatenated into a string and
11416 ** used as the P4 operand, they will be more readable.
11417 **
11418 ** Note also that the numeric types are grouped together so that testing
11419 ** for a numeric type is a single comparison.  And the NONE type is first.
11420 */
11421 #define SQLITE_AFF_NONE     'A'
11422 #define SQLITE_AFF_TEXT     'B'
11423 #define SQLITE_AFF_NUMERIC  'C'
11424 #define SQLITE_AFF_INTEGER  'D'
11425 #define SQLITE_AFF_REAL     'E'
11426 
11427 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
11428 
11429 /*
11430 ** The SQLITE_AFF_MASK values masks off the significant bits of an
11431 ** affinity value.
11432 */
11433 #define SQLITE_AFF_MASK     0x47
11434 
11435 /*
11436 ** Additional bit values that can be ORed with an affinity without
11437 ** changing the affinity.
11438 **
11439 ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
11440 ** It causes an assert() to fire if either operand to a comparison
11441 ** operator is NULL.  It is added to certain comparison operators to
11442 ** prove that the operands are always NOT NULL.
11443 */
11444 #define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
11445 #define SQLITE_STOREP2      0x20  /* Store result in reg[P2] rather than jump */
11446 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
11447 #define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
11448 
11449 /*
11450 ** An object of this type is created for each virtual table present in
11451 ** the database schema.
11452 **
11453 ** If the database schema is shared, then there is one instance of this
11454 ** structure for each database connection (sqlite3*) that uses the shared
11455 ** schema. This is because each database connection requires its own unique
11456 ** instance of the sqlite3_vtab* handle used to access the virtual table
11457 ** implementation. sqlite3_vtab* handles can not be shared between
11458 ** database connections, even when the rest of the in-memory database
11459 ** schema is shared, as the implementation often stores the database
11460 ** connection handle passed to it via the xConnect() or xCreate() method
11461 ** during initialization internally. This database connection handle may
11462 ** then be used by the virtual table implementation to access real tables
11463 ** within the database. So that they appear as part of the callers
11464 ** transaction, these accesses need to be made via the same database
11465 ** connection as that used to execute SQL operations on the virtual table.
11466 **
11467 ** All VTable objects that correspond to a single table in a shared
11468 ** database schema are initially stored in a linked-list pointed to by
11469 ** the Table.pVTable member variable of the corresponding Table object.
11470 ** When an sqlite3_prepare() operation is required to access the virtual
11471 ** table, it searches the list for the VTable that corresponds to the
11472 ** database connection doing the preparing so as to use the correct
11473 ** sqlite3_vtab* handle in the compiled query.
11474 **
11475 ** When an in-memory Table object is deleted (for example when the
11476 ** schema is being reloaded for some reason), the VTable objects are not
11477 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
11478 ** immediately. Instead, they are moved from the Table.pVTable list to
11479 ** another linked list headed by the sqlite3.pDisconnect member of the
11480 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
11481 ** next time a statement is prepared using said sqlite3*. This is done
11482 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
11483 ** Refer to comments above function sqlite3VtabUnlockList() for an
11484 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
11485 ** list without holding the corresponding sqlite3.mutex mutex.
11486 **
11487 ** The memory for objects of this type is always allocated by
11488 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
11489 ** the first argument.
11490 */
11491 struct VTable {
11492   sqlite3 *db;              /* Database connection associated with this table */
11493   Module *pMod;             /* Pointer to module implementation */
11494   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
11495   int nRef;                 /* Number of pointers to this structure */
11496   u8 bConstraint;           /* True if constraints are supported */
11497   int iSavepoint;           /* Depth of the SAVEPOINT stack */
11498   VTable *pNext;            /* Next in linked list (see above) */
11499 };
11500 
11501 /*
11502 ** The schema for each SQL table and view is represented in memory
11503 ** by an instance of the following structure.
11504 */
11505 struct Table {
11506   char *zName;         /* Name of the table or view */
11507   Column *aCol;        /* Information about each column */
11508   Index *pIndex;       /* List of SQL indexes on this table. */
11509   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
11510   FKey *pFKey;         /* Linked list of all foreign keys in this table */
11511   char *zColAff;       /* String defining the affinity of each column */
11512 #ifndef SQLITE_OMIT_CHECK
11513   ExprList *pCheck;    /* All CHECK constraints */
11514 #endif
11515   int tnum;            /* Root BTree page for this table */
11516   i16 iPKey;           /* If not negative, use aCol[iPKey] as the rowid */
11517   i16 nCol;            /* Number of columns in this table */
11518   u16 nRef;            /* Number of pointers to this Table */
11519   LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
11520   LogEst szTabRow;     /* Estimated size of each table row in bytes */
11521 #ifdef SQLITE_ENABLE_COSTMULT
11522   LogEst costMult;     /* Cost multiplier for using this table */
11523 #endif
11524   u8 tabFlags;         /* Mask of TF_* values */
11525   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
11526 #ifndef SQLITE_OMIT_ALTERTABLE
11527   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
11528 #endif
11529 #ifndef SQLITE_OMIT_VIRTUALTABLE
11530   int nModuleArg;      /* Number of arguments to the module */
11531   char **azModuleArg;  /* Text of all module args. [0] is module name */
11532   VTable *pVTable;     /* List of VTable objects. */
11533 #endif
11534   Trigger *pTrigger;   /* List of triggers stored in pSchema */
11535   Schema *pSchema;     /* Schema that contains this table */
11536   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
11537 };
11538 
11539 /*
11540 ** Allowed values for Table.tabFlags.
11541 **
11542 ** TF_OOOHidden applies to virtual tables that have hidden columns that are
11543 ** followed by non-hidden columns.  Example:  "CREATE VIRTUAL TABLE x USING
11544 ** vtab1(a HIDDEN, b);".  Since "b" is a non-hidden column but "a" is hidden,
11545 ** the TF_OOOHidden attribute would apply in this case.  Such tables require
11546 ** special handling during INSERT processing.
11547 */
11548 #define TF_Readonly        0x01    /* Read-only system table */
11549 #define TF_Ephemeral       0x02    /* An ephemeral table */
11550 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
11551 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
11552 #define TF_Virtual         0x10    /* Is a virtual table */
11553 #define TF_WithoutRowid    0x20    /* No rowid used. PRIMARY KEY is the key */
11554 #define TF_OOOHidden       0x40    /* Out-of-Order hidden columns */
11555 
11556 
11557 /*
11558 ** Test to see whether or not a table is a virtual table.  This is
11559 ** done as a macro so that it will be optimized out when virtual
11560 ** table support is omitted from the build.
11561 */
11562 #ifndef SQLITE_OMIT_VIRTUALTABLE
11563 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
11564 #  define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
11565 #else
11566 #  define IsVirtual(X)      0
11567 #  define IsHiddenColumn(X) 0
11568 #endif
11569 
11570 /* Does the table have a rowid */
11571 #define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
11572 
11573 /*
11574 ** Each foreign key constraint is an instance of the following structure.
11575 **
11576 ** A foreign key is associated with two tables.  The "from" table is
11577 ** the table that contains the REFERENCES clause that creates the foreign
11578 ** key.  The "to" table is the table that is named in the REFERENCES clause.
11579 ** Consider this example:
11580 **
11581 **     CREATE TABLE ex1(
11582 **       a INTEGER PRIMARY KEY,
11583 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
11584 **     );
11585 **
11586 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
11587 ** Equivalent names:
11588 **
11589 **     from-table == child-table
11590 **       to-table == parent-table
11591 **
11592 ** Each REFERENCES clause generates an instance of the following structure
11593 ** which is attached to the from-table.  The to-table need not exist when
11594 ** the from-table is created.  The existence of the to-table is not checked.
11595 **
11596 ** The list of all parents for child Table X is held at X.pFKey.
11597 **
11598 ** A list of all children for a table named Z (which might not even exist)
11599 ** is held in Schema.fkeyHash with a hash key of Z.
11600 */
11601 struct FKey {
11602   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
11603   FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
11604   char *zTo;        /* Name of table that the key points to (aka: Parent) */
11605   FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
11606   FKey *pPrevTo;    /* Previous with the same zTo */
11607   int nCol;         /* Number of columns in this key */
11608   /* EV: R-30323-21917 */
11609   u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
11610   u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
11611   Trigger *apTrigger[2];/* Triggers for aAction[] actions */
11612   struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
11613     int iFrom;            /* Index of column in pFrom */
11614     char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
11615   } aCol[1];            /* One entry for each of nCol columns */
11616 };
11617 
11618 /*
11619 ** SQLite supports many different ways to resolve a constraint
11620 ** error.  ROLLBACK processing means that a constraint violation
11621 ** causes the operation in process to fail and for the current transaction
11622 ** to be rolled back.  ABORT processing means the operation in process
11623 ** fails and any prior changes from that one operation are backed out,
11624 ** but the transaction is not rolled back.  FAIL processing means that
11625 ** the operation in progress stops and returns an error code.  But prior
11626 ** changes due to the same operation are not backed out and no rollback
11627 ** occurs.  IGNORE means that the particular row that caused the constraint
11628 ** error is not inserted or updated.  Processing continues and no error
11629 ** is returned.  REPLACE means that preexisting database rows that caused
11630 ** a UNIQUE constraint violation are removed so that the new insert or
11631 ** update can proceed.  Processing continues and no error is reported.
11632 **
11633 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
11634 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
11635 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
11636 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
11637 ** referenced table row is propagated into the row that holds the
11638 ** foreign key.
11639 **
11640 ** The following symbolic values are used to record which type
11641 ** of action to take.
11642 */
11643 #define OE_None     0   /* There is no constraint to check */
11644 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
11645 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
11646 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
11647 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
11648 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
11649 
11650 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
11651 #define OE_SetNull  7   /* Set the foreign key value to NULL */
11652 #define OE_SetDflt  8   /* Set the foreign key value to its default */
11653 #define OE_Cascade  9   /* Cascade the changes */
11654 
11655 #define OE_Default  10  /* Do whatever the default action is */
11656 
11657 
11658 /*
11659 ** An instance of the following structure is passed as the first
11660 ** argument to sqlite3VdbeKeyCompare and is used to control the
11661 ** comparison of the two index keys.
11662 **
11663 ** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
11664 ** are nField slots for the columns of an index then one extra slot
11665 ** for the rowid at the end.
11666 */
11667 struct KeyInfo {
11668   u32 nRef;           /* Number of references to this KeyInfo object */
11669   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
11670   u16 nField;         /* Number of key columns in the index */
11671   u16 nXField;        /* Number of columns beyond the key columns */
11672   sqlite3 *db;        /* The database connection */
11673   u8 *aSortOrder;     /* Sort order for each column. */
11674   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
11675 };
11676 
11677 /*
11678 ** An instance of the following structure holds information about a
11679 ** single index record that has already been parsed out into individual
11680 ** values.
11681 **
11682 ** A record is an object that contains one or more fields of data.
11683 ** Records are used to store the content of a table row and to store
11684 ** the key of an index.  A blob encoding of a record is created by
11685 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
11686 ** OP_Column opcode.
11687 **
11688 ** This structure holds a record that has already been disassembled
11689 ** into its constituent fields.
11690 **
11691 ** The r1 and r2 member variables are only used by the optimized comparison
11692 ** functions vdbeRecordCompareInt() and vdbeRecordCompareString().
11693 */
11694 struct UnpackedRecord {
11695   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
11696   u16 nField;         /* Number of entries in apMem[] */
11697   i8 default_rc;      /* Comparison result if keys are equal */
11698   u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
11699   Mem *aMem;          /* Values */
11700   int r1;             /* Value to return if (lhs > rhs) */
11701   int r2;             /* Value to return if (rhs < lhs) */
11702 };
11703 
11704 
11705 /*
11706 ** Each SQL index is represented in memory by an
11707 ** instance of the following structure.
11708 **
11709 ** The columns of the table that are to be indexed are described
11710 ** by the aiColumn[] field of this structure.  For example, suppose
11711 ** we have the following table and index:
11712 **
11713 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
11714 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
11715 **
11716 ** In the Table structure describing Ex1, nCol==3 because there are
11717 ** three columns in the table.  In the Index structure describing
11718 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
11719 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
11720 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
11721 ** The second column to be indexed (c1) has an index of 0 in
11722 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
11723 **
11724 ** The Index.onError field determines whether or not the indexed columns
11725 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
11726 ** it means this is not a unique index.  Otherwise it is a unique index
11727 ** and the value of Index.onError indicate the which conflict resolution
11728 ** algorithm to employ whenever an attempt is made to insert a non-unique
11729 ** element.
11730 */
11731 struct Index {
11732   char *zName;             /* Name of this index */
11733   i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
11734   LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
11735   Table *pTable;           /* The SQL table being indexed */
11736   char *zColAff;           /* String defining the affinity of each column */
11737   Index *pNext;            /* The next index associated with the same table */
11738   Schema *pSchema;         /* Schema containing this index */
11739   u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
11740   char **azColl;           /* Array of collation sequence names for index */
11741   Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
11742   int tnum;                /* DB Page containing root of this index */
11743   LogEst szIdxRow;         /* Estimated average row size in bytes */
11744   u16 nKeyCol;             /* Number of columns forming the key */
11745   u16 nColumn;             /* Number of columns stored in the index */
11746   u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
11747   unsigned idxType:2;      /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
11748   unsigned bUnordered:1;   /* Use this index for == or IN queries only */
11749   unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
11750   unsigned isResized:1;    /* True if resizeIndexObject() has been called */
11751   unsigned isCovering:1;   /* True if this is a covering index */
11752   unsigned noSkipScan:1;   /* Do not try to use skip-scan if true */
11753 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
11754   int nSample;             /* Number of elements in aSample[] */
11755   int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
11756   tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
11757   IndexSample *aSample;    /* Samples of the left-most key */
11758   tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */
11759   tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */
11760 #endif
11761 };
11762 
11763 /*
11764 ** Allowed values for Index.idxType
11765 */
11766 #define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
11767 #define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
11768 #define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
11769 
11770 /* Return true if index X is a PRIMARY KEY index */
11771 #define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
11772 
11773 /* Return true if index X is a UNIQUE index */
11774 #define IsUniqueIndex(X)      ((X)->onError!=OE_None)
11775 
11776 /*
11777 ** Each sample stored in the sqlite_stat3 table is represented in memory
11778 ** using a structure of this type.  See documentation at the top of the
11779 ** analyze.c source file for additional information.
11780 */
11781 struct IndexSample {
11782   void *p;          /* Pointer to sampled record */
11783   int n;            /* Size of record in bytes */
11784   tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
11785   tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
11786   tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
11787 };
11788 
11789 /*
11790 ** Each token coming out of the lexer is an instance of
11791 ** this structure.  Tokens are also used as part of an expression.
11792 **
11793 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
11794 ** may contain random values.  Do not make any assumptions about Token.dyn
11795 ** and Token.n when Token.z==0.
11796 */
11797 struct Token {
11798   const char *z;     /* Text of the token.  Not NULL-terminated! */
11799   unsigned int n;    /* Number of characters in this token */
11800 };
11801 
11802 /*
11803 ** An instance of this structure contains information needed to generate
11804 ** code for a SELECT that contains aggregate functions.
11805 **
11806 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
11807 ** pointer to this structure.  The Expr.iColumn field is the index in
11808 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
11809 ** code for that node.
11810 **
11811 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
11812 ** original Select structure that describes the SELECT statement.  These
11813 ** fields do not need to be freed when deallocating the AggInfo structure.
11814 */
11815 struct AggInfo {
11816   u8 directMode;          /* Direct rendering mode means take data directly
11817                           ** from source tables rather than from accumulators */
11818   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
11819                           ** than the source table */
11820   int sortingIdx;         /* Cursor number of the sorting index */
11821   int sortingIdxPTab;     /* Cursor number of pseudo-table */
11822   int nSortingColumn;     /* Number of columns in the sorting index */
11823   int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
11824   ExprList *pGroupBy;     /* The group by clause */
11825   struct AggInfo_col {    /* For each column used in source tables */
11826     Table *pTab;             /* Source table */
11827     int iTable;              /* Cursor number of the source table */
11828     int iColumn;             /* Column number within the source table */
11829     int iSorterColumn;       /* Column number in the sorting index */
11830     int iMem;                /* Memory location that acts as accumulator */
11831     Expr *pExpr;             /* The original expression */
11832   } *aCol;
11833   int nColumn;            /* Number of used entries in aCol[] */
11834   int nAccumulator;       /* Number of columns that show through to the output.
11835                           ** Additional columns are used only as parameters to
11836                           ** aggregate functions */
11837   struct AggInfo_func {   /* For each aggregate function */
11838     Expr *pExpr;             /* Expression encoding the function */
11839     FuncDef *pFunc;          /* The aggregate function implementation */
11840     int iMem;                /* Memory location that acts as accumulator */
11841     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
11842   } *aFunc;
11843   int nFunc;              /* Number of entries in aFunc[] */
11844 };
11845 
11846 /*
11847 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
11848 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
11849 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
11850 ** it uses less memory in the Expr object, which is a big memory user
11851 ** in systems with lots of prepared statements.  And few applications
11852 ** need more than about 10 or 20 variables.  But some extreme users want
11853 ** to have prepared statements with over 32767 variables, and for them
11854 ** the option is available (at compile-time).
11855 */
11856 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
11857 typedef i16 ynVar;
11858 #else
11859 typedef int ynVar;
11860 #endif
11861 
11862 /*
11863 ** Each node of an expression in the parse tree is an instance
11864 ** of this structure.
11865 **
11866 ** Expr.op is the opcode. The integer parser token codes are reused
11867 ** as opcodes here. For example, the parser defines TK_GE to be an integer
11868 ** code representing the ">=" operator. This same integer code is reused
11869 ** to represent the greater-than-or-equal-to operator in the expression
11870 ** tree.
11871 **
11872 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
11873 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
11874 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
11875 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
11876 ** then Expr.token contains the name of the function.
11877 **
11878 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
11879 ** binary operator. Either or both may be NULL.
11880 **
11881 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
11882 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
11883 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
11884 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
11885 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
11886 ** valid.
11887 **
11888 ** An expression of the form ID or ID.ID refers to a column in a table.
11889 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
11890 ** the integer cursor number of a VDBE cursor pointing to that table and
11891 ** Expr.iColumn is the column number for the specific column.  If the
11892 ** expression is used as a result in an aggregate SELECT, then the
11893 ** value is also stored in the Expr.iAgg column in the aggregate so that
11894 ** it can be accessed after all aggregates are computed.
11895 **
11896 ** If the expression is an unbound variable marker (a question mark
11897 ** character '?' in the original SQL) then the Expr.iTable holds the index
11898 ** number for that variable.
11899 **
11900 ** If the expression is a subquery then Expr.iColumn holds an integer
11901 ** register number containing the result of the subquery.  If the
11902 ** subquery gives a constant result, then iTable is -1.  If the subquery
11903 ** gives a different answer at different times during statement processing
11904 ** then iTable is the address of a subroutine that computes the subquery.
11905 **
11906 ** If the Expr is of type OP_Column, and the table it is selecting from
11907 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
11908 ** corresponding table definition.
11909 **
11910 ** ALLOCATION NOTES:
11911 **
11912 ** Expr objects can use a lot of memory space in database schema.  To
11913 ** help reduce memory requirements, sometimes an Expr object will be
11914 ** truncated.  And to reduce the number of memory allocations, sometimes
11915 ** two or more Expr objects will be stored in a single memory allocation,
11916 ** together with Expr.zToken strings.
11917 **
11918 ** If the EP_Reduced and EP_TokenOnly flags are set when
11919 ** an Expr object is truncated.  When EP_Reduced is set, then all
11920 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
11921 ** are contained within the same memory allocation.  Note, however, that
11922 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
11923 ** allocated, regardless of whether or not EP_Reduced is set.
11924 */
11925 struct Expr {
11926   u8 op;                 /* Operation performed by this node */
11927   char affinity;         /* The affinity of the column or 0 if not a column */
11928   u32 flags;             /* Various flags.  EP_* See below */
11929   union {
11930     char *zToken;          /* Token value. Zero terminated and dequoted */
11931     int iValue;            /* Non-negative integer value if EP_IntValue */
11932   } u;
11933 
11934   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
11935   ** space is allocated for the fields below this point. An attempt to
11936   ** access them will result in a segfault or malfunction.
11937   *********************************************************************/
11938 
11939   Expr *pLeft;           /* Left subnode */
11940   Expr *pRight;          /* Right subnode */
11941   union {
11942     ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
11943     Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
11944   } x;
11945 
11946   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
11947   ** space is allocated for the fields below this point. An attempt to
11948   ** access them will result in a segfault or malfunction.
11949   *********************************************************************/
11950 
11951 #if SQLITE_MAX_EXPR_DEPTH>0
11952   int nHeight;           /* Height of the tree headed by this node */
11953 #endif
11954   int iTable;            /* TK_COLUMN: cursor number of table holding column
11955                          ** TK_REGISTER: register number
11956                          ** TK_TRIGGER: 1 -> new, 0 -> old
11957                          ** EP_Unlikely:  134217728 times likelihood */
11958   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
11959                          ** TK_VARIABLE: variable number (always >= 1). */
11960   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
11961   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
11962   u8 op2;                /* TK_REGISTER: original value of Expr.op
11963                          ** TK_COLUMN: the value of p5 for OP_Column
11964                          ** TK_AGG_FUNCTION: nesting depth */
11965   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
11966   Table *pTab;           /* Table for TK_COLUMN expressions. */
11967 };
11968 
11969 /*
11970 ** The following are the meanings of bits in the Expr.flags field.
11971 */
11972 #define EP_FromJoin  0x000001 /* Originates in ON/USING clause of outer join */
11973 #define EP_Agg       0x000002 /* Contains one or more aggregate functions */
11974 #define EP_Resolved  0x000004 /* IDs have been resolved to COLUMNs */
11975 #define EP_Error     0x000008 /* Expression contains one or more errors */
11976 #define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
11977 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
11978 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
11979 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
11980 #define EP_Collate   0x000100 /* Tree contains a TK_COLLATE operator */
11981 #define EP_Generic   0x000200 /* Ignore COLLATE or affinity on this tree */
11982 #define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
11983 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
11984 #define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
11985 #define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
11986 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
11987 #define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
11988 #define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
11989 #define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
11990 #define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
11991 #define EP_ConstFunc 0x080000 /* Node is a SQLITE_FUNC_CONSTANT function */
11992 #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
11993 #define EP_Subquery  0x200000 /* Tree contains a TK_SELECT operator */
11994 
11995 /*
11996 ** Combinations of two or more EP_* flags
11997 */
11998 #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
11999 
12000 /*
12001 ** These macros can be used to test, set, or clear bits in the
12002 ** Expr.flags field.
12003 */
12004 #define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
12005 #define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
12006 #define ExprSetProperty(E,P)     (E)->flags|=(P)
12007 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
12008 
12009 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
12010 ** and Accreditation only.  It works like ExprSetProperty() during VVA
12011 ** processes but is a no-op for delivery.
12012 */
12013 #ifdef SQLITE_DEBUG
12014 # define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
12015 #else
12016 # define ExprSetVVAProperty(E,P)
12017 #endif
12018 
12019 /*
12020 ** Macros to determine the number of bytes required by a normal Expr
12021 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
12022 ** and an Expr struct with the EP_TokenOnly flag set.
12023 */
12024 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
12025 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
12026 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
12027 
12028 /*
12029 ** Flags passed to the sqlite3ExprDup() function. See the header comment
12030 ** above sqlite3ExprDup() for details.
12031 */
12032 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
12033 
12034 /*
12035 ** A list of expressions.  Each expression may optionally have a
12036 ** name.  An expr/name combination can be used in several ways, such
12037 ** as the list of "expr AS ID" fields following a "SELECT" or in the
12038 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
12039 ** also be used as the argument to a function, in which case the a.zName
12040 ** field is not used.
12041 **
12042 ** By default the Expr.zSpan field holds a human-readable description of
12043 ** the expression that is used in the generation of error messages and
12044 ** column labels.  In this case, Expr.zSpan is typically the text of a
12045 ** column expression as it exists in a SELECT statement.  However, if
12046 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
12047 ** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
12048 ** form is used for name resolution with nested FROM clauses.
12049 */
12050 struct ExprList {
12051   int nExpr;             /* Number of expressions on the list */
12052   struct ExprList_item { /* For each expression in the list */
12053     Expr *pExpr;            /* The list of expressions */
12054     char *zName;            /* Token associated with this expression */
12055     char *zSpan;            /* Original text of the expression */
12056     u8 sortOrder;           /* 1 for DESC or 0 for ASC */
12057     unsigned done :1;       /* A flag to indicate when processing is finished */
12058     unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
12059     unsigned reusable :1;   /* Constant expression is reusable */
12060     union {
12061       struct {
12062         u16 iOrderByCol;      /* For ORDER BY, column number in result set */
12063         u16 iAlias;           /* Index into Parse.aAlias[] for zName */
12064       } x;
12065       int iConstExprReg;      /* Register in which Expr value is cached */
12066     } u;
12067   } *a;                  /* Alloc a power of two greater or equal to nExpr */
12068 };
12069 
12070 /*
12071 ** An instance of this structure is used by the parser to record both
12072 ** the parse tree for an expression and the span of input text for an
12073 ** expression.
12074 */
12075 struct ExprSpan {
12076   Expr *pExpr;          /* The expression parse tree */
12077   const char *zStart;   /* First character of input text */
12078   const char *zEnd;     /* One character past the end of input text */
12079 };
12080 
12081 /*
12082 ** An instance of this structure can hold a simple list of identifiers,
12083 ** such as the list "a,b,c" in the following statements:
12084 **
12085 **      INSERT INTO t(a,b,c) VALUES ...;
12086 **      CREATE INDEX idx ON t(a,b,c);
12087 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
12088 **
12089 ** The IdList.a.idx field is used when the IdList represents the list of
12090 ** column names after a table name in an INSERT statement.  In the statement
12091 **
12092 **     INSERT INTO t(a,b,c) ...
12093 **
12094 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
12095 */
12096 struct IdList {
12097   struct IdList_item {
12098     char *zName;      /* Name of the identifier */
12099     int idx;          /* Index in some Table.aCol[] of a column named zName */
12100   } *a;
12101   int nId;         /* Number of identifiers on the list */
12102 };
12103 
12104 /*
12105 ** The bitmask datatype defined below is used for various optimizations.
12106 **
12107 ** Changing this from a 64-bit to a 32-bit type limits the number of
12108 ** tables in a join to 32 instead of 64.  But it also reduces the size
12109 ** of the library by 738 bytes on ix86.
12110 */
12111 typedef u64 Bitmask;
12112 
12113 /*
12114 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
12115 */
12116 #define BMS  ((int)(sizeof(Bitmask)*8))
12117 
12118 /*
12119 ** A bit in a Bitmask
12120 */
12121 #define MASKBIT(n)   (((Bitmask)1)<<(n))
12122 #define MASKBIT32(n) (((unsigned int)1)<<(n))
12123 
12124 /*
12125 ** The following structure describes the FROM clause of a SELECT statement.
12126 ** Each table or subquery in the FROM clause is a separate element of
12127 ** the SrcList.a[] array.
12128 **
12129 ** With the addition of multiple database support, the following structure
12130 ** can also be used to describe a particular table such as the table that
12131 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
12132 ** such a table must be a simple name: ID.  But in SQLite, the table can
12133 ** now be identified by a database name, a dot, then the table name: ID.ID.
12134 **
12135 ** The jointype starts out showing the join type between the current table
12136 ** and the next table on the list.  The parser builds the list this way.
12137 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
12138 ** jointype expresses the join between the table and the previous table.
12139 **
12140 ** In the colUsed field, the high-order bit (bit 63) is set if the table
12141 ** contains more than 63 columns and the 64-th or later column is used.
12142 */
12143 struct SrcList {
12144   int nSrc;        /* Number of tables or subqueries in the FROM clause */
12145   u32 nAlloc;      /* Number of entries allocated in a[] below */
12146   struct SrcList_item {
12147     Schema *pSchema;  /* Schema to which this item is fixed */
12148     char *zDatabase;  /* Name of database holding this table */
12149     char *zName;      /* Name of the table */
12150     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
12151     Table *pTab;      /* An SQL table corresponding to zName */
12152     Select *pSelect;  /* A SELECT statement used in place of a table name */
12153     int addrFillSub;  /* Address of subroutine to manifest a subquery */
12154     int regReturn;    /* Register holding return address of addrFillSub */
12155     int regResult;    /* Registers holding results of a co-routine */
12156     u8 jointype;      /* Type of join between this able and the previous */
12157     unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
12158     unsigned isCorrelated :1;  /* True if sub-query is correlated */
12159     unsigned viaCoroutine :1;  /* Implemented as a co-routine */
12160     unsigned isRecursive :1;   /* True for recursive reference in WITH */
12161 #ifndef SQLITE_OMIT_EXPLAIN
12162     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
12163 #endif
12164     int iCursor;      /* The VDBE cursor number used to access this table */
12165     Expr *pOn;        /* The ON clause of a join */
12166     IdList *pUsing;   /* The USING clause of a join */
12167     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
12168     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
12169     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
12170   } a[1];             /* One entry for each identifier on the list */
12171 };
12172 
12173 /*
12174 ** Permitted values of the SrcList.a.jointype field
12175 */
12176 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
12177 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
12178 #define JT_NATURAL   0x0004    /* True for a "natural" join */
12179 #define JT_LEFT      0x0008    /* Left outer join */
12180 #define JT_RIGHT     0x0010    /* Right outer join */
12181 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
12182 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
12183 
12184 
12185 /*
12186 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
12187 ** and the WhereInfo.wctrlFlags member.
12188 */
12189 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
12190 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
12191 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
12192 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
12193 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
12194 #define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
12195 #define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
12196 #define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
12197 #define WHERE_NO_AUTOINDEX     0x0080 /* Disallow automatic indexes */
12198 #define WHERE_GROUPBY          0x0100 /* pOrderBy is really a GROUP BY */
12199 #define WHERE_DISTINCTBY       0x0200 /* pOrderby is really a DISTINCT clause */
12200 #define WHERE_WANT_DISTINCT    0x0400 /* All output needs to be distinct */
12201 #define WHERE_SORTBYGROUP      0x0800 /* Support sqlite3WhereIsSorted() */
12202 #define WHERE_REOPEN_IDX       0x1000 /* Try to use OP_ReopenIdx */
12203 
12204 /* Allowed return values from sqlite3WhereIsDistinct()
12205 */
12206 #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
12207 #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
12208 #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
12209 #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
12210 
12211 /*
12212 ** A NameContext defines a context in which to resolve table and column
12213 ** names.  The context consists of a list of tables (the pSrcList) field and
12214 ** a list of named expression (pEList).  The named expression list may
12215 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
12216 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
12217 ** pEList corresponds to the result set of a SELECT and is NULL for
12218 ** other statements.
12219 **
12220 ** NameContexts can be nested.  When resolving names, the inner-most
12221 ** context is searched first.  If no match is found, the next outer
12222 ** context is checked.  If there is still no match, the next context
12223 ** is checked.  This process continues until either a match is found
12224 ** or all contexts are check.  When a match is found, the nRef member of
12225 ** the context containing the match is incremented.
12226 **
12227 ** Each subquery gets a new NameContext.  The pNext field points to the
12228 ** NameContext in the parent query.  Thus the process of scanning the
12229 ** NameContext list corresponds to searching through successively outer
12230 ** subqueries looking for a match.
12231 */
12232 struct NameContext {
12233   Parse *pParse;       /* The parser */
12234   SrcList *pSrcList;   /* One or more tables used to resolve names */
12235   ExprList *pEList;    /* Optional list of result-set columns */
12236   AggInfo *pAggInfo;   /* Information about aggregates at this level */
12237   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
12238   int nRef;            /* Number of names resolved by this context */
12239   int nErr;            /* Number of errors encountered while resolving names */
12240   u16 ncFlags;         /* Zero or more NC_* flags defined below */
12241 };
12242 
12243 /*
12244 ** Allowed values for the NameContext, ncFlags field.
12245 **
12246 ** Note:  NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
12247 ** SQLITE_FUNC_MINMAX.
12248 **
12249 */
12250 #define NC_AllowAgg  0x0001  /* Aggregate functions are allowed here */
12251 #define NC_HasAgg    0x0002  /* One or more aggregate functions seen */
12252 #define NC_IsCheck   0x0004  /* True if resolving names in a CHECK constraint */
12253 #define NC_InAggFunc 0x0008  /* True if analyzing arguments to an agg func */
12254 #define NC_PartIdx   0x0010  /* True if resolving a partial index WHERE */
12255 #define NC_MinMaxAgg 0x1000  /* min/max aggregates seen.  See note above */
12256 
12257 /*
12258 ** An instance of the following structure contains all information
12259 ** needed to generate code for a single SELECT statement.
12260 **
12261 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
12262 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
12263 ** limit and nOffset to the value of the offset (or 0 if there is not
12264 ** offset).  But later on, nLimit and nOffset become the memory locations
12265 ** in the VDBE that record the limit and offset counters.
12266 **
12267 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
12268 ** These addresses must be stored so that we can go back and fill in
12269 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
12270 ** the number of columns in P2 can be computed at the same time
12271 ** as the OP_OpenEphm instruction is coded because not
12272 ** enough information about the compound query is known at that point.
12273 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
12274 ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
12275 ** sequences for the ORDER BY clause.
12276 */
12277 struct Select {
12278   ExprList *pEList;      /* The fields of the result */
12279   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
12280   u16 selFlags;          /* Various SF_* values */
12281   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
12282 #if SELECTTRACE_ENABLED
12283   char zSelName[12];     /* Symbolic name of this SELECT use for debugging */
12284 #endif
12285   int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
12286   u64 nSelectRow;        /* Estimated number of result rows */
12287   SrcList *pSrc;         /* The FROM clause */
12288   Expr *pWhere;          /* The WHERE clause */
12289   ExprList *pGroupBy;    /* The GROUP BY clause */
12290   Expr *pHaving;         /* The HAVING clause */
12291   ExprList *pOrderBy;    /* The ORDER BY clause */
12292   Select *pPrior;        /* Prior select in a compound select statement */
12293   Select *pNext;         /* Next select to the left in a compound */
12294   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
12295   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
12296   With *pWith;           /* WITH clause attached to this select. Or NULL. */
12297 };
12298 
12299 /*
12300 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
12301 ** "Select Flag".
12302 */
12303 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
12304 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
12305 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
12306 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
12307 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
12308 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
12309 #define SF_Compound        0x0040  /* Part of a compound query */
12310 #define SF_Values          0x0080  /* Synthesized from VALUES clause */
12311 #define SF_MultiValue      0x0100  /* Single VALUES term with multiple rows */
12312 #define SF_NestedFrom      0x0200  /* Part of a parenthesized FROM clause */
12313 #define SF_MaybeConvert    0x0400  /* Need convertCompoundSelectToSubquery() */
12314 #define SF_Recursive       0x0800  /* The recursive part of a recursive CTE */
12315 #define SF_MinMaxAgg       0x1000  /* Aggregate containing min() or max() */
12316 #define SF_Converted       0x2000  /* By convertCompoundSelectToSubquery() */
12317 
12318 
12319 /*
12320 ** The results of a SELECT can be distributed in several ways, as defined
12321 ** by one of the following macros.  The "SRT" prefix means "SELECT Result
12322 ** Type".
12323 **
12324 **     SRT_Union       Store results as a key in a temporary index
12325 **                     identified by pDest->iSDParm.
12326 **
12327 **     SRT_Except      Remove results from the temporary index pDest->iSDParm.
12328 **
12329 **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
12330 **                     set is not empty.
12331 **
12332 **     SRT_Discard     Throw the results away.  This is used by SELECT
12333 **                     statements within triggers whose only purpose is
12334 **                     the side-effects of functions.
12335 **
12336 ** All of the above are free to ignore their ORDER BY clause. Those that
12337 ** follow must honor the ORDER BY clause.
12338 **
12339 **     SRT_Output      Generate a row of output (using the OP_ResultRow
12340 **                     opcode) for each row in the result set.
12341 **
12342 **     SRT_Mem         Only valid if the result is a single column.
12343 **                     Store the first column of the first result row
12344 **                     in register pDest->iSDParm then abandon the rest
12345 **                     of the query.  This destination implies "LIMIT 1".
12346 **
12347 **     SRT_Set         The result must be a single column.  Store each
12348 **                     row of result as the key in table pDest->iSDParm.
12349 **                     Apply the affinity pDest->affSdst before storing
12350 **                     results.  Used to implement "IN (SELECT ...)".
12351 **
12352 **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
12353 **                     the result there. The cursor is left open after
12354 **                     returning.  This is like SRT_Table except that
12355 **                     this destination uses OP_OpenEphemeral to create
12356 **                     the table first.
12357 **
12358 **     SRT_Coroutine   Generate a co-routine that returns a new row of
12359 **                     results each time it is invoked.  The entry point
12360 **                     of the co-routine is stored in register pDest->iSDParm
12361 **                     and the result row is stored in pDest->nDest registers
12362 **                     starting with pDest->iSdst.
12363 **
12364 **     SRT_Table       Store results in temporary table pDest->iSDParm.
12365 **     SRT_Fifo        This is like SRT_EphemTab except that the table
12366 **                     is assumed to already be open.  SRT_Fifo has
12367 **                     the additional property of being able to ignore
12368 **                     the ORDER BY clause.
12369 **
12370 **     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
12371 **                     But also use temporary table pDest->iSDParm+1 as
12372 **                     a record of all prior results and ignore any duplicate
12373 **                     rows.  Name means:  "Distinct Fifo".
12374 **
12375 **     SRT_Queue       Store results in priority queue pDest->iSDParm (really
12376 **                     an index).  Append a sequence number so that all entries
12377 **                     are distinct.
12378 **
12379 **     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
12380 **                     the same record has never been stored before.  The
12381 **                     index at pDest->iSDParm+1 hold all prior stores.
12382 */
12383 #define SRT_Union        1  /* Store result as keys in an index */
12384 #define SRT_Except       2  /* Remove result from a UNION index */
12385 #define SRT_Exists       3  /* Store 1 if the result is not empty */
12386 #define SRT_Discard      4  /* Do not save the results anywhere */
12387 #define SRT_Fifo         5  /* Store result as data with an automatic rowid */
12388 #define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */
12389 #define SRT_Queue        7  /* Store result in an queue */
12390 #define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */
12391 
12392 /* The ORDER BY clause is ignored for all of the above */
12393 #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
12394 
12395 #define SRT_Output       9  /* Output each row of result */
12396 #define SRT_Mem         10  /* Store result in a memory cell */
12397 #define SRT_Set         11  /* Store results as keys in an index */
12398 #define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
12399 #define SRT_Coroutine   13  /* Generate a single row of result */
12400 #define SRT_Table       14  /* Store result as data with an automatic rowid */
12401 
12402 /*
12403 ** An instance of this object describes where to put of the results of
12404 ** a SELECT statement.
12405 */
12406 struct SelectDest {
12407   u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
12408   char affSdst;        /* Affinity used when eDest==SRT_Set */
12409   int iSDParm;         /* A parameter used by the eDest disposal method */
12410   int iSdst;           /* Base register where results are written */
12411   int nSdst;           /* Number of registers allocated */
12412   ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
12413 };
12414 
12415 /*
12416 ** During code generation of statements that do inserts into AUTOINCREMENT
12417 ** tables, the following information is attached to the Table.u.autoInc.p
12418 ** pointer of each autoincrement table to record some side information that
12419 ** the code generator needs.  We have to keep per-table autoincrement
12420 ** information in case inserts are down within triggers.  Triggers do not
12421 ** normally coordinate their activities, but we do need to coordinate the
12422 ** loading and saving of autoincrement information.
12423 */
12424 struct AutoincInfo {
12425   AutoincInfo *pNext;   /* Next info block in a list of them all */
12426   Table *pTab;          /* Table this info block refers to */
12427   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
12428   int regCtr;           /* Memory register holding the rowid counter */
12429 };
12430 
12431 /*
12432 ** Size of the column cache
12433 */
12434 #ifndef SQLITE_N_COLCACHE
12435 # define SQLITE_N_COLCACHE 10
12436 #endif
12437 
12438 /*
12439 ** At least one instance of the following structure is created for each
12440 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
12441 ** statement. All such objects are stored in the linked list headed at
12442 ** Parse.pTriggerPrg and deleted once statement compilation has been
12443 ** completed.
12444 **
12445 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
12446 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
12447 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
12448 ** The Parse.pTriggerPrg list never contains two entries with the same
12449 ** values for both pTrigger and orconf.
12450 **
12451 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
12452 ** accessed (or set to 0 for triggers fired as a result of INSERT
12453 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
12454 ** a mask of new.* columns used by the program.
12455 */
12456 struct TriggerPrg {
12457   Trigger *pTrigger;      /* Trigger this program was coded from */
12458   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
12459   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
12460   int orconf;             /* Default ON CONFLICT policy */
12461   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
12462 };
12463 
12464 /*
12465 ** The yDbMask datatype for the bitmask of all attached databases.
12466 */
12467 #if SQLITE_MAX_ATTACHED>30
12468   typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
12469 # define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)
12470 # define DbMaskZero(M)      memset((M),0,sizeof(M))
12471 # define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))
12472 # define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)
12473 # define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)
12474 #else
12475   typedef unsigned int yDbMask;
12476 # define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)
12477 # define DbMaskZero(M)      (M)=0
12478 # define DbMaskSet(M,I)     (M)|=(((yDbMask)1)<<(I))
12479 # define DbMaskAllZero(M)   (M)==0
12480 # define DbMaskNonZero(M)   (M)!=0
12481 #endif
12482 
12483 /*
12484 ** An SQL parser context.  A copy of this structure is passed through
12485 ** the parser and down into all the parser action routine in order to
12486 ** carry around information that is global to the entire parse.
12487 **
12488 ** The structure is divided into two parts.  When the parser and code
12489 ** generate call themselves recursively, the first part of the structure
12490 ** is constant but the second part is reset at the beginning and end of
12491 ** each recursion.
12492 **
12493 ** The nTableLock and aTableLock variables are only used if the shared-cache
12494 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
12495 ** used to store the set of table-locks required by the statement being
12496 ** compiled. Function sqlite3TableLock() is used to add entries to the
12497 ** list.
12498 */
12499 struct Parse {
12500   sqlite3 *db;         /* The main database structure */
12501   char *zErrMsg;       /* An error message */
12502   Vdbe *pVdbe;         /* An engine for executing database bytecode */
12503   int rc;              /* Return code from execution */
12504   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
12505   u8 checkSchema;      /* Causes schema cookie check after an error */
12506   u8 nested;           /* Number of nested calls to the parser/code generator */
12507   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
12508   u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
12509   u8 mayAbort;         /* True if statement may throw an ABORT exception */
12510   u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
12511   u8 okConstFactor;    /* OK to factor out constants */
12512   int aTempReg[8];     /* Holding area for temporary registers */
12513   int nRangeReg;       /* Size of the temporary register block */
12514   int iRangeReg;       /* First register in temporary register block */
12515   int nErr;            /* Number of errors seen */
12516   int nTab;            /* Number of previously allocated VDBE cursors */
12517   int nMem;            /* Number of memory cells used so far */
12518   int nSet;            /* Number of sets used so far */
12519   int nOnce;           /* Number of OP_Once instructions so far */
12520   int nOpAlloc;        /* Number of slots allocated for Vdbe.aOp[] */
12521   int iFixedOp;        /* Never back out opcodes iFixedOp-1 or earlier */
12522   int ckBase;          /* Base register of data during check constraints */
12523   int iPartIdxTab;     /* Table corresponding to a partial index */
12524   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
12525   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
12526   int nLabel;          /* Number of labels used */
12527   int *aLabel;         /* Space to hold the labels */
12528   struct yColCache {
12529     int iTable;           /* Table cursor number */
12530     i16 iColumn;          /* Table column number */
12531     u8 tempReg;           /* iReg is a temp register that needs to be freed */
12532     int iLevel;           /* Nesting level */
12533     int iReg;             /* Reg with value of this column. 0 means none. */
12534     int lru;              /* Least recently used entry has the smallest value */
12535   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
12536   ExprList *pConstExpr;/* Constant expressions */
12537   Token constraintName;/* Name of the constraint currently being parsed */
12538   yDbMask writeMask;   /* Start a write transaction on these databases */
12539   yDbMask cookieMask;  /* Bitmask of schema verified databases */
12540   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
12541   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
12542   int regRoot;         /* Register holding root page number for new objects */
12543   int nMaxArg;         /* Max args passed to user function by sub-program */
12544 #if SELECTTRACE_ENABLED
12545   int nSelect;         /* Number of SELECT statements seen */
12546   int nSelectIndent;   /* How far to indent SELECTTRACE() output */
12547 #endif
12548 #ifndef SQLITE_OMIT_SHARED_CACHE
12549   int nTableLock;        /* Number of locks in aTableLock */
12550   TableLock *aTableLock; /* Required table locks for shared-cache mode */
12551 #endif
12552   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
12553 
12554   /* Information used while coding trigger programs. */
12555   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
12556   Table *pTriggerTab;  /* Table triggers are being coded for */
12557   int addrCrTab;       /* Address of OP_CreateTable opcode on CREATE TABLE */
12558   int addrSkipPK;      /* Address of instruction to skip PRIMARY KEY index */
12559   u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
12560   u32 oldmask;         /* Mask of old.* columns referenced */
12561   u32 newmask;         /* Mask of new.* columns referenced */
12562   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
12563   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
12564   u8 disableTriggers;  /* True to disable triggers */
12565 
12566   /************************************************************************
12567   ** Above is constant between recursions.  Below is reset before and after
12568   ** each recursion.  The boundary between these two regions is determined
12569   ** using offsetof(Parse,nVar) so the nVar field must be the first field
12570   ** in the recursive region.
12571   ************************************************************************/
12572 
12573   int nVar;                 /* Number of '?' variables seen in the SQL so far */
12574   int nzVar;                /* Number of available slots in azVar[] */
12575   u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
12576   u8 bFreeWith;             /* True if pWith should be freed with parser */
12577   u8 explain;               /* True if the EXPLAIN flag is found on the query */
12578 #ifndef SQLITE_OMIT_VIRTUALTABLE
12579   u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
12580   int nVtabLock;            /* Number of virtual tables to lock */
12581 #endif
12582   int nAlias;               /* Number of aliased result set columns */
12583   int nHeight;              /* Expression tree height of current sub-select */
12584 #ifndef SQLITE_OMIT_EXPLAIN
12585   int iSelectId;            /* ID of current select for EXPLAIN output */
12586   int iNextSelectId;        /* Next available select ID for EXPLAIN output */
12587 #endif
12588   char **azVar;             /* Pointers to names of parameters */
12589   Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
12590   const char *zTail;        /* All SQL text past the last semicolon parsed */
12591   Table *pNewTable;         /* A table being constructed by CREATE TABLE */
12592   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
12593   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
12594   Token sNameToken;         /* Token with unqualified schema object name */
12595   Token sLastToken;         /* The last token parsed */
12596 #ifndef SQLITE_OMIT_VIRTUALTABLE
12597   Token sArg;               /* Complete text of a module argument */
12598   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
12599 #endif
12600   Table *pZombieTab;        /* List of Table objects to delete after code gen */
12601   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
12602   With *pWith;              /* Current WITH clause, or NULL */
12603 };
12604 
12605 /*
12606 ** Return true if currently inside an sqlite3_declare_vtab() call.
12607 */
12608 #ifdef SQLITE_OMIT_VIRTUALTABLE
12609   #define IN_DECLARE_VTAB 0
12610 #else
12611   #define IN_DECLARE_VTAB (pParse->declareVtab)
12612 #endif
12613 
12614 /*
12615 ** An instance of the following structure can be declared on a stack and used
12616 ** to save the Parse.zAuthContext value so that it can be restored later.
12617 */
12618 struct AuthContext {
12619   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
12620   Parse *pParse;              /* The Parse structure */
12621 };
12622 
12623 /*
12624 ** Bitfield flags for P5 value in various opcodes.
12625 */
12626 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
12627 #define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
12628 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
12629 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
12630 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
12631 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
12632 #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
12633 #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
12634 #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
12635 #define OPFLAG_SEEKEQ        0x02    /* OP_Open** cursor uses EQ seek only */
12636 #define OPFLAG_P2ISREG       0x04    /* P2 to OP_Open** is a register number */
12637 #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
12638 
12639 /*
12640  * Each trigger present in the database schema is stored as an instance of
12641  * struct Trigger.
12642  *
12643  * Pointers to instances of struct Trigger are stored in two ways.
12644  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
12645  *    database). This allows Trigger structures to be retrieved by name.
12646  * 2. All triggers associated with a single table form a linked list, using the
12647  *    pNext member of struct Trigger. A pointer to the first element of the
12648  *    linked list is stored as the "pTrigger" member of the associated
12649  *    struct Table.
12650  *
12651  * The "step_list" member points to the first element of a linked list
12652  * containing the SQL statements specified as the trigger program.
12653  */
12654 struct Trigger {
12655   char *zName;            /* The name of the trigger                        */
12656   char *table;            /* The table or view to which the trigger applies */
12657   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
12658   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
12659   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
12660   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
12661                              the <column-list> is stored here */
12662   Schema *pSchema;        /* Schema containing the trigger */
12663   Schema *pTabSchema;     /* Schema containing the table */
12664   TriggerStep *step_list; /* Link list of trigger program steps             */
12665   Trigger *pNext;         /* Next trigger associated with the table */
12666 };
12667 
12668 /*
12669 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
12670 ** determine which.
12671 **
12672 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
12673 ** In that cases, the constants below can be ORed together.
12674 */
12675 #define TRIGGER_BEFORE  1
12676 #define TRIGGER_AFTER   2
12677 
12678 /*
12679  * An instance of struct TriggerStep is used to store a single SQL statement
12680  * that is a part of a trigger-program.
12681  *
12682  * Instances of struct TriggerStep are stored in a singly linked list (linked
12683  * using the "pNext" member) referenced by the "step_list" member of the
12684  * associated struct Trigger instance. The first element of the linked list is
12685  * the first step of the trigger-program.
12686  *
12687  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
12688  * "SELECT" statement. The meanings of the other members is determined by the
12689  * value of "op" as follows:
12690  *
12691  * (op == TK_INSERT)
12692  * orconf    -> stores the ON CONFLICT algorithm
12693  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
12694  *              this stores a pointer to the SELECT statement. Otherwise NULL.
12695  * zTarget   -> Dequoted name of the table to insert into.
12696  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
12697  *              this stores values to be inserted. Otherwise NULL.
12698  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
12699  *              statement, then this stores the column-names to be
12700  *              inserted into.
12701  *
12702  * (op == TK_DELETE)
12703  * zTarget   -> Dequoted name of the table to delete from.
12704  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
12705  *              Otherwise NULL.
12706  *
12707  * (op == TK_UPDATE)
12708  * zTarget   -> Dequoted name of the table to update.
12709  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
12710  *              Otherwise NULL.
12711  * pExprList -> A list of the columns to update and the expressions to update
12712  *              them to. See sqlite3Update() documentation of "pChanges"
12713  *              argument.
12714  *
12715  */
12716 struct TriggerStep {
12717   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
12718   u8 orconf;           /* OE_Rollback etc. */
12719   Trigger *pTrig;      /* The trigger that this step is a part of */
12720   Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
12721   char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
12722   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
12723   ExprList *pExprList; /* SET clause for UPDATE. */
12724   IdList *pIdList;     /* Column names for INSERT */
12725   TriggerStep *pNext;  /* Next in the link-list */
12726   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
12727 };
12728 
12729 /*
12730 ** The following structure contains information used by the sqliteFix...
12731 ** routines as they walk the parse tree to make database references
12732 ** explicit.
12733 */
12734 typedef struct DbFixer DbFixer;
12735 struct DbFixer {
12736   Parse *pParse;      /* The parsing context.  Error messages written here */
12737   Schema *pSchema;    /* Fix items to this schema */
12738   int bVarOnly;       /* Check for variable references only */
12739   const char *zDb;    /* Make sure all objects are contained in this database */
12740   const char *zType;  /* Type of the container - used for error messages */
12741   const Token *pName; /* Name of the container - used for error messages */
12742 };
12743 
12744 /*
12745 ** An objected used to accumulate the text of a string where we
12746 ** do not necessarily know how big the string will be in the end.
12747 */
12748 struct StrAccum {
12749   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
12750   char *zBase;         /* A base allocation.  Not from malloc. */
12751   char *zText;         /* The string collected so far */
12752   int  nChar;          /* Length of the string so far */
12753   int  nAlloc;         /* Amount of space allocated in zText */
12754   int  mxAlloc;        /* Maximum allowed allocation.  0 for no malloc usage */
12755   u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
12756 };
12757 #define STRACCUM_NOMEM   1
12758 #define STRACCUM_TOOBIG  2
12759 
12760 /*
12761 ** A pointer to this structure is used to communicate information
12762 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
12763 */
12764 typedef struct {
12765   sqlite3 *db;        /* The database being initialized */
12766   char **pzErrMsg;    /* Error message stored here */
12767   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
12768   int rc;             /* Result code stored here */
12769 } InitData;
12770 
12771 /*
12772 ** Structure containing global configuration data for the SQLite library.
12773 **
12774 ** This structure also contains some state information.
12775 */
12776 struct Sqlite3Config {
12777   int bMemstat;                     /* True to enable memory status */
12778   int bCoreMutex;                   /* True to enable core mutexing */
12779   int bFullMutex;                   /* True to enable full mutexing */
12780   int bOpenUri;                     /* True to interpret filenames as URIs */
12781   int bUseCis;                      /* Use covering indices for full-scans */
12782   int mxStrlen;                     /* Maximum string length */
12783   int neverCorrupt;                 /* Database is always well-formed */
12784   int szLookaside;                  /* Default lookaside buffer size */
12785   int nLookaside;                   /* Default lookaside buffer count */
12786   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
12787   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
12788   sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
12789   void *pHeap;                      /* Heap storage space */
12790   int nHeap;                        /* Size of pHeap[] */
12791   int mnReq, mxReq;                 /* Min and max heap requests sizes */
12792   sqlite3_int64 szMmap;             /* mmap() space per open file */
12793   sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
12794   void *pScratch;                   /* Scratch memory */
12795   int szScratch;                    /* Size of each scratch buffer */
12796   int nScratch;                     /* Number of scratch buffers */
12797   void *pPage;                      /* Page cache memory */
12798   int szPage;                       /* Size of each page in pPage[] */
12799   int nPage;                        /* Number of pages in pPage[] */
12800   int mxParserStack;                /* maximum depth of the parser stack */
12801   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
12802   u32 szPma;                        /* Maximum Sorter PMA size */
12803   /* The above might be initialized to non-zero.  The following need to always
12804   ** initially be zero, however. */
12805   int isInit;                       /* True after initialization has finished */
12806   int inProgress;                   /* True while initialization in progress */
12807   int isMutexInit;                  /* True after mutexes are initialized */
12808   int isMallocInit;                 /* True after malloc is initialized */
12809   int isPCacheInit;                 /* True after malloc is initialized */
12810   int nRefInitMutex;                /* Number of users of pInitMutex */
12811   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
12812   void (*xLog)(void*,int,const char*); /* Function for logging */
12813   void *pLogArg;                       /* First argument to xLog() */
12814 #ifdef SQLITE_ENABLE_SQLLOG
12815   void(*xSqllog)(void*,sqlite3*,const char*, int);
12816   void *pSqllogArg;
12817 #endif
12818 #ifdef SQLITE_VDBE_COVERAGE
12819   /* The following callback (if not NULL) is invoked on every VDBE branch
12820   ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
12821   */
12822   void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx);  /* Callback */
12823   void *pVdbeBranchArg;                                     /* 1st argument */
12824 #endif
12825 #ifndef SQLITE_OMIT_BUILTIN_TEST
12826   int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
12827 #endif
12828   int bLocaltimeFault;              /* True to fail localtime() calls */
12829 };
12830 
12831 /*
12832 ** This macro is used inside of assert() statements to indicate that
12833 ** the assert is only valid on a well-formed database.  Instead of:
12834 **
12835 **     assert( X );
12836 **
12837 ** One writes:
12838 **
12839 **     assert( X || CORRUPT_DB );
12840 **
12841 ** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
12842 ** that the database is definitely corrupt, only that it might be corrupt.
12843 ** For most test cases, CORRUPT_DB is set to false using a special
12844 ** sqlite3_test_control().  This enables assert() statements to prove
12845 ** things that are always true for well-formed databases.
12846 */
12847 #define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
12848 
12849 /*
12850 ** Context pointer passed down through the tree-walk.
12851 */
12852 struct Walker {
12853   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
12854   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
12855   void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
12856   Parse *pParse;                            /* Parser context.  */
12857   int walkerDepth;                          /* Number of subqueries */
12858   u8 eCode;                                 /* A small processing code */
12859   union {                                   /* Extra data for callback */
12860     NameContext *pNC;                          /* Naming context */
12861     int n;                                     /* A counter */
12862     int iCur;                                  /* A cursor number */
12863     SrcList *pSrcList;                         /* FROM clause */
12864     struct SrcCount *pSrcCount;                /* Counting column references */
12865   } u;
12866 };
12867 
12868 /* Forward declarations */
12869 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
12870 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
12871 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
12872 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
12873 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
12874 
12875 /*
12876 ** Return code from the parse-tree walking primitives and their
12877 ** callbacks.
12878 */
12879 #define WRC_Continue    0   /* Continue down into children */
12880 #define WRC_Prune       1   /* Omit children but continue walking siblings */
12881 #define WRC_Abort       2   /* Abandon the tree walk */
12882 
12883 /*
12884 ** An instance of this structure represents a set of one or more CTEs
12885 ** (common table expressions) created by a single WITH clause.
12886 */
12887 struct With {
12888   int nCte;                       /* Number of CTEs in the WITH clause */
12889   With *pOuter;                   /* Containing WITH clause, or NULL */
12890   struct Cte {                    /* For each CTE in the WITH clause.... */
12891     char *zName;                    /* Name of this CTE */
12892     ExprList *pCols;                /* List of explicit column names, or NULL */
12893     Select *pSelect;                /* The definition of this CTE */
12894     const char *zErr;               /* Error message for circular references */
12895   } a[1];
12896 };
12897 
12898 #ifdef SQLITE_DEBUG
12899 /*
12900 ** An instance of the TreeView object is used for printing the content of
12901 ** data structures on sqlite3DebugPrintf() using a tree-like view.
12902 */
12903 struct TreeView {
12904   int iLevel;             /* Which level of the tree we are on */
12905   u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */
12906 };
12907 #endif /* SQLITE_DEBUG */
12908 
12909 /*
12910 ** Assuming zIn points to the first byte of a UTF-8 character,
12911 ** advance zIn to point to the first byte of the next UTF-8 character.
12912 */
12913 #define SQLITE_SKIP_UTF8(zIn) {                        \
12914   if( (*(zIn++))>=0xc0 ){                              \
12915     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
12916   }                                                    \
12917 }
12918 
12919 /*
12920 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
12921 ** the same name but without the _BKPT suffix.  These macros invoke
12922 ** routines that report the line-number on which the error originated
12923 ** using sqlite3_log().  The routines also provide a convenient place
12924 ** to set a debugger breakpoint.
12925 */
12926 SQLITE_PRIVATE int sqlite3CorruptError(int);
12927 SQLITE_PRIVATE int sqlite3MisuseError(int);
12928 SQLITE_PRIVATE int sqlite3CantopenError(int);
12929 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
12930 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
12931 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
12932 
12933 
12934 /*
12935 ** FTS4 is really an extension for FTS3.  It is enabled using the
12936 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
12937 ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
12938 */
12939 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
12940 # define SQLITE_ENABLE_FTS3 1
12941 #endif
12942 
12943 /*
12944 ** The ctype.h header is needed for non-ASCII systems.  It is also
12945 ** needed by FTS3 when FTS3 is included in the amalgamation.
12946 */
12947 #if !defined(SQLITE_ASCII) || \
12948     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
12949 # include <ctype.h>
12950 #endif
12951 
12952 /*
12953 ** The following macros mimic the standard library functions toupper(),
12954 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
12955 ** sqlite versions only work for ASCII characters, regardless of locale.
12956 */
12957 #ifdef SQLITE_ASCII
12958 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
12959 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
12960 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
12961 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
12962 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
12963 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
12964 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
12965 #else
12966 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
12967 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
12968 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
12969 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
12970 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
12971 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
12972 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
12973 #endif
12974 SQLITE_PRIVATE int sqlite3IsIdChar(u8);
12975 
12976 /*
12977 ** Internal function prototypes
12978 */
12979 #define sqlite3StrICmp sqlite3_stricmp
12980 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
12981 #define sqlite3StrNICmp sqlite3_strnicmp
12982 
12983 SQLITE_PRIVATE int sqlite3MallocInit(void);
12984 SQLITE_PRIVATE void sqlite3MallocEnd(void);
12985 SQLITE_PRIVATE void *sqlite3Malloc(u64);
12986 SQLITE_PRIVATE void *sqlite3MallocZero(u64);
12987 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
12988 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
12989 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
12990 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
12991 SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
12992 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
12993 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
12994 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
12995 SQLITE_PRIVATE int sqlite3MallocSize(void*);
12996 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
12997 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
12998 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
12999 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
13000 SQLITE_PRIVATE void sqlite3PageFree(void*);
13001 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
13002 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
13003 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
13004 
13005 /*
13006 ** On systems with ample stack space and that support alloca(), make
13007 ** use of alloca() to obtain space for large automatic objects.  By default,
13008 ** obtain space from malloc().
13009 **
13010 ** The alloca() routine never returns NULL.  This will cause code paths
13011 ** that deal with sqlite3StackAlloc() failures to be unreachable.
13012 */
13013 #ifdef SQLITE_USE_ALLOCA
13014 # define sqlite3StackAllocRaw(D,N)   alloca(N)
13015 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
13016 # define sqlite3StackFree(D,P)
13017 #else
13018 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
13019 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
13020 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
13021 #endif
13022 
13023 #ifdef SQLITE_ENABLE_MEMSYS3
13024 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
13025 #endif
13026 #ifdef SQLITE_ENABLE_MEMSYS5
13027 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
13028 #endif
13029 
13030 
13031 #ifndef SQLITE_MUTEX_OMIT
13032 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
13033 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
13034 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
13035 SQLITE_PRIVATE   int sqlite3MutexInit(void);
13036 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
13037 #endif
13038 
13039 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
13040 SQLITE_PRIVATE void sqlite3StatusUp(int, int);
13041 SQLITE_PRIVATE void sqlite3StatusDown(int, int);
13042 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
13043 
13044 /* Access to mutexes used by sqlite3_status() */
13045 SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
13046 SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
13047 
13048 #ifndef SQLITE_OMIT_FLOATING_POINT
13049 SQLITE_PRIVATE   int sqlite3IsNaN(double);
13050 #else
13051 # define sqlite3IsNaN(X)  0
13052 #endif
13053 
13054 /*
13055 ** An instance of the following structure holds information about SQL
13056 ** functions arguments that are the parameters to the printf() function.
13057 */
13058 struct PrintfArguments {
13059   int nArg;                /* Total number of arguments */
13060   int nUsed;               /* Number of arguments used so far */
13061   sqlite3_value **apArg;   /* The argument values */
13062 };
13063 
13064 #define SQLITE_PRINTF_INTERNAL 0x01
13065 #define SQLITE_PRINTF_SQLFUNC  0x02
13066 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
13067 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
13068 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
13069 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
13070 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
13071 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
13072 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
13073 #endif
13074 #if defined(SQLITE_TEST)
13075 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
13076 #endif
13077 
13078 #if defined(SQLITE_DEBUG)
13079 SQLITE_PRIVATE   TreeView *sqlite3TreeViewPush(TreeView*,u8);
13080 SQLITE_PRIVATE   void sqlite3TreeViewPop(TreeView*);
13081 SQLITE_PRIVATE   void sqlite3TreeViewLine(TreeView*, const char*, ...);
13082 SQLITE_PRIVATE   void sqlite3TreeViewItem(TreeView*, const char*, u8);
13083 SQLITE_PRIVATE   void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
13084 SQLITE_PRIVATE   void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
13085 SQLITE_PRIVATE   void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
13086 #endif
13087 
13088 
13089 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
13090 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
13091 SQLITE_PRIVATE int sqlite3Dequote(char*);
13092 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
13093 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
13094 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
13095 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
13096 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
13097 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
13098 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
13099 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
13100 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
13101 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
13102 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
13103 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
13104 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
13105 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
13106 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
13107 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
13108 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
13109 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
13110 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
13111 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
13112 SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
13113 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
13114 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
13115 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
13116 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
13117 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
13118 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
13119 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
13120 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
13121 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
13122 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
13123 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
13124 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
13125 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
13126 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
13127 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
13128 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
13129 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
13130 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
13131 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
13132 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
13133 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
13134 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
13135                     sqlite3_vfs**,char**,char **);
13136 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
13137 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
13138 
13139 #ifdef SQLITE_OMIT_BUILTIN_TEST
13140 # define sqlite3FaultSim(X) SQLITE_OK
13141 #else
13142 SQLITE_PRIVATE   int sqlite3FaultSim(int);
13143 #endif
13144 
13145 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
13146 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
13147 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
13148 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
13149 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
13150 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
13151 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
13152 
13153 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
13154 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
13155 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
13156 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
13157 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
13158 
13159 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
13160 
13161 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
13162 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
13163 #else
13164 # define sqlite3ViewGetColumnNames(A,B) 0
13165 #endif
13166 
13167 #if SQLITE_MAX_ATTACHED>30
13168 SQLITE_PRIVATE   int sqlite3DbMaskAllZero(yDbMask);
13169 #endif
13170 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
13171 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
13172 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
13173 #ifndef SQLITE_OMIT_AUTOINCREMENT
13174 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
13175 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
13176 #else
13177 # define sqlite3AutoincrementBegin(X)
13178 # define sqlite3AutoincrementEnd(X)
13179 #endif
13180 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
13181 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
13182 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
13183 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
13184 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
13185 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
13186 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
13187                                       Token*, Select*, Expr*, IdList*);
13188 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
13189 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
13190 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
13191 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
13192 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
13193 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
13194 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
13195 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
13196                           Expr*, int, int);
13197 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
13198 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
13199 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
13200                          Expr*,ExprList*,u16,Expr*,Expr*);
13201 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
13202 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
13203 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
13204 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
13205 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
13206 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
13207 #endif
13208 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
13209 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
13210 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
13211 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
13212 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
13213 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
13214 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
13215 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
13216 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
13217 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
13218 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
13219 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
13220 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
13221 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
13222 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
13223 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
13224 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
13225 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
13226 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
13227 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
13228 SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
13229 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
13230 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
13231 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
13232 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
13233 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
13234 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
13235 #define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
13236 #define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
13237 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
13238 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
13239 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
13240 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
13241 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
13242 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
13243 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
13244 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
13245 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
13246 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
13247 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
13248 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
13249 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
13250 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
13251 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
13252 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
13253 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
13254 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
13255 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
13256 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
13257 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
13258 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
13259 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
13260 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
13261 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
13262 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
13263 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
13264 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
13265 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
13266 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
13267 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
13268 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
13269 SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
13270 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
13271 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
13272 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
13273 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
13274 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
13275 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
13276 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
13277 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
13278 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
13279                                      u8,u8,int,int*);
13280 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
13281 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
13282 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
13283 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
13284 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
13285 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
13286 SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
13287 SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
13288 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
13289 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
13290 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
13291 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
13292 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
13293 #if SELECTTRACE_ENABLED
13294 SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
13295 #else
13296 # define sqlite3SelectSetName(A,B)
13297 #endif
13298 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
13299 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
13300 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
13301 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
13302 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
13303 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
13304 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
13305 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
13306 
13307 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
13308 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
13309 #endif
13310 
13311 #ifndef SQLITE_OMIT_TRIGGER
13312 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
13313                            Expr*,int, int);
13314 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
13315 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
13316 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
13317 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
13318 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
13319 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
13320                             int, int, int);
13321 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
13322   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
13323 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
13324 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
13325 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
13326                                         Select*,u8);
13327 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
13328 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
13329 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
13330 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
13331 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
13332 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
13333 #else
13334 # define sqlite3TriggersExist(B,C,D,E,F) 0
13335 # define sqlite3DeleteTrigger(A,B)
13336 # define sqlite3DropTriggerPtr(A,B)
13337 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
13338 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
13339 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
13340 # define sqlite3TriggerList(X, Y) 0
13341 # define sqlite3ParseToplevel(p) p
13342 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
13343 #endif
13344 
13345 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
13346 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
13347 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
13348 #ifndef SQLITE_OMIT_AUTHORIZATION
13349 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
13350 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
13351 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
13352 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
13353 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
13354 #else
13355 # define sqlite3AuthRead(a,b,c,d)
13356 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
13357 # define sqlite3AuthContextPush(a,b,c)
13358 # define sqlite3AuthContextPop(a)  ((void)(a))
13359 #endif
13360 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
13361 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
13362 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
13363 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
13364 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
13365 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
13366 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
13367 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
13368 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
13369 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
13370 SQLITE_PRIVATE int sqlite3Atoi(const char*);
13371 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
13372 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
13373 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
13374 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
13375 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
13376 #ifndef SQLITE_OMIT_VIRTUALTABLE
13377 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
13378 #endif
13379 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
13380 
13381 /*
13382 ** Routines to read and write variable-length integers.  These used to
13383 ** be defined locally, but now we use the varint routines in the util.c
13384 ** file.
13385 */
13386 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
13387 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
13388 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
13389 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
13390 
13391 /*
13392 ** The common case is for a varint to be a single byte.  They following
13393 ** macros handle the common case without a procedure call, but then call
13394 ** the procedure for larger varints.
13395 */
13396 #define getVarint32(A,B)  \
13397   (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
13398 #define putVarint32(A,B)  \
13399   (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
13400   sqlite3PutVarint((A),(B)))
13401 #define getVarint    sqlite3GetVarint
13402 #define putVarint    sqlite3PutVarint
13403 
13404 
13405 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
13406 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
13407 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
13408 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
13409 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
13410 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
13411 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
13412 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
13413 SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
13414 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
13415 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
13416 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
13417 
13418 #if defined(SQLITE_NEED_ERR_NAME)
13419 SQLITE_PRIVATE const char *sqlite3ErrName(int);
13420 #endif
13421 
13422 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
13423 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
13424 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
13425 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
13426 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
13427 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
13428 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
13429 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
13430 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
13431 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
13432 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
13433 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
13434 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
13435 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
13436 SQLITE_PRIVATE int sqlite3AbsInt32(int);
13437 #ifdef SQLITE_ENABLE_8_3_NAMES
13438 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
13439 #else
13440 # define sqlite3FileSuffix3(X,Y)
13441 #endif
13442 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
13443 
13444 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
13445 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
13446 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
13447                         void(*)(void*));
13448 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
13449 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
13450 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
13451 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
13452 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
13453 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
13454 #ifndef SQLITE_AMALGAMATION
13455 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
13456 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
13457 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
13458 SQLITE_PRIVATE const Token sqlite3IntTokens[];
13459 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
13460 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
13461 #ifndef SQLITE_OMIT_WSD
13462 SQLITE_PRIVATE int sqlite3PendingByte;
13463 #endif
13464 #endif
13465 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
13466 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
13467 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
13468 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
13469 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
13470 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
13471 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
13472 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
13473 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
13474 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
13475 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
13476 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
13477 SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
13478 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
13479 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
13480 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
13481 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
13482 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
13483 SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
13484 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
13485 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
13486 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
13487 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
13488 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
13489 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
13490 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
13491 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
13492 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
13493 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
13494 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
13495 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
13496 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
13497 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
13498 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
13499 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
13500 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
13501 #ifdef SQLITE_DEBUG
13502 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
13503 #endif
13504 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
13505   void (*)(sqlite3_context*,int,sqlite3_value **),
13506   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
13507   FuncDestructor *pDestructor
13508 );
13509 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
13510 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
13511 
13512 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
13513 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
13514 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
13515 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
13516 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
13517 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
13518 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
13519 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
13520 
13521 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
13522 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
13523 
13524 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
13525 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
13526 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
13527 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
13528 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
13529 SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
13530 #endif
13531 
13532 /*
13533 ** The interface to the LEMON-generated parser
13534 */
13535 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
13536 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
13537 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
13538 #ifdef YYTRACKMAXSTACKDEPTH
13539 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
13540 #endif
13541 
13542 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
13543 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13544 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
13545 #else
13546 # define sqlite3CloseExtensions(X)
13547 #endif
13548 
13549 #ifndef SQLITE_OMIT_SHARED_CACHE
13550 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
13551 #else
13552   #define sqlite3TableLock(v,w,x,y,z)
13553 #endif
13554 
13555 #ifdef SQLITE_TEST
13556 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
13557 #endif
13558 
13559 #ifdef SQLITE_OMIT_VIRTUALTABLE
13560 #  define sqlite3VtabClear(Y)
13561 #  define sqlite3VtabSync(X,Y) SQLITE_OK
13562 #  define sqlite3VtabRollback(X)
13563 #  define sqlite3VtabCommit(X)
13564 #  define sqlite3VtabInSync(db) 0
13565 #  define sqlite3VtabLock(X)
13566 #  define sqlite3VtabUnlock(X)
13567 #  define sqlite3VtabUnlockList(X)
13568 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
13569 #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
13570 #else
13571 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
13572 SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
13573 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
13574 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
13575 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
13576 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
13577 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
13578 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
13579 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
13580 SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
13581 SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
13582 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
13583 #endif
13584 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
13585 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
13586 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
13587 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
13588 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
13589 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
13590 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
13591 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
13592 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
13593 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
13594 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
13595 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
13596 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
13597 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
13598 SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
13599 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
13600 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
13601 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
13602 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
13603 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
13604 #ifndef SQLITE_OMIT_WAL
13605 SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
13606 SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
13607 #endif
13608 #ifndef SQLITE_OMIT_CTE
13609 SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
13610 SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
13611 SQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);
13612 #else
13613 #define sqlite3WithPush(x,y,z)
13614 #define sqlite3WithDelete(x,y)
13615 #endif
13616 
13617 /* Declarations for functions in fkey.c. All of these are replaced by
13618 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
13619 ** key functionality is available. If OMIT_TRIGGER is defined but
13620 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
13621 ** this case foreign keys are parsed, but no other functionality is
13622 ** provided (enforcement of FK constraints requires the triggers sub-system).
13623 */
13624 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
13625 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
13626 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
13627 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
13628 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
13629 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
13630 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
13631 #else
13632   #define sqlite3FkActions(a,b,c,d,e,f)
13633   #define sqlite3FkCheck(a,b,c,d,e,f)
13634   #define sqlite3FkDropTable(a,b,c)
13635   #define sqlite3FkOldmask(a,b)         0
13636   #define sqlite3FkRequired(a,b,c,d)    0
13637 #endif
13638 #ifndef SQLITE_OMIT_FOREIGN_KEY
13639 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
13640 SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
13641 #else
13642   #define sqlite3FkDelete(a,b)
13643   #define sqlite3FkLocateIndex(a,b,c,d,e)
13644 #endif
13645 
13646 
13647 /*
13648 ** Available fault injectors.  Should be numbered beginning with 0.
13649 */
13650 #define SQLITE_FAULTINJECTOR_MALLOC     0
13651 #define SQLITE_FAULTINJECTOR_COUNT      1
13652 
13653 /*
13654 ** The interface to the code in fault.c used for identifying "benign"
13655 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
13656 ** is not defined.
13657 */
13658 #ifndef SQLITE_OMIT_BUILTIN_TEST
13659 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
13660 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
13661 #else
13662   #define sqlite3BeginBenignMalloc()
13663   #define sqlite3EndBenignMalloc()
13664 #endif
13665 
13666 /*
13667 ** Allowed return values from sqlite3FindInIndex()
13668 */
13669 #define IN_INDEX_ROWID        1   /* Search the rowid of the table */
13670 #define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */
13671 #define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */
13672 #define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */
13673 #define IN_INDEX_NOOP         5   /* No table available. Use comparisons */
13674 /*
13675 ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
13676 */
13677 #define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
13678 #define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
13679 #define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
13680 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
13681 
13682 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
13683 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
13684 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
13685 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
13686 SQLITE_PRIVATE   int sqlite3JournalExists(sqlite3_file *p);
13687 #else
13688   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
13689   #define sqlite3JournalExists(p) 1
13690 #endif
13691 
13692 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
13693 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
13694 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
13695 
13696 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
13697 #if SQLITE_MAX_EXPR_DEPTH>0
13698 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
13699 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
13700 #else
13701   #define sqlite3SelectExprHeight(x) 0
13702   #define sqlite3ExprCheckHeight(x,y)
13703 #endif
13704 
13705 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
13706 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
13707 
13708 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13709 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
13710 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
13711 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
13712 #else
13713   #define sqlite3ConnectionBlocked(x,y)
13714   #define sqlite3ConnectionUnlocked(x)
13715   #define sqlite3ConnectionClosed(x)
13716 #endif
13717 
13718 #ifdef SQLITE_DEBUG
13719 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
13720 #endif
13721 
13722 /*
13723 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
13724 ** sqlite3IoTrace is a pointer to a printf-like routine used to
13725 ** print I/O tracing messages.
13726 */
13727 #ifdef SQLITE_ENABLE_IOTRACE
13728 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
13729 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
13730 SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
13731 #else
13732 # define IOTRACE(A)
13733 # define sqlite3VdbeIOTraceSql(X)
13734 #endif
13735 
13736 /*
13737 ** These routines are available for the mem2.c debugging memory allocator
13738 ** only.  They are used to verify that different "types" of memory
13739 ** allocations are properly tracked by the system.
13740 **
13741 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
13742 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
13743 ** a single bit set.
13744 **
13745 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
13746 ** argument match the type set by the previous sqlite3MemdebugSetType().
13747 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
13748 **
13749 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
13750 ** argument match the type set by the previous sqlite3MemdebugSetType().
13751 **
13752 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
13753 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
13754 ** it might have been allocated by lookaside, except the allocation was
13755 ** too large or lookaside was already full.  It is important to verify
13756 ** that allocations that might have been satisfied by lookaside are not
13757 ** passed back to non-lookaside free() routines.  Asserts such as the
13758 ** example above are placed on the non-lookaside free() routines to verify
13759 ** this constraint.
13760 **
13761 ** All of this is no-op for a production build.  It only comes into
13762 ** play when the SQLITE_MEMDEBUG compile-time option is used.
13763 */
13764 #ifdef SQLITE_MEMDEBUG
13765 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
13766 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
13767 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
13768 #else
13769 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
13770 # define sqlite3MemdebugHasType(X,Y)  1
13771 # define sqlite3MemdebugNoType(X,Y)   1
13772 #endif
13773 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
13774 #define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */
13775 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
13776 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
13777 
13778 /*
13779 ** Threading interface
13780 */
13781 #if SQLITE_MAX_WORKER_THREADS>0
13782 SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
13783 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
13784 #endif
13785 
13786 #endif /* _SQLITEINT_H_ */
13787 
13788 /************** End of sqliteInt.h *******************************************/
13789 /************** Begin file global.c ******************************************/
13790 /*
13791 ** 2008 June 13
13792 **
13793 ** The author disclaims copyright to this source code.  In place of
13794 ** a legal notice, here is a blessing:
13795 **
13796 **    May you do good and not evil.
13797 **    May you find forgiveness for yourself and forgive others.
13798 **    May you share freely, never taking more than you give.
13799 **
13800 *************************************************************************
13801 **
13802 ** This file contains definitions of global variables and constants.
13803 */
13804 
13805 /* An array to map all upper-case characters into their corresponding
13806 ** lower-case character.
13807 **
13808 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
13809 ** handle case conversions for the UTF character set since the tables
13810 ** involved are nearly as big or bigger than SQLite itself.
13811 */
13812 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
13813 #ifdef SQLITE_ASCII
13814       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
13815      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
13816      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
13817      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
13818     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
13819     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
13820     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
13821     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
13822     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
13823     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
13824     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
13825     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
13826     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
13827     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
13828     252,253,254,255
13829 #endif
13830 #ifdef SQLITE_EBCDIC
13831       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
13832      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
13833      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
13834      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
13835      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
13836      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
13837      96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
13838     112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
13839     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
13840     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
13841     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
13842     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
13843     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
13844     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
13845     224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
13846     240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
13847 #endif
13848 };
13849 
13850 /*
13851 ** The following 256 byte lookup table is used to support SQLites built-in
13852 ** equivalents to the following standard library functions:
13853 **
13854 **   isspace()                        0x01
13855 **   isalpha()                        0x02
13856 **   isdigit()                        0x04
13857 **   isalnum()                        0x06
13858 **   isxdigit()                       0x08
13859 **   toupper()                        0x20
13860 **   SQLite identifier character      0x40
13861 **
13862 ** Bit 0x20 is set if the mapped character requires translation to upper
13863 ** case. i.e. if the character is a lower-case ASCII character.
13864 ** If x is a lower-case ASCII character, then its upper-case equivalent
13865 ** is (x - 0x20). Therefore toupper() can be implemented as:
13866 **
13867 **   (x & ~(map[x]&0x20))
13868 **
13869 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
13870 ** array. tolower() is used more often than toupper() by SQLite.
13871 **
13872 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
13873 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
13874 ** non-ASCII UTF character. Hence the test for whether or not a character is
13875 ** part of an identifier is 0x46.
13876 **
13877 ** SQLite's versions are identical to the standard versions assuming a
13878 ** locale of "C". They are implemented as macros in sqliteInt.h.
13879 */
13880 #ifdef SQLITE_ASCII
13881 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
13882   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
13883   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
13884   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
13885   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
13886   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
13887   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
13888   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
13889   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
13890 
13891   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
13892   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
13893   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
13894   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
13895   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
13896   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
13897   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
13898   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
13899 
13900   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
13901   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
13902   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
13903   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
13904   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
13905   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
13906   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
13907   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
13908 
13909   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
13910   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
13911   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
13912   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
13913   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
13914   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
13915   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
13916   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
13917 };
13918 #endif
13919 
13920 /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
13921 ** compatibility for legacy applications, the URI filename capability is
13922 ** disabled by default.
13923 **
13924 ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
13925 ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
13926 **
13927 ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
13928 ** disabled. The default value may be changed by compiling with the
13929 ** SQLITE_USE_URI symbol defined.
13930 */
13931 #ifndef SQLITE_USE_URI
13932 # define  SQLITE_USE_URI 0
13933 #endif
13934 
13935 /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
13936 ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
13937 ** that compile-time option is omitted.
13938 */
13939 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
13940 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
13941 #endif
13942 
13943 /* The minimum PMA size is set to this value multiplied by the database
13944 ** page size in bytes.
13945 */
13946 #ifndef SQLITE_SORTER_PMASZ
13947 # define SQLITE_SORTER_PMASZ 250
13948 #endif
13949 
13950 /*
13951 ** The following singleton contains the global configuration for
13952 ** the SQLite library.
13953 */
13954 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
13955    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
13956    1,                         /* bCoreMutex */
13957    SQLITE_THREADSAFE==1,      /* bFullMutex */
13958    SQLITE_USE_URI,            /* bOpenUri */
13959    SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
13960    0x7ffffffe,                /* mxStrlen */
13961    0,                         /* neverCorrupt */
13962    128,                       /* szLookaside */
13963    500,                       /* nLookaside */
13964    {0,0,0,0,0,0,0,0},         /* m */
13965    {0,0,0,0,0,0,0,0,0},       /* mutex */
13966    {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
13967    (void*)0,                  /* pHeap */
13968    0,                         /* nHeap */
13969    0, 0,                      /* mnHeap, mxHeap */
13970    SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
13971    SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
13972    (void*)0,                  /* pScratch */
13973    0,                         /* szScratch */
13974    0,                         /* nScratch */
13975    (void*)0,                  /* pPage */
13976    0,                         /* szPage */
13977    0,                         /* nPage */
13978    0,                         /* mxParserStack */
13979    0,                         /* sharedCacheEnabled */
13980    SQLITE_SORTER_PMASZ,       /* szPma */
13981    /* All the rest should always be initialized to zero */
13982    0,                         /* isInit */
13983    0,                         /* inProgress */
13984    0,                         /* isMutexInit */
13985    0,                         /* isMallocInit */
13986    0,                         /* isPCacheInit */
13987    0,                         /* nRefInitMutex */
13988    0,                         /* pInitMutex */
13989    0,                         /* xLog */
13990    0,                         /* pLogArg */
13991 #ifdef SQLITE_ENABLE_SQLLOG
13992    0,                         /* xSqllog */
13993    0,                         /* pSqllogArg */
13994 #endif
13995 #ifdef SQLITE_VDBE_COVERAGE
13996    0,                         /* xVdbeBranch */
13997    0,                         /* pVbeBranchArg */
13998 #endif
13999 #ifndef SQLITE_OMIT_BUILTIN_TEST
14000    0,                         /* xTestCallback */
14001 #endif
14002    0                          /* bLocaltimeFault */
14003 };
14004 
14005 /*
14006 ** Hash table for global functions - functions common to all
14007 ** database connections.  After initialization, this table is
14008 ** read-only.
14009 */
14010 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
14011 
14012 /*
14013 ** Constant tokens for values 0 and 1.
14014 */
14015 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
14016    { "0", 1 },
14017    { "1", 1 }
14018 };
14019 
14020 
14021 /*
14022 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
14023 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
14024 ** the database page that contains the pending byte.  It never attempts
14025 ** to read or write that page.  The pending byte page is set assign
14026 ** for use by the VFS layers as space for managing file locks.
14027 **
14028 ** During testing, it is often desirable to move the pending byte to
14029 ** a different position in the file.  This allows code that has to
14030 ** deal with the pending byte to run on files that are much smaller
14031 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
14032 ** move the pending byte.
14033 **
14034 ** IMPORTANT:  Changing the pending byte to any value other than
14035 ** 0x40000000 results in an incompatible database file format!
14036 ** Changing the pending byte during operation will result in undefined
14037 ** and incorrect behavior.
14038 */
14039 #ifndef SQLITE_OMIT_WSD
14040 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
14041 #endif
14042 
14043 /*
14044 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
14045 ** created by mkopcodeh.awk during compilation.  Data is obtained
14046 ** from the comments following the "case OP_xxxx:" statements in
14047 ** the vdbe.c file.
14048 */
14049 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
14050 
14051 /************** End of global.c **********************************************/
14052 /************** Begin file ctime.c *******************************************/
14053 /*
14054 ** 2010 February 23
14055 **
14056 ** The author disclaims copyright to this source code.  In place of
14057 ** a legal notice, here is a blessing:
14058 **
14059 **    May you do good and not evil.
14060 **    May you find forgiveness for yourself and forgive others.
14061 **    May you share freely, never taking more than you give.
14062 **
14063 *************************************************************************
14064 **
14065 ** This file implements routines used to report what compile-time options
14066 ** SQLite was built with.
14067 */
14068 
14069 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
14070 
14071 
14072 /*
14073 ** An array of names of all compile-time options.  This array should
14074 ** be sorted A-Z.
14075 **
14076 ** This array looks large, but in a typical installation actually uses
14077 ** only a handful of compile-time options, so most times this array is usually
14078 ** rather short and uses little memory space.
14079 */
14080 static const char * const azCompileOpt[] = {
14081 
14082 /* These macros are provided to "stringify" the value of the define
14083 ** for those options in which the value is meaningful. */
14084 #define CTIMEOPT_VAL_(opt) #opt
14085 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
14086 
14087 #if SQLITE_32BIT_ROWID
14088   "32BIT_ROWID",
14089 #endif
14090 #if SQLITE_4_BYTE_ALIGNED_MALLOC
14091   "4_BYTE_ALIGNED_MALLOC",
14092 #endif
14093 #if SQLITE_CASE_SENSITIVE_LIKE
14094   "CASE_SENSITIVE_LIKE",
14095 #endif
14096 #if SQLITE_CHECK_PAGES
14097   "CHECK_PAGES",
14098 #endif
14099 #if SQLITE_COVERAGE_TEST
14100   "COVERAGE_TEST",
14101 #endif
14102 #if SQLITE_DEBUG
14103   "DEBUG",
14104 #endif
14105 #if SQLITE_DEFAULT_LOCKING_MODE
14106   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
14107 #endif
14108 #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
14109   "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
14110 #endif
14111 #if SQLITE_DISABLE_DIRSYNC
14112   "DISABLE_DIRSYNC",
14113 #endif
14114 #if SQLITE_DISABLE_LFS
14115   "DISABLE_LFS",
14116 #endif
14117 #if SQLITE_ENABLE_API_ARMOR
14118   "ENABLE_API_ARMOR",
14119 #endif
14120 #if SQLITE_ENABLE_ATOMIC_WRITE
14121   "ENABLE_ATOMIC_WRITE",
14122 #endif
14123 #if SQLITE_ENABLE_CEROD
14124   "ENABLE_CEROD",
14125 #endif
14126 #if SQLITE_ENABLE_COLUMN_METADATA
14127   "ENABLE_COLUMN_METADATA",
14128 #endif
14129 #if SQLITE_ENABLE_DBSTAT_VTAB
14130   "ENABLE_DBSTAT_VTAB",
14131 #endif
14132 #if SQLITE_ENABLE_EXPENSIVE_ASSERT
14133   "ENABLE_EXPENSIVE_ASSERT",
14134 #endif
14135 #if SQLITE_ENABLE_FTS1
14136   "ENABLE_FTS1",
14137 #endif
14138 #if SQLITE_ENABLE_FTS2
14139   "ENABLE_FTS2",
14140 #endif
14141 #if SQLITE_ENABLE_FTS3
14142   "ENABLE_FTS3",
14143 #endif
14144 #if SQLITE_ENABLE_FTS3_PARENTHESIS
14145   "ENABLE_FTS3_PARENTHESIS",
14146 #endif
14147 #if SQLITE_ENABLE_FTS4
14148   "ENABLE_FTS4",
14149 #endif
14150 #if SQLITE_ENABLE_ICU
14151   "ENABLE_ICU",
14152 #endif
14153 #if SQLITE_ENABLE_IOTRACE
14154   "ENABLE_IOTRACE",
14155 #endif
14156 #if SQLITE_ENABLE_LOAD_EXTENSION
14157   "ENABLE_LOAD_EXTENSION",
14158 #endif
14159 #if SQLITE_ENABLE_LOCKING_STYLE
14160   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
14161 #endif
14162 #if SQLITE_ENABLE_MEMORY_MANAGEMENT
14163   "ENABLE_MEMORY_MANAGEMENT",
14164 #endif
14165 #if SQLITE_ENABLE_MEMSYS3
14166   "ENABLE_MEMSYS3",
14167 #endif
14168 #if SQLITE_ENABLE_MEMSYS5
14169   "ENABLE_MEMSYS5",
14170 #endif
14171 #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
14172   "ENABLE_OVERSIZE_CELL_CHECK",
14173 #endif
14174 #if SQLITE_ENABLE_RTREE
14175   "ENABLE_RTREE",
14176 #endif
14177 #if defined(SQLITE_ENABLE_STAT4)
14178   "ENABLE_STAT4",
14179 #elif defined(SQLITE_ENABLE_STAT3)
14180   "ENABLE_STAT3",
14181 #endif
14182 #if SQLITE_ENABLE_UNLOCK_NOTIFY
14183   "ENABLE_UNLOCK_NOTIFY",
14184 #endif
14185 #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
14186   "ENABLE_UPDATE_DELETE_LIMIT",
14187 #endif
14188 #if SQLITE_HAS_CODEC
14189   "HAS_CODEC",
14190 #endif
14191 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
14192   "HAVE_ISNAN",
14193 #endif
14194 #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
14195   "HOMEGROWN_RECURSIVE_MUTEX",
14196 #endif
14197 #if SQLITE_IGNORE_AFP_LOCK_ERRORS
14198   "IGNORE_AFP_LOCK_ERRORS",
14199 #endif
14200 #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
14201   "IGNORE_FLOCK_LOCK_ERRORS",
14202 #endif
14203 #ifdef SQLITE_INT64_TYPE
14204   "INT64_TYPE",
14205 #endif
14206 #if SQLITE_LOCK_TRACE
14207   "LOCK_TRACE",
14208 #endif
14209 #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
14210   "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
14211 #endif
14212 #ifdef SQLITE_MAX_SCHEMA_RETRY
14213   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
14214 #endif
14215 #if SQLITE_MEMDEBUG
14216   "MEMDEBUG",
14217 #endif
14218 #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
14219   "MIXED_ENDIAN_64BIT_FLOAT",
14220 #endif
14221 #if SQLITE_NO_SYNC
14222   "NO_SYNC",
14223 #endif
14224 #if SQLITE_OMIT_ALTERTABLE
14225   "OMIT_ALTERTABLE",
14226 #endif
14227 #if SQLITE_OMIT_ANALYZE
14228   "OMIT_ANALYZE",
14229 #endif
14230 #if SQLITE_OMIT_ATTACH
14231   "OMIT_ATTACH",
14232 #endif
14233 #if SQLITE_OMIT_AUTHORIZATION
14234   "OMIT_AUTHORIZATION",
14235 #endif
14236 #if SQLITE_OMIT_AUTOINCREMENT
14237   "OMIT_AUTOINCREMENT",
14238 #endif
14239 #if SQLITE_OMIT_AUTOINIT
14240   "OMIT_AUTOINIT",
14241 #endif
14242 #if SQLITE_OMIT_AUTOMATIC_INDEX
14243   "OMIT_AUTOMATIC_INDEX",
14244 #endif
14245 #if SQLITE_OMIT_AUTORESET
14246   "OMIT_AUTORESET",
14247 #endif
14248 #if SQLITE_OMIT_AUTOVACUUM
14249   "OMIT_AUTOVACUUM",
14250 #endif
14251 #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
14252   "OMIT_BETWEEN_OPTIMIZATION",
14253 #endif
14254 #if SQLITE_OMIT_BLOB_LITERAL
14255   "OMIT_BLOB_LITERAL",
14256 #endif
14257 #if SQLITE_OMIT_BTREECOUNT
14258   "OMIT_BTREECOUNT",
14259 #endif
14260 #if SQLITE_OMIT_BUILTIN_TEST
14261   "OMIT_BUILTIN_TEST",
14262 #endif
14263 #if SQLITE_OMIT_CAST
14264   "OMIT_CAST",
14265 #endif
14266 #if SQLITE_OMIT_CHECK
14267   "OMIT_CHECK",
14268 #endif
14269 #if SQLITE_OMIT_COMPLETE
14270   "OMIT_COMPLETE",
14271 #endif
14272 #if SQLITE_OMIT_COMPOUND_SELECT
14273   "OMIT_COMPOUND_SELECT",
14274 #endif
14275 #if SQLITE_OMIT_CTE
14276   "OMIT_CTE",
14277 #endif
14278 #if SQLITE_OMIT_DATETIME_FUNCS
14279   "OMIT_DATETIME_FUNCS",
14280 #endif
14281 #if SQLITE_OMIT_DECLTYPE
14282   "OMIT_DECLTYPE",
14283 #endif
14284 #if SQLITE_OMIT_DEPRECATED
14285   "OMIT_DEPRECATED",
14286 #endif
14287 #if SQLITE_OMIT_DISKIO
14288   "OMIT_DISKIO",
14289 #endif
14290 #if SQLITE_OMIT_EXPLAIN
14291   "OMIT_EXPLAIN",
14292 #endif
14293 #if SQLITE_OMIT_FLAG_PRAGMAS
14294   "OMIT_FLAG_PRAGMAS",
14295 #endif
14296 #if SQLITE_OMIT_FLOATING_POINT
14297   "OMIT_FLOATING_POINT",
14298 #endif
14299 #if SQLITE_OMIT_FOREIGN_KEY
14300   "OMIT_FOREIGN_KEY",
14301 #endif
14302 #if SQLITE_OMIT_GET_TABLE
14303   "OMIT_GET_TABLE",
14304 #endif
14305 #if SQLITE_OMIT_INCRBLOB
14306   "OMIT_INCRBLOB",
14307 #endif
14308 #if SQLITE_OMIT_INTEGRITY_CHECK
14309   "OMIT_INTEGRITY_CHECK",
14310 #endif
14311 #if SQLITE_OMIT_LIKE_OPTIMIZATION
14312   "OMIT_LIKE_OPTIMIZATION",
14313 #endif
14314 #if SQLITE_OMIT_LOAD_EXTENSION
14315   "OMIT_LOAD_EXTENSION",
14316 #endif
14317 #if SQLITE_OMIT_LOCALTIME
14318   "OMIT_LOCALTIME",
14319 #endif
14320 #if SQLITE_OMIT_LOOKASIDE
14321   "OMIT_LOOKASIDE",
14322 #endif
14323 #if SQLITE_OMIT_MEMORYDB
14324   "OMIT_MEMORYDB",
14325 #endif
14326 #if SQLITE_OMIT_OR_OPTIMIZATION
14327   "OMIT_OR_OPTIMIZATION",
14328 #endif
14329 #if SQLITE_OMIT_PAGER_PRAGMAS
14330   "OMIT_PAGER_PRAGMAS",
14331 #endif
14332 #if SQLITE_OMIT_PRAGMA
14333   "OMIT_PRAGMA",
14334 #endif
14335 #if SQLITE_OMIT_PROGRESS_CALLBACK
14336   "OMIT_PROGRESS_CALLBACK",
14337 #endif
14338 #if SQLITE_OMIT_QUICKBALANCE
14339   "OMIT_QUICKBALANCE",
14340 #endif
14341 #if SQLITE_OMIT_REINDEX
14342   "OMIT_REINDEX",
14343 #endif
14344 #if SQLITE_OMIT_SCHEMA_PRAGMAS
14345   "OMIT_SCHEMA_PRAGMAS",
14346 #endif
14347 #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
14348   "OMIT_SCHEMA_VERSION_PRAGMAS",
14349 #endif
14350 #if SQLITE_OMIT_SHARED_CACHE
14351   "OMIT_SHARED_CACHE",
14352 #endif
14353 #if SQLITE_OMIT_SUBQUERY
14354   "OMIT_SUBQUERY",
14355 #endif
14356 #if SQLITE_OMIT_TCL_VARIABLE
14357   "OMIT_TCL_VARIABLE",
14358 #endif
14359 #if SQLITE_OMIT_TEMPDB
14360   "OMIT_TEMPDB",
14361 #endif
14362 #if SQLITE_OMIT_TRACE
14363   "OMIT_TRACE",
14364 #endif
14365 #if SQLITE_OMIT_TRIGGER
14366   "OMIT_TRIGGER",
14367 #endif
14368 #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
14369   "OMIT_TRUNCATE_OPTIMIZATION",
14370 #endif
14371 #if SQLITE_OMIT_UTF16
14372   "OMIT_UTF16",
14373 #endif
14374 #if SQLITE_OMIT_VACUUM
14375   "OMIT_VACUUM",
14376 #endif
14377 #if SQLITE_OMIT_VIEW
14378   "OMIT_VIEW",
14379 #endif
14380 #if SQLITE_OMIT_VIRTUALTABLE
14381   "OMIT_VIRTUALTABLE",
14382 #endif
14383 #if SQLITE_OMIT_WAL
14384   "OMIT_WAL",
14385 #endif
14386 #if SQLITE_OMIT_WSD
14387   "OMIT_WSD",
14388 #endif
14389 #if SQLITE_OMIT_XFER_OPT
14390   "OMIT_XFER_OPT",
14391 #endif
14392 #if SQLITE_PERFORMANCE_TRACE
14393   "PERFORMANCE_TRACE",
14394 #endif
14395 #if SQLITE_PROXY_DEBUG
14396   "PROXY_DEBUG",
14397 #endif
14398 #if SQLITE_RTREE_INT_ONLY
14399   "RTREE_INT_ONLY",
14400 #endif
14401 #if SQLITE_SECURE_DELETE
14402   "SECURE_DELETE",
14403 #endif
14404 #if SQLITE_SMALL_STACK
14405   "SMALL_STACK",
14406 #endif
14407 #if SQLITE_SOUNDEX
14408   "SOUNDEX",
14409 #endif
14410 #if SQLITE_SYSTEM_MALLOC
14411   "SYSTEM_MALLOC",
14412 #endif
14413 #if SQLITE_TCL
14414   "TCL",
14415 #endif
14416 #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
14417   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
14418 #endif
14419 #if SQLITE_TEST
14420   "TEST",
14421 #endif
14422 #if defined(SQLITE_THREADSAFE)
14423   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
14424 #endif
14425 #if SQLITE_USE_ALLOCA
14426   "USE_ALLOCA",
14427 #endif
14428 #if SQLITE_USER_AUTHENTICATION
14429   "USER_AUTHENTICATION",
14430 #endif
14431 #if SQLITE_WIN32_MALLOC
14432   "WIN32_MALLOC",
14433 #endif
14434 #if SQLITE_ZERO_MALLOC
14435   "ZERO_MALLOC"
14436 #endif
14437 };
14438 
14439 /*
14440 ** Given the name of a compile-time option, return true if that option
14441 ** was used and false if not.
14442 **
14443 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
14444 ** is not required for a match.
14445 */
sqlite3_compileoption_used(const char * zOptName)14446 SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName){
14447   int i, n;
14448 
14449 #if SQLITE_ENABLE_API_ARMOR
14450   if( zOptName==0 ){
14451     (void)SQLITE_MISUSE_BKPT;
14452     return 0;
14453   }
14454 #endif
14455   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
14456   n = sqlite3Strlen30(zOptName);
14457 
14458   /* Since ArraySize(azCompileOpt) is normally in single digits, a
14459   ** linear search is adequate.  No need for a binary search. */
14460   for(i=0; i<ArraySize(azCompileOpt); i++){
14461     if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
14462      && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
14463     ){
14464       return 1;
14465     }
14466   }
14467   return 0;
14468 }
14469 
14470 /*
14471 ** Return the N-th compile-time option string.  If N is out of range,
14472 ** return a NULL pointer.
14473 */
sqlite3_compileoption_get(int N)14474 SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N){
14475   if( N>=0 && N<ArraySize(azCompileOpt) ){
14476     return azCompileOpt[N];
14477   }
14478   return 0;
14479 }
14480 
14481 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
14482 
14483 /************** End of ctime.c ***********************************************/
14484 /************** Begin file status.c ******************************************/
14485 /*
14486 ** 2008 June 18
14487 **
14488 ** The author disclaims copyright to this source code.  In place of
14489 ** a legal notice, here is a blessing:
14490 **
14491 **    May you do good and not evil.
14492 **    May you find forgiveness for yourself and forgive others.
14493 **    May you share freely, never taking more than you give.
14494 **
14495 *************************************************************************
14496 **
14497 ** This module implements the sqlite3_status() interface and related
14498 ** functionality.
14499 */
14500 /************** Include vdbeInt.h in the middle of status.c ******************/
14501 /************** Begin file vdbeInt.h *****************************************/
14502 /*
14503 ** 2003 September 6
14504 **
14505 ** The author disclaims copyright to this source code.  In place of
14506 ** a legal notice, here is a blessing:
14507 **
14508 **    May you do good and not evil.
14509 **    May you find forgiveness for yourself and forgive others.
14510 **    May you share freely, never taking more than you give.
14511 **
14512 *************************************************************************
14513 ** This is the header file for information that is private to the
14514 ** VDBE.  This information used to all be at the top of the single
14515 ** source code file "vdbe.c".  When that file became too big (over
14516 ** 6000 lines long) it was split up into several smaller files and
14517 ** this header information was factored out.
14518 */
14519 #ifndef _VDBEINT_H_
14520 #define _VDBEINT_H_
14521 
14522 /*
14523 ** The maximum number of times that a statement will try to reparse
14524 ** itself before giving up and returning SQLITE_SCHEMA.
14525 */
14526 #ifndef SQLITE_MAX_SCHEMA_RETRY
14527 # define SQLITE_MAX_SCHEMA_RETRY 50
14528 #endif
14529 
14530 /*
14531 ** SQL is translated into a sequence of instructions to be
14532 ** executed by a virtual machine.  Each instruction is an instance
14533 ** of the following structure.
14534 */
14535 typedef struct VdbeOp Op;
14536 
14537 /*
14538 ** Boolean values
14539 */
14540 typedef unsigned Bool;
14541 
14542 /* Opaque type used by code in vdbesort.c */
14543 typedef struct VdbeSorter VdbeSorter;
14544 
14545 /* Opaque type used by the explainer */
14546 typedef struct Explain Explain;
14547 
14548 /* Elements of the linked list at Vdbe.pAuxData */
14549 typedef struct AuxData AuxData;
14550 
14551 /*
14552 ** A cursor is a pointer into a single BTree within a database file.
14553 ** The cursor can seek to a BTree entry with a particular key, or
14554 ** loop over all entries of the Btree.  You can also insert new BTree
14555 ** entries or retrieve the key or data from the entry that the cursor
14556 ** is currently pointing to.
14557 **
14558 ** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
14559 ** A pseudo-table is a single-row table implemented by registers.
14560 **
14561 ** Every cursor that the virtual machine has open is represented by an
14562 ** instance of the following structure.
14563 */
14564 struct VdbeCursor {
14565   BtCursor *pCursor;    /* The cursor structure of the backend */
14566   Btree *pBt;           /* Separate file holding temporary table */
14567   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
14568   int seekResult;       /* Result of previous sqlite3BtreeMoveto() */
14569   int pseudoTableReg;   /* Register holding pseudotable content. */
14570   i16 nField;           /* Number of fields in the header */
14571   u16 nHdrParsed;       /* Number of header fields parsed so far */
14572 #ifdef SQLITE_DEBUG
14573   u8 seekOp;            /* Most recent seek operation on this cursor */
14574 #endif
14575   i8 iDb;               /* Index of cursor database in db->aDb[] (or -1) */
14576   u8 nullRow;           /* True if pointing to a row with no data */
14577   u8 deferredMoveto;    /* A call to sqlite3BtreeMoveto() is needed */
14578   Bool isEphemeral:1;   /* True for an ephemeral table */
14579   Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
14580   Bool isTable:1;       /* True if a table requiring integer keys */
14581   Bool isOrdered:1;     /* True if the underlying table is BTREE_UNORDERED */
14582   Pgno pgnoRoot;        /* Root page of the open btree cursor */
14583   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
14584   i64 seqCount;         /* Sequence counter */
14585   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
14586   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
14587 
14588   /* Cached information about the header for the data record that the
14589   ** cursor is currently pointing to.  Only valid if cacheStatus matches
14590   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
14591   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
14592   ** the cache is out of date.
14593   **
14594   ** aRow might point to (ephemeral) data for the current row, or it might
14595   ** be NULL.
14596   */
14597   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
14598   u32 payloadSize;      /* Total number of bytes in the record */
14599   u32 szRow;            /* Byte available in aRow */
14600   u32 iHdrOffset;       /* Offset to next unparsed byte of the header */
14601   const u8 *aRow;       /* Data for the current row, if all on one page */
14602   u32 *aOffset;         /* Pointer to aType[nField] */
14603   u32 aType[1];         /* Type values for all entries in the record */
14604   /* 2*nField extra array elements allocated for aType[], beyond the one
14605   ** static element declared in the structure.  nField total array slots for
14606   ** aType[] and nField+1 array slots for aOffset[] */
14607 };
14608 typedef struct VdbeCursor VdbeCursor;
14609 
14610 /*
14611 ** When a sub-program is executed (OP_Program), a structure of this type
14612 ** is allocated to store the current value of the program counter, as
14613 ** well as the current memory cell array and various other frame specific
14614 ** values stored in the Vdbe struct. When the sub-program is finished,
14615 ** these values are copied back to the Vdbe from the VdbeFrame structure,
14616 ** restoring the state of the VM to as it was before the sub-program
14617 ** began executing.
14618 **
14619 ** The memory for a VdbeFrame object is allocated and managed by a memory
14620 ** cell in the parent (calling) frame. When the memory cell is deleted or
14621 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
14622 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
14623 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
14624 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
14625 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
14626 ** child frame are released.
14627 **
14628 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
14629 ** set to NULL if the currently executing frame is the main program.
14630 */
14631 typedef struct VdbeFrame VdbeFrame;
14632 struct VdbeFrame {
14633   Vdbe *v;                /* VM this frame belongs to */
14634   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
14635   Op *aOp;                /* Program instructions for parent frame */
14636   i64 *anExec;            /* Event counters from parent frame */
14637   Mem *aMem;              /* Array of memory cells for parent frame */
14638   u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
14639   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
14640   void *token;            /* Copy of SubProgram.token */
14641   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
14642   int nCursor;            /* Number of entries in apCsr */
14643   int pc;                 /* Program Counter in parent (calling) frame */
14644   int nOp;                /* Size of aOp array */
14645   int nMem;               /* Number of entries in aMem */
14646   int nOnceFlag;          /* Number of entries in aOnceFlag */
14647   int nChildMem;          /* Number of memory cells for child frame */
14648   int nChildCsr;          /* Number of cursors for child frame */
14649   int nChange;            /* Statement changes (Vdbe.nChange)     */
14650   int nDbChange;          /* Value of db->nChange */
14651 };
14652 
14653 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
14654 
14655 /*
14656 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
14657 */
14658 #define CACHE_STALE 0
14659 
14660 /*
14661 ** Internally, the vdbe manipulates nearly all SQL values as Mem
14662 ** structures. Each Mem struct may cache multiple representations (string,
14663 ** integer etc.) of the same value.
14664 */
14665 struct Mem {
14666   union MemValue {
14667     double r;           /* Real value used when MEM_Real is set in flags */
14668     i64 i;              /* Integer value used when MEM_Int is set in flags */
14669     int nZero;          /* Used when bit MEM_Zero is set in flags */
14670     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
14671     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
14672     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
14673   } u;
14674   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
14675   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
14676   int n;              /* Number of characters in string value, excluding '\0' */
14677   char *z;            /* String or BLOB value */
14678   /* ShallowCopy only needs to copy the information above */
14679   char *zMalloc;      /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
14680   int szMalloc;       /* Size of the zMalloc allocation */
14681   u32 uTemp;          /* Transient storage for serial_type in OP_MakeRecord */
14682   sqlite3 *db;        /* The associated database connection */
14683   void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
14684 #ifdef SQLITE_DEBUG
14685   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
14686   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
14687 #endif
14688 };
14689 
14690 /* One or more of the following flags are set to indicate the validOK
14691 ** representations of the value stored in the Mem struct.
14692 **
14693 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
14694 ** No other flags may be set in this case.
14695 **
14696 ** If the MEM_Str flag is set then Mem.z points at a string representation.
14697 ** Usually this is encoded in the same unicode encoding as the main
14698 ** database (see below for exceptions). If the MEM_Term flag is also
14699 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
14700 ** flags may coexist with the MEM_Str flag.
14701 */
14702 #define MEM_Null      0x0001   /* Value is NULL */
14703 #define MEM_Str       0x0002   /* Value is a string */
14704 #define MEM_Int       0x0004   /* Value is an integer */
14705 #define MEM_Real      0x0008   /* Value is a real number */
14706 #define MEM_Blob      0x0010   /* Value is a BLOB */
14707 #define MEM_AffMask   0x001f   /* Mask of affinity bits */
14708 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
14709 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
14710 #define MEM_Undefined 0x0080   /* Value is undefined */
14711 #define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
14712 #define MEM_TypeMask  0x01ff   /* Mask of type bits */
14713 
14714 
14715 /* Whenever Mem contains a valid string or blob representation, one of
14716 ** the following flags must be set to determine the memory management
14717 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
14718 ** string is \000 or \u0000 terminated
14719 */
14720 #define MEM_Term      0x0200   /* String rep is nul terminated */
14721 #define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */
14722 #define MEM_Static    0x0800   /* Mem.z points to a static string */
14723 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
14724 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
14725 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
14726 #ifdef SQLITE_OMIT_INCRBLOB
14727   #undef MEM_Zero
14728   #define MEM_Zero 0x0000
14729 #endif
14730 
14731 /*
14732 ** Clear any existing type flags from a Mem and replace them with f
14733 */
14734 #define MemSetTypeFlag(p, f) \
14735    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
14736 
14737 /*
14738 ** Return true if a memory cell is not marked as invalid.  This macro
14739 ** is for use inside assert() statements only.
14740 */
14741 #ifdef SQLITE_DEBUG
14742 #define memIsValid(M)  ((M)->flags & MEM_Undefined)==0
14743 #endif
14744 
14745 /*
14746 ** Each auxiliary data pointer stored by a user defined function
14747 ** implementation calling sqlite3_set_auxdata() is stored in an instance
14748 ** of this structure. All such structures associated with a single VM
14749 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
14750 ** when the VM is halted (if not before).
14751 */
14752 struct AuxData {
14753   int iOp;                        /* Instruction number of OP_Function opcode */
14754   int iArg;                       /* Index of function argument. */
14755   void *pAux;                     /* Aux data pointer */
14756   void (*xDelete)(void *);        /* Destructor for the aux data */
14757   AuxData *pNext;                 /* Next element in list */
14758 };
14759 
14760 /*
14761 ** The "context" argument for an installable function.  A pointer to an
14762 ** instance of this structure is the first argument to the routines used
14763 ** implement the SQL functions.
14764 **
14765 ** There is a typedef for this structure in sqlite.h.  So all routines,
14766 ** even the public interface to SQLite, can use a pointer to this structure.
14767 ** But this file is the only place where the internal details of this
14768 ** structure are known.
14769 **
14770 ** This structure is defined inside of vdbeInt.h because it uses substructures
14771 ** (Mem) which are only defined there.
14772 */
14773 struct sqlite3_context {
14774   Mem *pOut;            /* The return value is stored here */
14775   FuncDef *pFunc;       /* Pointer to function information */
14776   Mem *pMem;            /* Memory cell used to store aggregate context */
14777   Vdbe *pVdbe;          /* The VM that owns this context */
14778   int iOp;              /* Instruction number of OP_Function */
14779   int isError;          /* Error code returned by the function. */
14780   u8 skipFlag;          /* Skip accumulator loading if true */
14781   u8 fErrorOrAux;       /* isError!=0 or pVdbe->pAuxData modified */
14782 };
14783 
14784 /*
14785 ** An Explain object accumulates indented output which is helpful
14786 ** in describing recursive data structures.
14787 */
14788 struct Explain {
14789   Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
14790   StrAccum str;      /* The string being accumulated */
14791   int nIndent;       /* Number of elements in aIndent */
14792   u16 aIndent[100];  /* Levels of indentation */
14793   char zBase[100];   /* Initial space */
14794 };
14795 
14796 /* A bitfield type for use inside of structures.  Always follow with :N where
14797 ** N is the number of bits.
14798 */
14799 typedef unsigned bft;  /* Bit Field Type */
14800 
14801 typedef struct ScanStatus ScanStatus;
14802 struct ScanStatus {
14803   int addrExplain;                /* OP_Explain for loop */
14804   int addrLoop;                   /* Address of "loops" counter */
14805   int addrVisit;                  /* Address of "rows visited" counter */
14806   int iSelectID;                  /* The "Select-ID" for this loop */
14807   LogEst nEst;                    /* Estimated output rows per loop */
14808   char *zName;                    /* Name of table or index */
14809 };
14810 
14811 /*
14812 ** An instance of the virtual machine.  This structure contains the complete
14813 ** state of the virtual machine.
14814 **
14815 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
14816 ** is really a pointer to an instance of this structure.
14817 */
14818 struct Vdbe {
14819   sqlite3 *db;            /* The database connection that owns this statement */
14820   Op *aOp;                /* Space to hold the virtual machine's program */
14821   Mem *aMem;              /* The memory locations */
14822   Mem **apArg;            /* Arguments to currently executing user function */
14823   Mem *aColName;          /* Column names to return */
14824   Mem *pResultSet;        /* Pointer to an array of results */
14825   Parse *pParse;          /* Parsing context used to create this Vdbe */
14826   int nMem;               /* Number of memory locations currently allocated */
14827   int nOp;                /* Number of instructions in the program */
14828   int nCursor;            /* Number of slots in apCsr[] */
14829   u32 magic;              /* Magic number for sanity checking */
14830   char *zErrMsg;          /* Error message written here */
14831   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
14832   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
14833   Mem *aVar;              /* Values for the OP_Variable opcode. */
14834   char **azVar;           /* Name of variables */
14835   ynVar nVar;             /* Number of entries in aVar[] */
14836   ynVar nzVar;            /* Number of entries in azVar[] */
14837   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
14838   int pc;                 /* The program counter */
14839   int rc;                 /* Value to return */
14840 #ifdef SQLITE_DEBUG
14841   int rcApp;              /* errcode set by sqlite3_result_error_code() */
14842 #endif
14843   u16 nResColumn;         /* Number of columns in one row of the result set */
14844   u8 errorAction;         /* Recovery action to do in case of an error */
14845   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
14846   bft explain:2;          /* True if EXPLAIN present on SQL command */
14847   bft changeCntOn:1;      /* True to update the change-counter */
14848   bft expired:1;          /* True if the VM needs to be recompiled */
14849   bft runOnlyOnce:1;      /* Automatically expire on reset */
14850   bft usesStmtJournal:1;  /* True if uses a statement journal */
14851   bft readOnly:1;         /* True for statements that do not write */
14852   bft bIsReader:1;        /* True for statements that read */
14853   bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
14854   bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
14855   int nChange;            /* Number of db changes made since last reset */
14856   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
14857   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
14858   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
14859   u32 aCounter[5];        /* Counters used by sqlite3_stmt_status() */
14860 #ifndef SQLITE_OMIT_TRACE
14861   i64 startTime;          /* Time when query started - used for profiling */
14862 #endif
14863   i64 iCurrentTime;       /* Value of julianday('now') for this statement */
14864   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
14865   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
14866   i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
14867   char *zSql;             /* Text of the SQL statement that generated this */
14868   void *pFree;            /* Free this when deleting the vdbe */
14869   VdbeFrame *pFrame;      /* Parent frame */
14870   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
14871   int nFrame;             /* Number of frames in pFrame list */
14872   u32 expmask;            /* Binding to these vars invalidates VM */
14873   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
14874   int nOnceFlag;          /* Size of array aOnceFlag[] */
14875   u8 *aOnceFlag;          /* Flags for OP_Once */
14876   AuxData *pAuxData;      /* Linked list of auxdata allocations */
14877 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
14878   i64 *anExec;            /* Number of times each op has been executed */
14879   int nScan;              /* Entries in aScan[] */
14880   ScanStatus *aScan;      /* Scan definitions for sqlite3_stmt_scanstatus() */
14881 #endif
14882 };
14883 
14884 /*
14885 ** The following are allowed values for Vdbe.magic
14886 */
14887 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
14888 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
14889 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
14890 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
14891 
14892 /*
14893 ** Function prototypes
14894 */
14895 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
14896 void sqliteVdbePopStack(Vdbe*,int);
14897 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
14898 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
14899 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
14900 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
14901 #endif
14902 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
14903 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
14904 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
14905 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
14906 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
14907 
14908 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
14909 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
14910 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
14911 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
14912 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
14913 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
14914 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
14915 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
14916 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
14917 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
14918 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
14919 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
14920 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
14921 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
14922 #ifdef SQLITE_OMIT_FLOATING_POINT
14923 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
14924 #else
14925 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
14926 #endif
14927 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
14928 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
14929 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
14930 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
14931 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
14932 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
14933 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
14934 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
14935 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
14936 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
14937 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
14938 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
14939 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
14940 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
14941 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
14942 #define VdbeMemDynamic(X)  \
14943   (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
14944 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
14945 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
14946 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
14947 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
14948 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
14949 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
14950 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
14951 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
14952 
14953 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
14954 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
14955 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
14956 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
14957 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
14958 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
14959 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
14960 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
14961 
14962 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
14963 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
14964 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
14965 #else
14966 # define sqlite3VdbeEnter(X)
14967 # define sqlite3VdbeLeave(X)
14968 #endif
14969 
14970 #ifdef SQLITE_DEBUG
14971 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
14972 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
14973 #endif
14974 
14975 #ifndef SQLITE_OMIT_FOREIGN_KEY
14976 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
14977 #else
14978 # define sqlite3VdbeCheckFk(p,i) 0
14979 #endif
14980 
14981 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
14982 #ifdef SQLITE_DEBUG
14983 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
14984 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
14985 #endif
14986 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
14987 
14988 #ifndef SQLITE_OMIT_INCRBLOB
14989 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
14990   #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
14991 #else
14992   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
14993   #define ExpandBlob(P) SQLITE_OK
14994 #endif
14995 
14996 #endif /* !defined(_VDBEINT_H_) */
14997 
14998 /************** End of vdbeInt.h *********************************************/
14999 /************** Continuing where we left off in status.c *********************/
15000 
15001 /*
15002 ** Variables in which to record status information.
15003 */
15004 typedef struct sqlite3StatType sqlite3StatType;
15005 static SQLITE_WSD struct sqlite3StatType {
15006 #if SQLITE_PTRSIZE>4
15007   sqlite3_int64 nowValue[10];         /* Current value */
15008   sqlite3_int64 mxValue[10];          /* Maximum value */
15009 #else
15010   u32 nowValue[10];                   /* Current value */
15011   u32 mxValue[10];                    /* Maximum value */
15012 #endif
15013 } sqlite3Stat = { {0,}, {0,} };
15014 
15015 /*
15016 ** Elements of sqlite3Stat[] are protected by either the memory allocator
15017 ** mutex, or by the pcache1 mutex.  The following array determines which.
15018 */
15019 static const char statMutex[] = {
15020   0,  /* SQLITE_STATUS_MEMORY_USED */
15021   1,  /* SQLITE_STATUS_PAGECACHE_USED */
15022   1,  /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
15023   0,  /* SQLITE_STATUS_SCRATCH_USED */
15024   0,  /* SQLITE_STATUS_SCRATCH_OVERFLOW */
15025   0,  /* SQLITE_STATUS_MALLOC_SIZE */
15026   0,  /* SQLITE_STATUS_PARSER_STACK */
15027   1,  /* SQLITE_STATUS_PAGECACHE_SIZE */
15028   0,  /* SQLITE_STATUS_SCRATCH_SIZE */
15029   0,  /* SQLITE_STATUS_MALLOC_COUNT */
15030 };
15031 
15032 
15033 /* The "wsdStat" macro will resolve to the status information
15034 ** state vector.  If writable static data is unsupported on the target,
15035 ** we have to locate the state vector at run-time.  In the more common
15036 ** case where writable static data is supported, wsdStat can refer directly
15037 ** to the "sqlite3Stat" state vector declared above.
15038 */
15039 #ifdef SQLITE_OMIT_WSD
15040 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
15041 # define wsdStat x[0]
15042 #else
15043 # define wsdStatInit
15044 # define wsdStat sqlite3Stat
15045 #endif
15046 
15047 /*
15048 ** Return the current value of a status parameter.  The caller must
15049 ** be holding the appropriate mutex.
15050 */
sqlite3StatusValue(int op)15051 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
15052   wsdStatInit;
15053   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15054   assert( op>=0 && op<ArraySize(statMutex) );
15055   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
15056                                            : sqlite3MallocMutex()) );
15057   return wsdStat.nowValue[op];
15058 }
15059 
15060 /*
15061 ** Add N to the value of a status record.  The caller must hold the
15062 ** appropriate mutex.  (Locking is checked by assert()).
15063 **
15064 ** The StatusUp() routine can accept positive or negative values for N.
15065 ** The value of N is added to the current status value and the high-water
15066 ** mark is adjusted if necessary.
15067 **
15068 ** The StatusDown() routine lowers the current value by N.  The highwater
15069 ** mark is unchanged.  N must be non-negative for StatusDown().
15070 */
sqlite3StatusUp(int op,int N)15071 SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
15072   wsdStatInit;
15073   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15074   assert( op>=0 && op<ArraySize(statMutex) );
15075   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
15076                                            : sqlite3MallocMutex()) );
15077   wsdStat.nowValue[op] += N;
15078   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
15079     wsdStat.mxValue[op] = wsdStat.nowValue[op];
15080   }
15081 }
sqlite3StatusDown(int op,int N)15082 SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
15083   wsdStatInit;
15084   assert( N>=0 );
15085   assert( op>=0 && op<ArraySize(statMutex) );
15086   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
15087                                            : sqlite3MallocMutex()) );
15088   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15089   wsdStat.nowValue[op] -= N;
15090 }
15091 
15092 /*
15093 ** Set the value of a status to X.  The highwater mark is adjusted if
15094 ** necessary.  The caller must hold the appropriate mutex.
15095 */
sqlite3StatusSet(int op,int X)15096 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
15097   wsdStatInit;
15098   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15099   assert( op>=0 && op<ArraySize(statMutex) );
15100   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
15101                                            : sqlite3MallocMutex()) );
15102   wsdStat.nowValue[op] = X;
15103   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
15104     wsdStat.mxValue[op] = wsdStat.nowValue[op];
15105   }
15106 }
15107 
15108 /*
15109 ** Query status information.
15110 */
sqlite3_status64(int op,sqlite3_int64 * pCurrent,sqlite3_int64 * pHighwater,int resetFlag)15111 SQLITE_API int SQLITE_STDCALL sqlite3_status64(
15112   int op,
15113   sqlite3_int64 *pCurrent,
15114   sqlite3_int64 *pHighwater,
15115   int resetFlag
15116 ){
15117   sqlite3_mutex *pMutex;
15118   wsdStatInit;
15119   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
15120     return SQLITE_MISUSE_BKPT;
15121   }
15122 #ifdef SQLITE_ENABLE_API_ARMOR
15123   if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
15124 #endif
15125   pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
15126   sqlite3_mutex_enter(pMutex);
15127   *pCurrent = wsdStat.nowValue[op];
15128   *pHighwater = wsdStat.mxValue[op];
15129   if( resetFlag ){
15130     wsdStat.mxValue[op] = wsdStat.nowValue[op];
15131   }
15132   sqlite3_mutex_leave(pMutex);
15133   (void)pMutex;  /* Prevent warning when SQLITE_THREADSAFE=0 */
15134   return SQLITE_OK;
15135 }
sqlite3_status(int op,int * pCurrent,int * pHighwater,int resetFlag)15136 SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
15137   sqlite3_int64 iCur, iHwtr;
15138   int rc;
15139 #ifdef SQLITE_ENABLE_API_ARMOR
15140   if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
15141 #endif
15142   rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
15143   if( rc==0 ){
15144     *pCurrent = (int)iCur;
15145     *pHighwater = (int)iHwtr;
15146   }
15147   return rc;
15148 }
15149 
15150 /*
15151 ** Query status information for a single database connection
15152 */
sqlite3_db_status(sqlite3 * db,int op,int * pCurrent,int * pHighwater,int resetFlag)15153 SQLITE_API int SQLITE_STDCALL sqlite3_db_status(
15154   sqlite3 *db,          /* The database connection whose status is desired */
15155   int op,               /* Status verb */
15156   int *pCurrent,        /* Write current value here */
15157   int *pHighwater,      /* Write high-water mark here */
15158   int resetFlag         /* Reset high-water mark if true */
15159 ){
15160   int rc = SQLITE_OK;   /* Return code */
15161 #ifdef SQLITE_ENABLE_API_ARMOR
15162   if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
15163     return SQLITE_MISUSE_BKPT;
15164   }
15165 #endif
15166   sqlite3_mutex_enter(db->mutex);
15167   switch( op ){
15168     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
15169       *pCurrent = db->lookaside.nOut;
15170       *pHighwater = db->lookaside.mxOut;
15171       if( resetFlag ){
15172         db->lookaside.mxOut = db->lookaside.nOut;
15173       }
15174       break;
15175     }
15176 
15177     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
15178     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
15179     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
15180       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
15181       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
15182       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
15183       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
15184       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
15185       *pCurrent = 0;
15186       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
15187       if( resetFlag ){
15188         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
15189       }
15190       break;
15191     }
15192 
15193     /*
15194     ** Return an approximation for the amount of memory currently used
15195     ** by all pagers associated with the given database connection.  The
15196     ** highwater mark is meaningless and is returned as zero.
15197     */
15198     case SQLITE_DBSTATUS_CACHE_USED: {
15199       int totalUsed = 0;
15200       int i;
15201       sqlite3BtreeEnterAll(db);
15202       for(i=0; i<db->nDb; i++){
15203         Btree *pBt = db->aDb[i].pBt;
15204         if( pBt ){
15205           Pager *pPager = sqlite3BtreePager(pBt);
15206           totalUsed += sqlite3PagerMemUsed(pPager);
15207         }
15208       }
15209       sqlite3BtreeLeaveAll(db);
15210       *pCurrent = totalUsed;
15211       *pHighwater = 0;
15212       break;
15213     }
15214 
15215     /*
15216     ** *pCurrent gets an accurate estimate of the amount of memory used
15217     ** to store the schema for all databases (main, temp, and any ATTACHed
15218     ** databases.  *pHighwater is set to zero.
15219     */
15220     case SQLITE_DBSTATUS_SCHEMA_USED: {
15221       int i;                      /* Used to iterate through schemas */
15222       int nByte = 0;              /* Used to accumulate return value */
15223 
15224       sqlite3BtreeEnterAll(db);
15225       db->pnBytesFreed = &nByte;
15226       for(i=0; i<db->nDb; i++){
15227         Schema *pSchema = db->aDb[i].pSchema;
15228         if( ALWAYS(pSchema!=0) ){
15229           HashElem *p;
15230 
15231           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
15232               pSchema->tblHash.count
15233             + pSchema->trigHash.count
15234             + pSchema->idxHash.count
15235             + pSchema->fkeyHash.count
15236           );
15237           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
15238           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
15239           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
15240           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
15241 
15242           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
15243             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
15244           }
15245           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
15246             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
15247           }
15248         }
15249       }
15250       db->pnBytesFreed = 0;
15251       sqlite3BtreeLeaveAll(db);
15252 
15253       *pHighwater = 0;
15254       *pCurrent = nByte;
15255       break;
15256     }
15257 
15258     /*
15259     ** *pCurrent gets an accurate estimate of the amount of memory used
15260     ** to store all prepared statements.
15261     ** *pHighwater is set to zero.
15262     */
15263     case SQLITE_DBSTATUS_STMT_USED: {
15264       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
15265       int nByte = 0;              /* Used to accumulate return value */
15266 
15267       db->pnBytesFreed = &nByte;
15268       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
15269         sqlite3VdbeClearObject(db, pVdbe);
15270         sqlite3DbFree(db, pVdbe);
15271       }
15272       db->pnBytesFreed = 0;
15273 
15274       *pHighwater = 0;  /* IMP: R-64479-57858 */
15275       *pCurrent = nByte;
15276 
15277       break;
15278     }
15279 
15280     /*
15281     ** Set *pCurrent to the total cache hits or misses encountered by all
15282     ** pagers the database handle is connected to. *pHighwater is always set
15283     ** to zero.
15284     */
15285     case SQLITE_DBSTATUS_CACHE_HIT:
15286     case SQLITE_DBSTATUS_CACHE_MISS:
15287     case SQLITE_DBSTATUS_CACHE_WRITE:{
15288       int i;
15289       int nRet = 0;
15290       assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
15291       assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
15292 
15293       for(i=0; i<db->nDb; i++){
15294         if( db->aDb[i].pBt ){
15295           Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
15296           sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
15297         }
15298       }
15299       *pHighwater = 0; /* IMP: R-42420-56072 */
15300                        /* IMP: R-54100-20147 */
15301                        /* IMP: R-29431-39229 */
15302       *pCurrent = nRet;
15303       break;
15304     }
15305 
15306     /* Set *pCurrent to non-zero if there are unresolved deferred foreign
15307     ** key constraints.  Set *pCurrent to zero if all foreign key constraints
15308     ** have been satisfied.  The *pHighwater is always set to zero.
15309     */
15310     case SQLITE_DBSTATUS_DEFERRED_FKS: {
15311       *pHighwater = 0;  /* IMP: R-11967-56545 */
15312       *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
15313       break;
15314     }
15315 
15316     default: {
15317       rc = SQLITE_ERROR;
15318     }
15319   }
15320   sqlite3_mutex_leave(db->mutex);
15321   return rc;
15322 }
15323 
15324 /************** End of status.c **********************************************/
15325 /************** Begin file date.c ********************************************/
15326 /*
15327 ** 2003 October 31
15328 **
15329 ** The author disclaims copyright to this source code.  In place of
15330 ** a legal notice, here is a blessing:
15331 **
15332 **    May you do good and not evil.
15333 **    May you find forgiveness for yourself and forgive others.
15334 **    May you share freely, never taking more than you give.
15335 **
15336 *************************************************************************
15337 ** This file contains the C functions that implement date and time
15338 ** functions for SQLite.
15339 **
15340 ** There is only one exported symbol in this file - the function
15341 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
15342 ** All other code has file scope.
15343 **
15344 ** SQLite processes all times and dates as julian day numbers.  The
15345 ** dates and times are stored as the number of days since noon
15346 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
15347 ** calendar system.
15348 **
15349 ** 1970-01-01 00:00:00 is JD 2440587.5
15350 ** 2000-01-01 00:00:00 is JD 2451544.5
15351 **
15352 ** This implementation requires years to be expressed as a 4-digit number
15353 ** which means that only dates between 0000-01-01 and 9999-12-31 can
15354 ** be represented, even though julian day numbers allow a much wider
15355 ** range of dates.
15356 **
15357 ** The Gregorian calendar system is used for all dates and times,
15358 ** even those that predate the Gregorian calendar.  Historians usually
15359 ** use the julian calendar for dates prior to 1582-10-15 and for some
15360 ** dates afterwards, depending on locale.  Beware of this difference.
15361 **
15362 ** The conversion algorithms are implemented based on descriptions
15363 ** in the following text:
15364 **
15365 **      Jean Meeus
15366 **      Astronomical Algorithms, 2nd Edition, 1998
15367 **      ISBM 0-943396-61-1
15368 **      Willmann-Bell, Inc
15369 **      Richmond, Virginia (USA)
15370 */
15371 /* #include <stdlib.h> */
15372 /* #include <assert.h> */
15373 #include <time.h>
15374 
15375 #ifndef SQLITE_OMIT_DATETIME_FUNCS
15376 
15377 
15378 /*
15379 ** A structure for holding a single date and time.
15380 */
15381 typedef struct DateTime DateTime;
15382 struct DateTime {
15383   sqlite3_int64 iJD; /* The julian day number times 86400000 */
15384   int Y, M, D;       /* Year, month, and day */
15385   int h, m;          /* Hour and minutes */
15386   int tz;            /* Timezone offset in minutes */
15387   double s;          /* Seconds */
15388   char validYMD;     /* True (1) if Y,M,D are valid */
15389   char validHMS;     /* True (1) if h,m,s are valid */
15390   char validJD;      /* True (1) if iJD is valid */
15391   char validTZ;      /* True (1) if tz is valid */
15392 };
15393 
15394 
15395 /*
15396 ** Convert zDate into one or more integers.  Additional arguments
15397 ** come in groups of 5 as follows:
15398 **
15399 **       N       number of digits in the integer
15400 **       min     minimum allowed value of the integer
15401 **       max     maximum allowed value of the integer
15402 **       nextC   first character after the integer
15403 **       pVal    where to write the integers value.
15404 **
15405 ** Conversions continue until one with nextC==0 is encountered.
15406 ** The function returns the number of successful conversions.
15407 */
getDigits(const char * zDate,...)15408 static int getDigits(const char *zDate, ...){
15409   va_list ap;
15410   int val;
15411   int N;
15412   int min;
15413   int max;
15414   int nextC;
15415   int *pVal;
15416   int cnt = 0;
15417   va_start(ap, zDate);
15418   do{
15419     N = va_arg(ap, int);
15420     min = va_arg(ap, int);
15421     max = va_arg(ap, int);
15422     nextC = va_arg(ap, int);
15423     pVal = va_arg(ap, int*);
15424     val = 0;
15425     while( N-- ){
15426       if( !sqlite3Isdigit(*zDate) ){
15427         goto end_getDigits;
15428       }
15429       val = val*10 + *zDate - '0';
15430       zDate++;
15431     }
15432     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
15433       goto end_getDigits;
15434     }
15435     *pVal = val;
15436     zDate++;
15437     cnt++;
15438   }while( nextC );
15439 end_getDigits:
15440   va_end(ap);
15441   return cnt;
15442 }
15443 
15444 /*
15445 ** Parse a timezone extension on the end of a date-time.
15446 ** The extension is of the form:
15447 **
15448 **        (+/-)HH:MM
15449 **
15450 ** Or the "zulu" notation:
15451 **
15452 **        Z
15453 **
15454 ** If the parse is successful, write the number of minutes
15455 ** of change in p->tz and return 0.  If a parser error occurs,
15456 ** return non-zero.
15457 **
15458 ** A missing specifier is not considered an error.
15459 */
parseTimezone(const char * zDate,DateTime * p)15460 static int parseTimezone(const char *zDate, DateTime *p){
15461   int sgn = 0;
15462   int nHr, nMn;
15463   int c;
15464   while( sqlite3Isspace(*zDate) ){ zDate++; }
15465   p->tz = 0;
15466   c = *zDate;
15467   if( c=='-' ){
15468     sgn = -1;
15469   }else if( c=='+' ){
15470     sgn = +1;
15471   }else if( c=='Z' || c=='z' ){
15472     zDate++;
15473     goto zulu_time;
15474   }else{
15475     return c!=0;
15476   }
15477   zDate++;
15478   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
15479     return 1;
15480   }
15481   zDate += 5;
15482   p->tz = sgn*(nMn + nHr*60);
15483 zulu_time:
15484   while( sqlite3Isspace(*zDate) ){ zDate++; }
15485   return *zDate!=0;
15486 }
15487 
15488 /*
15489 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
15490 ** The HH, MM, and SS must each be exactly 2 digits.  The
15491 ** fractional seconds FFFF can be one or more digits.
15492 **
15493 ** Return 1 if there is a parsing error and 0 on success.
15494 */
parseHhMmSs(const char * zDate,DateTime * p)15495 static int parseHhMmSs(const char *zDate, DateTime *p){
15496   int h, m, s;
15497   double ms = 0.0;
15498   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
15499     return 1;
15500   }
15501   zDate += 5;
15502   if( *zDate==':' ){
15503     zDate++;
15504     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
15505       return 1;
15506     }
15507     zDate += 2;
15508     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
15509       double rScale = 1.0;
15510       zDate++;
15511       while( sqlite3Isdigit(*zDate) ){
15512         ms = ms*10.0 + *zDate - '0';
15513         rScale *= 10.0;
15514         zDate++;
15515       }
15516       ms /= rScale;
15517     }
15518   }else{
15519     s = 0;
15520   }
15521   p->validJD = 0;
15522   p->validHMS = 1;
15523   p->h = h;
15524   p->m = m;
15525   p->s = s + ms;
15526   if( parseTimezone(zDate, p) ) return 1;
15527   p->validTZ = (p->tz!=0)?1:0;
15528   return 0;
15529 }
15530 
15531 /*
15532 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
15533 ** that the YYYY-MM-DD is according to the Gregorian calendar.
15534 **
15535 ** Reference:  Meeus page 61
15536 */
computeJD(DateTime * p)15537 static void computeJD(DateTime *p){
15538   int Y, M, D, A, B, X1, X2;
15539 
15540   if( p->validJD ) return;
15541   if( p->validYMD ){
15542     Y = p->Y;
15543     M = p->M;
15544     D = p->D;
15545   }else{
15546     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
15547     M = 1;
15548     D = 1;
15549   }
15550   if( M<=2 ){
15551     Y--;
15552     M += 12;
15553   }
15554   A = Y/100;
15555   B = 2 - A + (A/4);
15556   X1 = 36525*(Y+4716)/100;
15557   X2 = 306001*(M+1)/10000;
15558   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
15559   p->validJD = 1;
15560   if( p->validHMS ){
15561     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
15562     if( p->validTZ ){
15563       p->iJD -= p->tz*60000;
15564       p->validYMD = 0;
15565       p->validHMS = 0;
15566       p->validTZ = 0;
15567     }
15568   }
15569 }
15570 
15571 /*
15572 ** Parse dates of the form
15573 **
15574 **     YYYY-MM-DD HH:MM:SS.FFF
15575 **     YYYY-MM-DD HH:MM:SS
15576 **     YYYY-MM-DD HH:MM
15577 **     YYYY-MM-DD
15578 **
15579 ** Write the result into the DateTime structure and return 0
15580 ** on success and 1 if the input string is not a well-formed
15581 ** date.
15582 */
parseYyyyMmDd(const char * zDate,DateTime * p)15583 static int parseYyyyMmDd(const char *zDate, DateTime *p){
15584   int Y, M, D, neg;
15585 
15586   if( zDate[0]=='-' ){
15587     zDate++;
15588     neg = 1;
15589   }else{
15590     neg = 0;
15591   }
15592   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
15593     return 1;
15594   }
15595   zDate += 10;
15596   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
15597   if( parseHhMmSs(zDate, p)==0 ){
15598     /* We got the time */
15599   }else if( *zDate==0 ){
15600     p->validHMS = 0;
15601   }else{
15602     return 1;
15603   }
15604   p->validJD = 0;
15605   p->validYMD = 1;
15606   p->Y = neg ? -Y : Y;
15607   p->M = M;
15608   p->D = D;
15609   if( p->validTZ ){
15610     computeJD(p);
15611   }
15612   return 0;
15613 }
15614 
15615 /*
15616 ** Set the time to the current time reported by the VFS.
15617 **
15618 ** Return the number of errors.
15619 */
setDateTimeToCurrent(sqlite3_context * context,DateTime * p)15620 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
15621   p->iJD = sqlite3StmtCurrentTime(context);
15622   if( p->iJD>0 ){
15623     p->validJD = 1;
15624     return 0;
15625   }else{
15626     return 1;
15627   }
15628 }
15629 
15630 /*
15631 ** Attempt to parse the given string into a julian day number.  Return
15632 ** the number of errors.
15633 **
15634 ** The following are acceptable forms for the input string:
15635 **
15636 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
15637 **      DDDD.DD
15638 **      now
15639 **
15640 ** In the first form, the +/-HH:MM is always optional.  The fractional
15641 ** seconds extension (the ".FFF") is optional.  The seconds portion
15642 ** (":SS.FFF") is option.  The year and date can be omitted as long
15643 ** as there is a time string.  The time string can be omitted as long
15644 ** as there is a year and date.
15645 */
parseDateOrTime(sqlite3_context * context,const char * zDate,DateTime * p)15646 static int parseDateOrTime(
15647   sqlite3_context *context,
15648   const char *zDate,
15649   DateTime *p
15650 ){
15651   double r;
15652   if( parseYyyyMmDd(zDate,p)==0 ){
15653     return 0;
15654   }else if( parseHhMmSs(zDate, p)==0 ){
15655     return 0;
15656   }else if( sqlite3StrICmp(zDate,"now")==0){
15657     return setDateTimeToCurrent(context, p);
15658   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
15659     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
15660     p->validJD = 1;
15661     return 0;
15662   }
15663   return 1;
15664 }
15665 
15666 /*
15667 ** Compute the Year, Month, and Day from the julian day number.
15668 */
computeYMD(DateTime * p)15669 static void computeYMD(DateTime *p){
15670   int Z, A, B, C, D, E, X1;
15671   if( p->validYMD ) return;
15672   if( !p->validJD ){
15673     p->Y = 2000;
15674     p->M = 1;
15675     p->D = 1;
15676   }else{
15677     Z = (int)((p->iJD + 43200000)/86400000);
15678     A = (int)((Z - 1867216.25)/36524.25);
15679     A = Z + 1 + A - (A/4);
15680     B = A + 1524;
15681     C = (int)((B - 122.1)/365.25);
15682     D = (36525*C)/100;
15683     E = (int)((B-D)/30.6001);
15684     X1 = (int)(30.6001*E);
15685     p->D = B - D - X1;
15686     p->M = E<14 ? E-1 : E-13;
15687     p->Y = p->M>2 ? C - 4716 : C - 4715;
15688   }
15689   p->validYMD = 1;
15690 }
15691 
15692 /*
15693 ** Compute the Hour, Minute, and Seconds from the julian day number.
15694 */
computeHMS(DateTime * p)15695 static void computeHMS(DateTime *p){
15696   int s;
15697   if( p->validHMS ) return;
15698   computeJD(p);
15699   s = (int)((p->iJD + 43200000) % 86400000);
15700   p->s = s/1000.0;
15701   s = (int)p->s;
15702   p->s -= s;
15703   p->h = s/3600;
15704   s -= p->h*3600;
15705   p->m = s/60;
15706   p->s += s - p->m*60;
15707   p->validHMS = 1;
15708 }
15709 
15710 /*
15711 ** Compute both YMD and HMS
15712 */
computeYMD_HMS(DateTime * p)15713 static void computeYMD_HMS(DateTime *p){
15714   computeYMD(p);
15715   computeHMS(p);
15716 }
15717 
15718 /*
15719 ** Clear the YMD and HMS and the TZ
15720 */
clearYMD_HMS_TZ(DateTime * p)15721 static void clearYMD_HMS_TZ(DateTime *p){
15722   p->validYMD = 0;
15723   p->validHMS = 0;
15724   p->validTZ = 0;
15725 }
15726 
15727 /*
15728 ** On recent Windows platforms, the localtime_s() function is available
15729 ** as part of the "Secure CRT". It is essentially equivalent to
15730 ** localtime_r() available under most POSIX platforms, except that the
15731 ** order of the parameters is reversed.
15732 **
15733 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
15734 **
15735 ** If the user has not indicated to use localtime_r() or localtime_s()
15736 ** already, check for an MSVC build environment that provides
15737 ** localtime_s().
15738 */
15739 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
15740     && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
15741 #undef  HAVE_LOCALTIME_S
15742 #define HAVE_LOCALTIME_S 1
15743 #endif
15744 
15745 #ifndef SQLITE_OMIT_LOCALTIME
15746 /*
15747 ** The following routine implements the rough equivalent of localtime_r()
15748 ** using whatever operating-system specific localtime facility that
15749 ** is available.  This routine returns 0 on success and
15750 ** non-zero on any kind of error.
15751 **
15752 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
15753 ** routine will always fail.
15754 **
15755 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
15756 ** library function localtime_r() is used to assist in the calculation of
15757 ** local time.
15758 */
osLocaltime(time_t * t,struct tm * pTm)15759 static int osLocaltime(time_t *t, struct tm *pTm){
15760   int rc;
15761 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
15762   struct tm *pX;
15763 #if SQLITE_THREADSAFE>0
15764   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15765 #endif
15766   sqlite3_mutex_enter(mutex);
15767   pX = localtime(t);
15768 #ifndef SQLITE_OMIT_BUILTIN_TEST
15769   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
15770 #endif
15771   if( pX ) *pTm = *pX;
15772   sqlite3_mutex_leave(mutex);
15773   rc = pX==0;
15774 #else
15775 #ifndef SQLITE_OMIT_BUILTIN_TEST
15776   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
15777 #endif
15778 #if HAVE_LOCALTIME_R
15779   rc = localtime_r(t, pTm)==0;
15780 #else
15781   rc = localtime_s(pTm, t);
15782 #endif /* HAVE_LOCALTIME_R */
15783 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
15784   return rc;
15785 }
15786 #endif /* SQLITE_OMIT_LOCALTIME */
15787 
15788 
15789 #ifndef SQLITE_OMIT_LOCALTIME
15790 /*
15791 ** Compute the difference (in milliseconds) between localtime and UTC
15792 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
15793 ** return this value and set *pRc to SQLITE_OK.
15794 **
15795 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
15796 ** is undefined in this case.
15797 */
localtimeOffset(DateTime * p,sqlite3_context * pCtx,int * pRc)15798 static sqlite3_int64 localtimeOffset(
15799   DateTime *p,                    /* Date at which to calculate offset */
15800   sqlite3_context *pCtx,          /* Write error here if one occurs */
15801   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
15802 ){
15803   DateTime x, y;
15804   time_t t;
15805   struct tm sLocal;
15806 
15807   /* Initialize the contents of sLocal to avoid a compiler warning. */
15808   memset(&sLocal, 0, sizeof(sLocal));
15809 
15810   x = *p;
15811   computeYMD_HMS(&x);
15812   if( x.Y<1971 || x.Y>=2038 ){
15813     /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
15814     ** works for years between 1970 and 2037. For dates outside this range,
15815     ** SQLite attempts to map the year into an equivalent year within this
15816     ** range, do the calculation, then map the year back.
15817     */
15818     x.Y = 2000;
15819     x.M = 1;
15820     x.D = 1;
15821     x.h = 0;
15822     x.m = 0;
15823     x.s = 0.0;
15824   } else {
15825     int s = (int)(x.s + 0.5);
15826     x.s = s;
15827   }
15828   x.tz = 0;
15829   x.validJD = 0;
15830   computeJD(&x);
15831   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
15832   if( osLocaltime(&t, &sLocal) ){
15833     sqlite3_result_error(pCtx, "local time unavailable", -1);
15834     *pRc = SQLITE_ERROR;
15835     return 0;
15836   }
15837   y.Y = sLocal.tm_year + 1900;
15838   y.M = sLocal.tm_mon + 1;
15839   y.D = sLocal.tm_mday;
15840   y.h = sLocal.tm_hour;
15841   y.m = sLocal.tm_min;
15842   y.s = sLocal.tm_sec;
15843   y.validYMD = 1;
15844   y.validHMS = 1;
15845   y.validJD = 0;
15846   y.validTZ = 0;
15847   computeJD(&y);
15848   *pRc = SQLITE_OK;
15849   return y.iJD - x.iJD;
15850 }
15851 #endif /* SQLITE_OMIT_LOCALTIME */
15852 
15853 /*
15854 ** Process a modifier to a date-time stamp.  The modifiers are
15855 ** as follows:
15856 **
15857 **     NNN days
15858 **     NNN hours
15859 **     NNN minutes
15860 **     NNN.NNNN seconds
15861 **     NNN months
15862 **     NNN years
15863 **     start of month
15864 **     start of year
15865 **     start of week
15866 **     start of day
15867 **     weekday N
15868 **     unixepoch
15869 **     localtime
15870 **     utc
15871 **
15872 ** Return 0 on success and 1 if there is any kind of error. If the error
15873 ** is in a system call (i.e. localtime()), then an error message is written
15874 ** to context pCtx. If the error is an unrecognized modifier, no error is
15875 ** written to pCtx.
15876 */
parseModifier(sqlite3_context * pCtx,const char * zMod,DateTime * p)15877 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
15878   int rc = 1;
15879   int n;
15880   double r;
15881   char *z, zBuf[30];
15882   z = zBuf;
15883   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
15884     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
15885   }
15886   z[n] = 0;
15887   switch( z[0] ){
15888 #ifndef SQLITE_OMIT_LOCALTIME
15889     case 'l': {
15890       /*    localtime
15891       **
15892       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
15893       ** show local time.
15894       */
15895       if( strcmp(z, "localtime")==0 ){
15896         computeJD(p);
15897         p->iJD += localtimeOffset(p, pCtx, &rc);
15898         clearYMD_HMS_TZ(p);
15899       }
15900       break;
15901     }
15902 #endif
15903     case 'u': {
15904       /*
15905       **    unixepoch
15906       **
15907       ** Treat the current value of p->iJD as the number of
15908       ** seconds since 1970.  Convert to a real julian day number.
15909       */
15910       if( strcmp(z, "unixepoch")==0 && p->validJD ){
15911         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
15912         clearYMD_HMS_TZ(p);
15913         rc = 0;
15914       }
15915 #ifndef SQLITE_OMIT_LOCALTIME
15916       else if( strcmp(z, "utc")==0 ){
15917         sqlite3_int64 c1;
15918         computeJD(p);
15919         c1 = localtimeOffset(p, pCtx, &rc);
15920         if( rc==SQLITE_OK ){
15921           p->iJD -= c1;
15922           clearYMD_HMS_TZ(p);
15923           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
15924         }
15925       }
15926 #endif
15927       break;
15928     }
15929     case 'w': {
15930       /*
15931       **    weekday N
15932       **
15933       ** Move the date to the same time on the next occurrence of
15934       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
15935       ** date is already on the appropriate weekday, this is a no-op.
15936       */
15937       if( strncmp(z, "weekday ", 8)==0
15938                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
15939                && (n=(int)r)==r && n>=0 && r<7 ){
15940         sqlite3_int64 Z;
15941         computeYMD_HMS(p);
15942         p->validTZ = 0;
15943         p->validJD = 0;
15944         computeJD(p);
15945         Z = ((p->iJD + 129600000)/86400000) % 7;
15946         if( Z>n ) Z -= 7;
15947         p->iJD += (n - Z)*86400000;
15948         clearYMD_HMS_TZ(p);
15949         rc = 0;
15950       }
15951       break;
15952     }
15953     case 's': {
15954       /*
15955       **    start of TTTTT
15956       **
15957       ** Move the date backwards to the beginning of the current day,
15958       ** or month or year.
15959       */
15960       if( strncmp(z, "start of ", 9)!=0 ) break;
15961       z += 9;
15962       computeYMD(p);
15963       p->validHMS = 1;
15964       p->h = p->m = 0;
15965       p->s = 0.0;
15966       p->validTZ = 0;
15967       p->validJD = 0;
15968       if( strcmp(z,"month")==0 ){
15969         p->D = 1;
15970         rc = 0;
15971       }else if( strcmp(z,"year")==0 ){
15972         computeYMD(p);
15973         p->M = 1;
15974         p->D = 1;
15975         rc = 0;
15976       }else if( strcmp(z,"day")==0 ){
15977         rc = 0;
15978       }
15979       break;
15980     }
15981     case '+':
15982     case '-':
15983     case '0':
15984     case '1':
15985     case '2':
15986     case '3':
15987     case '4':
15988     case '5':
15989     case '6':
15990     case '7':
15991     case '8':
15992     case '9': {
15993       double rRounder;
15994       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
15995       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
15996         rc = 1;
15997         break;
15998       }
15999       if( z[n]==':' ){
16000         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
16001         ** specified number of hours, minutes, seconds, and fractional seconds
16002         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
16003         ** omitted.
16004         */
16005         const char *z2 = z;
16006         DateTime tx;
16007         sqlite3_int64 day;
16008         if( !sqlite3Isdigit(*z2) ) z2++;
16009         memset(&tx, 0, sizeof(tx));
16010         if( parseHhMmSs(z2, &tx) ) break;
16011         computeJD(&tx);
16012         tx.iJD -= 43200000;
16013         day = tx.iJD/86400000;
16014         tx.iJD -= day*86400000;
16015         if( z[0]=='-' ) tx.iJD = -tx.iJD;
16016         computeJD(p);
16017         clearYMD_HMS_TZ(p);
16018         p->iJD += tx.iJD;
16019         rc = 0;
16020         break;
16021       }
16022       z += n;
16023       while( sqlite3Isspace(*z) ) z++;
16024       n = sqlite3Strlen30(z);
16025       if( n>10 || n<3 ) break;
16026       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
16027       computeJD(p);
16028       rc = 0;
16029       rRounder = r<0 ? -0.5 : +0.5;
16030       if( n==3 && strcmp(z,"day")==0 ){
16031         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
16032       }else if( n==4 && strcmp(z,"hour")==0 ){
16033         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
16034       }else if( n==6 && strcmp(z,"minute")==0 ){
16035         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
16036       }else if( n==6 && strcmp(z,"second")==0 ){
16037         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
16038       }else if( n==5 && strcmp(z,"month")==0 ){
16039         int x, y;
16040         computeYMD_HMS(p);
16041         p->M += (int)r;
16042         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
16043         p->Y += x;
16044         p->M -= x*12;
16045         p->validJD = 0;
16046         computeJD(p);
16047         y = (int)r;
16048         if( y!=r ){
16049           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
16050         }
16051       }else if( n==4 && strcmp(z,"year")==0 ){
16052         int y = (int)r;
16053         computeYMD_HMS(p);
16054         p->Y += y;
16055         p->validJD = 0;
16056         computeJD(p);
16057         if( y!=r ){
16058           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
16059         }
16060       }else{
16061         rc = 1;
16062       }
16063       clearYMD_HMS_TZ(p);
16064       break;
16065     }
16066     default: {
16067       break;
16068     }
16069   }
16070   return rc;
16071 }
16072 
16073 /*
16074 ** Process time function arguments.  argv[0] is a date-time stamp.
16075 ** argv[1] and following are modifiers.  Parse them all and write
16076 ** the resulting time into the DateTime structure p.  Return 0
16077 ** on success and 1 if there are any errors.
16078 **
16079 ** If there are zero parameters (if even argv[0] is undefined)
16080 ** then assume a default value of "now" for argv[0].
16081 */
isDate(sqlite3_context * context,int argc,sqlite3_value ** argv,DateTime * p)16082 static int isDate(
16083   sqlite3_context *context,
16084   int argc,
16085   sqlite3_value **argv,
16086   DateTime *p
16087 ){
16088   int i;
16089   const unsigned char *z;
16090   int eType;
16091   memset(p, 0, sizeof(*p));
16092   if( argc==0 ){
16093     return setDateTimeToCurrent(context, p);
16094   }
16095   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
16096                    || eType==SQLITE_INTEGER ){
16097     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
16098     p->validJD = 1;
16099   }else{
16100     z = sqlite3_value_text(argv[0]);
16101     if( !z || parseDateOrTime(context, (char*)z, p) ){
16102       return 1;
16103     }
16104   }
16105   for(i=1; i<argc; i++){
16106     z = sqlite3_value_text(argv[i]);
16107     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
16108   }
16109   return 0;
16110 }
16111 
16112 
16113 /*
16114 ** The following routines implement the various date and time functions
16115 ** of SQLite.
16116 */
16117 
16118 /*
16119 **    julianday( TIMESTRING, MOD, MOD, ...)
16120 **
16121 ** Return the julian day number of the date specified in the arguments
16122 */
juliandayFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)16123 static void juliandayFunc(
16124   sqlite3_context *context,
16125   int argc,
16126   sqlite3_value **argv
16127 ){
16128   DateTime x;
16129   if( isDate(context, argc, argv, &x)==0 ){
16130     computeJD(&x);
16131     sqlite3_result_double(context, x.iJD/86400000.0);
16132   }
16133 }
16134 
16135 /*
16136 **    datetime( TIMESTRING, MOD, MOD, ...)
16137 **
16138 ** Return YYYY-MM-DD HH:MM:SS
16139 */
datetimeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)16140 static void datetimeFunc(
16141   sqlite3_context *context,
16142   int argc,
16143   sqlite3_value **argv
16144 ){
16145   DateTime x;
16146   if( isDate(context, argc, argv, &x)==0 ){
16147     char zBuf[100];
16148     computeYMD_HMS(&x);
16149     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
16150                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
16151     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
16152   }
16153 }
16154 
16155 /*
16156 **    time( TIMESTRING, MOD, MOD, ...)
16157 **
16158 ** Return HH:MM:SS
16159 */
timeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)16160 static void timeFunc(
16161   sqlite3_context *context,
16162   int argc,
16163   sqlite3_value **argv
16164 ){
16165   DateTime x;
16166   if( isDate(context, argc, argv, &x)==0 ){
16167     char zBuf[100];
16168     computeHMS(&x);
16169     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
16170     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
16171   }
16172 }
16173 
16174 /*
16175 **    date( TIMESTRING, MOD, MOD, ...)
16176 **
16177 ** Return YYYY-MM-DD
16178 */
dateFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)16179 static void dateFunc(
16180   sqlite3_context *context,
16181   int argc,
16182   sqlite3_value **argv
16183 ){
16184   DateTime x;
16185   if( isDate(context, argc, argv, &x)==0 ){
16186     char zBuf[100];
16187     computeYMD(&x);
16188     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
16189     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
16190   }
16191 }
16192 
16193 /*
16194 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
16195 **
16196 ** Return a string described by FORMAT.  Conversions as follows:
16197 **
16198 **   %d  day of month
16199 **   %f  ** fractional seconds  SS.SSS
16200 **   %H  hour 00-24
16201 **   %j  day of year 000-366
16202 **   %J  ** julian day number
16203 **   %m  month 01-12
16204 **   %M  minute 00-59
16205 **   %s  seconds since 1970-01-01
16206 **   %S  seconds 00-59
16207 **   %w  day of week 0-6  sunday==0
16208 **   %W  week of year 00-53
16209 **   %Y  year 0000-9999
16210 **   %%  %
16211 */
strftimeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)16212 static void strftimeFunc(
16213   sqlite3_context *context,
16214   int argc,
16215   sqlite3_value **argv
16216 ){
16217   DateTime x;
16218   u64 n;
16219   size_t i,j;
16220   char *z;
16221   sqlite3 *db;
16222   const char *zFmt;
16223   char zBuf[100];
16224   if( argc==0 ) return;
16225   zFmt = (const char*)sqlite3_value_text(argv[0]);
16226   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
16227   db = sqlite3_context_db_handle(context);
16228   for(i=0, n=1; zFmt[i]; i++, n++){
16229     if( zFmt[i]=='%' ){
16230       switch( zFmt[i+1] ){
16231         case 'd':
16232         case 'H':
16233         case 'm':
16234         case 'M':
16235         case 'S':
16236         case 'W':
16237           n++;
16238           /* fall thru */
16239         case 'w':
16240         case '%':
16241           break;
16242         case 'f':
16243           n += 8;
16244           break;
16245         case 'j':
16246           n += 3;
16247           break;
16248         case 'Y':
16249           n += 8;
16250           break;
16251         case 's':
16252         case 'J':
16253           n += 50;
16254           break;
16255         default:
16256           return;  /* ERROR.  return a NULL */
16257       }
16258       i++;
16259     }
16260   }
16261   testcase( n==sizeof(zBuf)-1 );
16262   testcase( n==sizeof(zBuf) );
16263   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
16264   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
16265   if( n<sizeof(zBuf) ){
16266     z = zBuf;
16267   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
16268     sqlite3_result_error_toobig(context);
16269     return;
16270   }else{
16271     z = sqlite3DbMallocRaw(db, (int)n);
16272     if( z==0 ){
16273       sqlite3_result_error_nomem(context);
16274       return;
16275     }
16276   }
16277   computeJD(&x);
16278   computeYMD_HMS(&x);
16279   for(i=j=0; zFmt[i]; i++){
16280     if( zFmt[i]!='%' ){
16281       z[j++] = zFmt[i];
16282     }else{
16283       i++;
16284       switch( zFmt[i] ){
16285         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
16286         case 'f': {
16287           double s = x.s;
16288           if( s>59.999 ) s = 59.999;
16289           sqlite3_snprintf(7, &z[j],"%06.3f", s);
16290           j += sqlite3Strlen30(&z[j]);
16291           break;
16292         }
16293         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
16294         case 'W': /* Fall thru */
16295         case 'j': {
16296           int nDay;             /* Number of days since 1st day of year */
16297           DateTime y = x;
16298           y.validJD = 0;
16299           y.M = 1;
16300           y.D = 1;
16301           computeJD(&y);
16302           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
16303           if( zFmt[i]=='W' ){
16304             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
16305             wd = (int)(((x.iJD+43200000)/86400000)%7);
16306             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
16307             j += 2;
16308           }else{
16309             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
16310             j += 3;
16311           }
16312           break;
16313         }
16314         case 'J': {
16315           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
16316           j+=sqlite3Strlen30(&z[j]);
16317           break;
16318         }
16319         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
16320         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
16321         case 's': {
16322           sqlite3_snprintf(30,&z[j],"%lld",
16323                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
16324           j += sqlite3Strlen30(&z[j]);
16325           break;
16326         }
16327         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
16328         case 'w': {
16329           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
16330           break;
16331         }
16332         case 'Y': {
16333           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
16334           break;
16335         }
16336         default:   z[j++] = '%'; break;
16337       }
16338     }
16339   }
16340   z[j] = 0;
16341   sqlite3_result_text(context, z, -1,
16342                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
16343 }
16344 
16345 /*
16346 ** current_time()
16347 **
16348 ** This function returns the same value as time('now').
16349 */
ctimeFunc(sqlite3_context * context,int NotUsed,sqlite3_value ** NotUsed2)16350 static void ctimeFunc(
16351   sqlite3_context *context,
16352   int NotUsed,
16353   sqlite3_value **NotUsed2
16354 ){
16355   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16356   timeFunc(context, 0, 0);
16357 }
16358 
16359 /*
16360 ** current_date()
16361 **
16362 ** This function returns the same value as date('now').
16363 */
cdateFunc(sqlite3_context * context,int NotUsed,sqlite3_value ** NotUsed2)16364 static void cdateFunc(
16365   sqlite3_context *context,
16366   int NotUsed,
16367   sqlite3_value **NotUsed2
16368 ){
16369   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16370   dateFunc(context, 0, 0);
16371 }
16372 
16373 /*
16374 ** current_timestamp()
16375 **
16376 ** This function returns the same value as datetime('now').
16377 */
ctimestampFunc(sqlite3_context * context,int NotUsed,sqlite3_value ** NotUsed2)16378 static void ctimestampFunc(
16379   sqlite3_context *context,
16380   int NotUsed,
16381   sqlite3_value **NotUsed2
16382 ){
16383   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16384   datetimeFunc(context, 0, 0);
16385 }
16386 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
16387 
16388 #ifdef SQLITE_OMIT_DATETIME_FUNCS
16389 /*
16390 ** If the library is compiled to omit the full-scale date and time
16391 ** handling (to get a smaller binary), the following minimal version
16392 ** of the functions current_time(), current_date() and current_timestamp()
16393 ** are included instead. This is to support column declarations that
16394 ** include "DEFAULT CURRENT_TIME" etc.
16395 **
16396 ** This function uses the C-library functions time(), gmtime()
16397 ** and strftime(). The format string to pass to strftime() is supplied
16398 ** as the user-data for the function.
16399 */
currentTimeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)16400 static void currentTimeFunc(
16401   sqlite3_context *context,
16402   int argc,
16403   sqlite3_value **argv
16404 ){
16405   time_t t;
16406   char *zFormat = (char *)sqlite3_user_data(context);
16407   sqlite3 *db;
16408   sqlite3_int64 iT;
16409   struct tm *pTm;
16410   struct tm sNow;
16411   char zBuf[20];
16412 
16413   UNUSED_PARAMETER(argc);
16414   UNUSED_PARAMETER(argv);
16415 
16416   iT = sqlite3StmtCurrentTime(context);
16417   if( iT<=0 ) return;
16418   t = iT/1000 - 10000*(sqlite3_int64)21086676;
16419 #if HAVE_GMTIME_R
16420   pTm = gmtime_r(&t, &sNow);
16421 #else
16422   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
16423   pTm = gmtime(&t);
16424   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
16425   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
16426 #endif
16427   if( pTm ){
16428     strftime(zBuf, 20, zFormat, &sNow);
16429     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
16430   }
16431 }
16432 #endif
16433 
16434 /*
16435 ** This function registered all of the above C functions as SQL
16436 ** functions.  This should be the only routine in this file with
16437 ** external linkage.
16438 */
sqlite3RegisterDateTimeFunctions(void)16439 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
16440   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
16441 #ifndef SQLITE_OMIT_DATETIME_FUNCS
16442     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
16443     FUNCTION(date,             -1, 0, 0, dateFunc      ),
16444     FUNCTION(time,             -1, 0, 0, timeFunc      ),
16445     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
16446     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
16447     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
16448     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
16449     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
16450 #else
16451     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
16452     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
16453     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
16454 #endif
16455   };
16456   int i;
16457   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
16458   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
16459 
16460   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
16461     sqlite3FuncDefInsert(pHash, &aFunc[i]);
16462   }
16463 }
16464 
16465 /************** End of date.c ************************************************/
16466 /************** Begin file os.c **********************************************/
16467 /*
16468 ** 2005 November 29
16469 **
16470 ** The author disclaims copyright to this source code.  In place of
16471 ** a legal notice, here is a blessing:
16472 **
16473 **    May you do good and not evil.
16474 **    May you find forgiveness for yourself and forgive others.
16475 **    May you share freely, never taking more than you give.
16476 **
16477 ******************************************************************************
16478 **
16479 ** This file contains OS interface code that is common to all
16480 ** architectures.
16481 */
16482 #define _SQLITE_OS_C_ 1
16483 #undef _SQLITE_OS_C_
16484 
16485 /*
16486 ** The default SQLite sqlite3_vfs implementations do not allocate
16487 ** memory (actually, os_unix.c allocates a small amount of memory
16488 ** from within OsOpen()), but some third-party implementations may.
16489 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
16490 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
16491 **
16492 ** The following functions are instrumented for malloc() failure
16493 ** testing:
16494 **
16495 **     sqlite3OsRead()
16496 **     sqlite3OsWrite()
16497 **     sqlite3OsSync()
16498 **     sqlite3OsFileSize()
16499 **     sqlite3OsLock()
16500 **     sqlite3OsCheckReservedLock()
16501 **     sqlite3OsFileControl()
16502 **     sqlite3OsShmMap()
16503 **     sqlite3OsOpen()
16504 **     sqlite3OsDelete()
16505 **     sqlite3OsAccess()
16506 **     sqlite3OsFullPathname()
16507 **
16508 */
16509 #if defined(SQLITE_TEST)
16510 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
16511   #define DO_OS_MALLOC_TEST(x)                                       \
16512   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
16513     void *pTstAlloc = sqlite3Malloc(10);                             \
16514     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
16515     sqlite3_free(pTstAlloc);                                         \
16516   }
16517 #else
16518   #define DO_OS_MALLOC_TEST(x)
16519 #endif
16520 
16521 /*
16522 ** The following routines are convenience wrappers around methods
16523 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
16524 ** of this would be completely automatic if SQLite were coded using
16525 ** C++ instead of plain old C.
16526 */
sqlite3OsClose(sqlite3_file * pId)16527 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
16528   int rc = SQLITE_OK;
16529   if( pId->pMethods ){
16530     rc = pId->pMethods->xClose(pId);
16531     pId->pMethods = 0;
16532   }
16533   return rc;
16534 }
sqlite3OsRead(sqlite3_file * id,void * pBuf,int amt,i64 offset)16535 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
16536   DO_OS_MALLOC_TEST(id);
16537   return id->pMethods->xRead(id, pBuf, amt, offset);
16538 }
sqlite3OsWrite(sqlite3_file * id,const void * pBuf,int amt,i64 offset)16539 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
16540   DO_OS_MALLOC_TEST(id);
16541   return id->pMethods->xWrite(id, pBuf, amt, offset);
16542 }
sqlite3OsTruncate(sqlite3_file * id,i64 size)16543 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
16544   return id->pMethods->xTruncate(id, size);
16545 }
sqlite3OsSync(sqlite3_file * id,int flags)16546 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
16547   DO_OS_MALLOC_TEST(id);
16548   return id->pMethods->xSync(id, flags);
16549 }
sqlite3OsFileSize(sqlite3_file * id,i64 * pSize)16550 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
16551   DO_OS_MALLOC_TEST(id);
16552   return id->pMethods->xFileSize(id, pSize);
16553 }
sqlite3OsLock(sqlite3_file * id,int lockType)16554 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
16555   DO_OS_MALLOC_TEST(id);
16556   return id->pMethods->xLock(id, lockType);
16557 }
sqlite3OsUnlock(sqlite3_file * id,int lockType)16558 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
16559   return id->pMethods->xUnlock(id, lockType);
16560 }
sqlite3OsCheckReservedLock(sqlite3_file * id,int * pResOut)16561 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
16562   DO_OS_MALLOC_TEST(id);
16563   return id->pMethods->xCheckReservedLock(id, pResOut);
16564 }
16565 
16566 /*
16567 ** Use sqlite3OsFileControl() when we are doing something that might fail
16568 ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
16569 ** when simply tossing information over the wall to the VFS and we do not
16570 ** really care if the VFS receives and understands the information since it
16571 ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
16572 ** routine has no return value since the return value would be meaningless.
16573 */
sqlite3OsFileControl(sqlite3_file * id,int op,void * pArg)16574 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
16575 #ifdef SQLITE_TEST
16576   if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
16577     /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
16578     ** is using a regular VFS, it is called after the corresponding
16579     ** transaction has been committed. Injecting a fault at this point
16580     ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
16581     ** but the transaction is committed anyway.
16582     **
16583     ** The core must call OsFileControl() though, not OsFileControlHint(),
16584     ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
16585     ** means the commit really has failed and an error should be returned
16586     ** to the user.  */
16587     DO_OS_MALLOC_TEST(id);
16588   }
16589 #endif
16590   return id->pMethods->xFileControl(id, op, pArg);
16591 }
sqlite3OsFileControlHint(sqlite3_file * id,int op,void * pArg)16592 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
16593   (void)id->pMethods->xFileControl(id, op, pArg);
16594 }
16595 
sqlite3OsSectorSize(sqlite3_file * id)16596 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
16597   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
16598   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
16599 }
sqlite3OsDeviceCharacteristics(sqlite3_file * id)16600 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
16601   return id->pMethods->xDeviceCharacteristics(id);
16602 }
sqlite3OsShmLock(sqlite3_file * id,int offset,int n,int flags)16603 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
16604   return id->pMethods->xShmLock(id, offset, n, flags);
16605 }
sqlite3OsShmBarrier(sqlite3_file * id)16606 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
16607   id->pMethods->xShmBarrier(id);
16608 }
sqlite3OsShmUnmap(sqlite3_file * id,int deleteFlag)16609 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
16610   return id->pMethods->xShmUnmap(id, deleteFlag);
16611 }
sqlite3OsShmMap(sqlite3_file * id,int iPage,int pgsz,int bExtend,void volatile ** pp)16612 SQLITE_PRIVATE int sqlite3OsShmMap(
16613   sqlite3_file *id,               /* Database file handle */
16614   int iPage,
16615   int pgsz,
16616   int bExtend,                    /* True to extend file if necessary */
16617   void volatile **pp              /* OUT: Pointer to mapping */
16618 ){
16619   DO_OS_MALLOC_TEST(id);
16620   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
16621 }
16622 
16623 #if SQLITE_MAX_MMAP_SIZE>0
16624 /* The real implementation of xFetch and xUnfetch */
sqlite3OsFetch(sqlite3_file * id,i64 iOff,int iAmt,void ** pp)16625 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
16626   DO_OS_MALLOC_TEST(id);
16627   return id->pMethods->xFetch(id, iOff, iAmt, pp);
16628 }
sqlite3OsUnfetch(sqlite3_file * id,i64 iOff,void * p)16629 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
16630   return id->pMethods->xUnfetch(id, iOff, p);
16631 }
16632 #else
16633 /* No-op stubs to use when memory-mapped I/O is disabled */
sqlite3OsFetch(sqlite3_file * id,i64 iOff,int iAmt,void ** pp)16634 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
16635   *pp = 0;
16636   return SQLITE_OK;
16637 }
sqlite3OsUnfetch(sqlite3_file * id,i64 iOff,void * p)16638 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
16639   return SQLITE_OK;
16640 }
16641 #endif
16642 
16643 /*
16644 ** The next group of routines are convenience wrappers around the
16645 ** VFS methods.
16646 */
sqlite3OsOpen(sqlite3_vfs * pVfs,const char * zPath,sqlite3_file * pFile,int flags,int * pFlagsOut)16647 SQLITE_PRIVATE int sqlite3OsOpen(
16648   sqlite3_vfs *pVfs,
16649   const char *zPath,
16650   sqlite3_file *pFile,
16651   int flags,
16652   int *pFlagsOut
16653 ){
16654   int rc;
16655   DO_OS_MALLOC_TEST(0);
16656   /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
16657   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
16658   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
16659   ** reaching the VFS. */
16660   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
16661   assert( rc==SQLITE_OK || pFile->pMethods==0 );
16662   return rc;
16663 }
sqlite3OsDelete(sqlite3_vfs * pVfs,const char * zPath,int dirSync)16664 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
16665   DO_OS_MALLOC_TEST(0);
16666   assert( dirSync==0 || dirSync==1 );
16667   return pVfs->xDelete(pVfs, zPath, dirSync);
16668 }
sqlite3OsAccess(sqlite3_vfs * pVfs,const char * zPath,int flags,int * pResOut)16669 SQLITE_PRIVATE int sqlite3OsAccess(
16670   sqlite3_vfs *pVfs,
16671   const char *zPath,
16672   int flags,
16673   int *pResOut
16674 ){
16675   DO_OS_MALLOC_TEST(0);
16676   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
16677 }
sqlite3OsFullPathname(sqlite3_vfs * pVfs,const char * zPath,int nPathOut,char * zPathOut)16678 SQLITE_PRIVATE int sqlite3OsFullPathname(
16679   sqlite3_vfs *pVfs,
16680   const char *zPath,
16681   int nPathOut,
16682   char *zPathOut
16683 ){
16684   DO_OS_MALLOC_TEST(0);
16685   zPathOut[0] = 0;
16686   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
16687 }
16688 #ifndef SQLITE_OMIT_LOAD_EXTENSION
sqlite3OsDlOpen(sqlite3_vfs * pVfs,const char * zPath)16689 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
16690   return pVfs->xDlOpen(pVfs, zPath);
16691 }
sqlite3OsDlError(sqlite3_vfs * pVfs,int nByte,char * zBufOut)16692 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
16693   pVfs->xDlError(pVfs, nByte, zBufOut);
16694 }
sqlite3OsDlSym(sqlite3_vfs * pVfs,void * pHdle,const char * zSym)16695 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
16696   return pVfs->xDlSym(pVfs, pHdle, zSym);
16697 }
sqlite3OsDlClose(sqlite3_vfs * pVfs,void * pHandle)16698 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
16699   pVfs->xDlClose(pVfs, pHandle);
16700 }
16701 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
sqlite3OsRandomness(sqlite3_vfs * pVfs,int nByte,char * zBufOut)16702 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
16703   return pVfs->xRandomness(pVfs, nByte, zBufOut);
16704 }
sqlite3OsSleep(sqlite3_vfs * pVfs,int nMicro)16705 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
16706   return pVfs->xSleep(pVfs, nMicro);
16707 }
sqlite3OsCurrentTimeInt64(sqlite3_vfs * pVfs,sqlite3_int64 * pTimeOut)16708 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
16709   int rc;
16710   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
16711   ** method to get the current date and time if that method is available
16712   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
16713   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
16714   ** unavailable.
16715   */
16716   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
16717     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
16718   }else{
16719     double r;
16720     rc = pVfs->xCurrentTime(pVfs, &r);
16721     *pTimeOut = (sqlite3_int64)(r*86400000.0);
16722   }
16723   return rc;
16724 }
16725 
sqlite3OsOpenMalloc(sqlite3_vfs * pVfs,const char * zFile,sqlite3_file ** ppFile,int flags,int * pOutFlags)16726 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
16727   sqlite3_vfs *pVfs,
16728   const char *zFile,
16729   sqlite3_file **ppFile,
16730   int flags,
16731   int *pOutFlags
16732 ){
16733   int rc = SQLITE_NOMEM;
16734   sqlite3_file *pFile;
16735   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
16736   if( pFile ){
16737     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
16738     if( rc!=SQLITE_OK ){
16739       sqlite3_free(pFile);
16740     }else{
16741       *ppFile = pFile;
16742     }
16743   }
16744   return rc;
16745 }
sqlite3OsCloseFree(sqlite3_file * pFile)16746 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
16747   int rc = SQLITE_OK;
16748   assert( pFile );
16749   rc = sqlite3OsClose(pFile);
16750   sqlite3_free(pFile);
16751   return rc;
16752 }
16753 
16754 /*
16755 ** This function is a wrapper around the OS specific implementation of
16756 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
16757 ** ability to simulate a malloc failure, so that the handling of an
16758 ** error in sqlite3_os_init() by the upper layers can be tested.
16759 */
sqlite3OsInit(void)16760 SQLITE_PRIVATE int sqlite3OsInit(void){
16761   void *p = sqlite3_malloc(10);
16762   if( p==0 ) return SQLITE_NOMEM;
16763   sqlite3_free(p);
16764   return sqlite3_os_init();
16765 }
16766 
16767 /*
16768 ** The list of all registered VFS implementations.
16769 */
16770 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
16771 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
16772 
16773 /*
16774 ** Locate a VFS by name.  If no name is given, simply return the
16775 ** first VFS on the list.
16776 */
sqlite3_vfs_find(const char * zVfs)16777 SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfs){
16778   sqlite3_vfs *pVfs = 0;
16779 #if SQLITE_THREADSAFE
16780   sqlite3_mutex *mutex;
16781 #endif
16782 #ifndef SQLITE_OMIT_AUTOINIT
16783   int rc = sqlite3_initialize();
16784   if( rc ) return 0;
16785 #endif
16786 #if SQLITE_THREADSAFE
16787   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
16788 #endif
16789   sqlite3_mutex_enter(mutex);
16790   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
16791     if( zVfs==0 ) break;
16792     if( strcmp(zVfs, pVfs->zName)==0 ) break;
16793   }
16794   sqlite3_mutex_leave(mutex);
16795   return pVfs;
16796 }
16797 
16798 /*
16799 ** Unlink a VFS from the linked list
16800 */
vfsUnlink(sqlite3_vfs * pVfs)16801 static void vfsUnlink(sqlite3_vfs *pVfs){
16802   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
16803   if( pVfs==0 ){
16804     /* No-op */
16805   }else if( vfsList==pVfs ){
16806     vfsList = pVfs->pNext;
16807   }else if( vfsList ){
16808     sqlite3_vfs *p = vfsList;
16809     while( p->pNext && p->pNext!=pVfs ){
16810       p = p->pNext;
16811     }
16812     if( p->pNext==pVfs ){
16813       p->pNext = pVfs->pNext;
16814     }
16815   }
16816 }
16817 
16818 /*
16819 ** Register a VFS with the system.  It is harmless to register the same
16820 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
16821 ** true.
16822 */
sqlite3_vfs_register(sqlite3_vfs * pVfs,int makeDflt)16823 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
16824   MUTEX_LOGIC(sqlite3_mutex *mutex;)
16825 #ifndef SQLITE_OMIT_AUTOINIT
16826   int rc = sqlite3_initialize();
16827   if( rc ) return rc;
16828 #endif
16829 #ifdef SQLITE_ENABLE_API_ARMOR
16830   if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
16831 #endif
16832 
16833   MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
16834   sqlite3_mutex_enter(mutex);
16835   vfsUnlink(pVfs);
16836   if( makeDflt || vfsList==0 ){
16837     pVfs->pNext = vfsList;
16838     vfsList = pVfs;
16839   }else{
16840     pVfs->pNext = vfsList->pNext;
16841     vfsList->pNext = pVfs;
16842   }
16843   assert(vfsList);
16844   sqlite3_mutex_leave(mutex);
16845   return SQLITE_OK;
16846 }
16847 
16848 /*
16849 ** Unregister a VFS so that it is no longer accessible.
16850 */
sqlite3_vfs_unregister(sqlite3_vfs * pVfs)16851 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
16852 #if SQLITE_THREADSAFE
16853   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
16854 #endif
16855   sqlite3_mutex_enter(mutex);
16856   vfsUnlink(pVfs);
16857   sqlite3_mutex_leave(mutex);
16858   return SQLITE_OK;
16859 }
16860 
16861 /************** End of os.c **************************************************/
16862 /************** Begin file fault.c *******************************************/
16863 /*
16864 ** 2008 Jan 22
16865 **
16866 ** The author disclaims copyright to this source code.  In place of
16867 ** a legal notice, here is a blessing:
16868 **
16869 **    May you do good and not evil.
16870 **    May you find forgiveness for yourself and forgive others.
16871 **    May you share freely, never taking more than you give.
16872 **
16873 *************************************************************************
16874 **
16875 ** This file contains code to support the concept of "benign"
16876 ** malloc failures (when the xMalloc() or xRealloc() method of the
16877 ** sqlite3_mem_methods structure fails to allocate a block of memory
16878 ** and returns 0).
16879 **
16880 ** Most malloc failures are non-benign. After they occur, SQLite
16881 ** abandons the current operation and returns an error code (usually
16882 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
16883 ** fatal. For example, if a malloc fails while resizing a hash table, this
16884 ** is completely recoverable simply by not carrying out the resize. The
16885 ** hash table will continue to function normally.  So a malloc failure
16886 ** during a hash table resize is a benign fault.
16887 */
16888 
16889 
16890 #ifndef SQLITE_OMIT_BUILTIN_TEST
16891 
16892 /*
16893 ** Global variables.
16894 */
16895 typedef struct BenignMallocHooks BenignMallocHooks;
16896 static SQLITE_WSD struct BenignMallocHooks {
16897   void (*xBenignBegin)(void);
16898   void (*xBenignEnd)(void);
16899 } sqlite3Hooks = { 0, 0 };
16900 
16901 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
16902 ** structure.  If writable static data is unsupported on the target,
16903 ** we have to locate the state vector at run-time.  In the more common
16904 ** case where writable static data is supported, wsdHooks can refer directly
16905 ** to the "sqlite3Hooks" state vector declared above.
16906 */
16907 #ifdef SQLITE_OMIT_WSD
16908 # define wsdHooksInit \
16909   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
16910 # define wsdHooks x[0]
16911 #else
16912 # define wsdHooksInit
16913 # define wsdHooks sqlite3Hooks
16914 #endif
16915 
16916 
16917 /*
16918 ** Register hooks to call when sqlite3BeginBenignMalloc() and
16919 ** sqlite3EndBenignMalloc() are called, respectively.
16920 */
sqlite3BenignMallocHooks(void (* xBenignBegin)(void),void (* xBenignEnd)(void))16921 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
16922   void (*xBenignBegin)(void),
16923   void (*xBenignEnd)(void)
16924 ){
16925   wsdHooksInit;
16926   wsdHooks.xBenignBegin = xBenignBegin;
16927   wsdHooks.xBenignEnd = xBenignEnd;
16928 }
16929 
16930 /*
16931 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
16932 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
16933 ** indicates that subsequent malloc failures are non-benign.
16934 */
sqlite3BeginBenignMalloc(void)16935 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
16936   wsdHooksInit;
16937   if( wsdHooks.xBenignBegin ){
16938     wsdHooks.xBenignBegin();
16939   }
16940 }
sqlite3EndBenignMalloc(void)16941 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
16942   wsdHooksInit;
16943   if( wsdHooks.xBenignEnd ){
16944     wsdHooks.xBenignEnd();
16945   }
16946 }
16947 
16948 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
16949 
16950 /************** End of fault.c ***********************************************/
16951 /************** Begin file mem0.c ********************************************/
16952 /*
16953 ** 2008 October 28
16954 **
16955 ** The author disclaims copyright to this source code.  In place of
16956 ** a legal notice, here is a blessing:
16957 **
16958 **    May you do good and not evil.
16959 **    May you find forgiveness for yourself and forgive others.
16960 **    May you share freely, never taking more than you give.
16961 **
16962 *************************************************************************
16963 **
16964 ** This file contains a no-op memory allocation drivers for use when
16965 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
16966 ** here always fail.  SQLite will not operate with these drivers.  These
16967 ** are merely placeholders.  Real drivers must be substituted using
16968 ** sqlite3_config() before SQLite will operate.
16969 */
16970 
16971 /*
16972 ** This version of the memory allocator is the default.  It is
16973 ** used when no other memory allocator is specified using compile-time
16974 ** macros.
16975 */
16976 #ifdef SQLITE_ZERO_MALLOC
16977 
16978 /*
16979 ** No-op versions of all memory allocation routines
16980 */
sqlite3MemMalloc(int nByte)16981 static void *sqlite3MemMalloc(int nByte){ return 0; }
sqlite3MemFree(void * pPrior)16982 static void sqlite3MemFree(void *pPrior){ return; }
sqlite3MemRealloc(void * pPrior,int nByte)16983 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
sqlite3MemSize(void * pPrior)16984 static int sqlite3MemSize(void *pPrior){ return 0; }
sqlite3MemRoundup(int n)16985 static int sqlite3MemRoundup(int n){ return n; }
sqlite3MemInit(void * NotUsed)16986 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
sqlite3MemShutdown(void * NotUsed)16987 static void sqlite3MemShutdown(void *NotUsed){ return; }
16988 
16989 /*
16990 ** This routine is the only routine in this file with external linkage.
16991 **
16992 ** Populate the low-level memory allocation function pointers in
16993 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16994 */
sqlite3MemSetDefault(void)16995 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16996   static const sqlite3_mem_methods defaultMethods = {
16997      sqlite3MemMalloc,
16998      sqlite3MemFree,
16999      sqlite3MemRealloc,
17000      sqlite3MemSize,
17001      sqlite3MemRoundup,
17002      sqlite3MemInit,
17003      sqlite3MemShutdown,
17004      0
17005   };
17006   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
17007 }
17008 
17009 #endif /* SQLITE_ZERO_MALLOC */
17010 
17011 /************** End of mem0.c ************************************************/
17012 /************** Begin file mem1.c ********************************************/
17013 /*
17014 ** 2007 August 14
17015 **
17016 ** The author disclaims copyright to this source code.  In place of
17017 ** a legal notice, here is a blessing:
17018 **
17019 **    May you do good and not evil.
17020 **    May you find forgiveness for yourself and forgive others.
17021 **    May you share freely, never taking more than you give.
17022 **
17023 *************************************************************************
17024 **
17025 ** This file contains low-level memory allocation drivers for when
17026 ** SQLite will use the standard C-library malloc/realloc/free interface
17027 ** to obtain the memory it needs.
17028 **
17029 ** This file contains implementations of the low-level memory allocation
17030 ** routines specified in the sqlite3_mem_methods object.  The content of
17031 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
17032 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
17033 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
17034 ** default configuration is to use memory allocation routines in this
17035 ** file.
17036 **
17037 ** C-preprocessor macro summary:
17038 **
17039 **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
17040 **                                the malloc_usable_size() interface exists
17041 **                                on the target platform.  Or, this symbol
17042 **                                can be set manually, if desired.
17043 **                                If an equivalent interface exists by
17044 **                                a different name, using a separate -D
17045 **                                option to rename it.
17046 **
17047 **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
17048 **                                memory allocator.  Set this symbol to enable
17049 **                                building on older macs.
17050 **
17051 **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
17052 **                                _msize() on windows systems.  This might
17053 **                                be necessary when compiling for Delphi,
17054 **                                for example.
17055 */
17056 
17057 /*
17058 ** This version of the memory allocator is the default.  It is
17059 ** used when no other memory allocator is specified using compile-time
17060 ** macros.
17061 */
17062 #ifdef SQLITE_SYSTEM_MALLOC
17063 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
17064 
17065 /*
17066 ** Use the zone allocator available on apple products unless the
17067 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
17068 */
17069 #include <sys/sysctl.h>
17070 #include <malloc/malloc.h>
17071 #include <libkern/OSAtomic.h>
17072 static malloc_zone_t* _sqliteZone_;
17073 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
17074 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
17075 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
17076 #define SQLITE_MALLOCSIZE(x) \
17077         (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
17078 
17079 #else /* if not __APPLE__ */
17080 
17081 /*
17082 ** Use standard C library malloc and free on non-Apple systems.
17083 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
17084 */
17085 #define SQLITE_MALLOC(x)             malloc(x)
17086 #define SQLITE_FREE(x)               free(x)
17087 #define SQLITE_REALLOC(x,y)          realloc((x),(y))
17088 
17089 /*
17090 ** The malloc.h header file is needed for malloc_usable_size() function
17091 ** on some systems (e.g. Linux).
17092 */
17093 #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
17094 #  define SQLITE_USE_MALLOC_H 1
17095 #  define SQLITE_USE_MALLOC_USABLE_SIZE 1
17096 /*
17097 ** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
17098 ** use of _msize() is automatic, but can be disabled by compiling with
17099 ** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
17100 ** the malloc.h header file.
17101 */
17102 #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
17103 #  define SQLITE_USE_MALLOC_H
17104 #  define SQLITE_USE_MSIZE
17105 #endif
17106 
17107 /*
17108 ** Include the malloc.h header file, if necessary.  Also set define macro
17109 ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
17110 ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
17111 ** The memory size function can always be overridden manually by defining
17112 ** the macro SQLITE_MALLOCSIZE to the desired function name.
17113 */
17114 #if defined(SQLITE_USE_MALLOC_H)
17115 #  include <malloc.h>
17116 #  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
17117 #    if !defined(SQLITE_MALLOCSIZE)
17118 #      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
17119 #    endif
17120 #  elif defined(SQLITE_USE_MSIZE)
17121 #    if !defined(SQLITE_MALLOCSIZE)
17122 #      define SQLITE_MALLOCSIZE      _msize
17123 #    endif
17124 #  endif
17125 #endif /* defined(SQLITE_USE_MALLOC_H) */
17126 
17127 #endif /* __APPLE__ or not __APPLE__ */
17128 
17129 /*
17130 ** Like malloc(), but remember the size of the allocation
17131 ** so that we can find it later using sqlite3MemSize().
17132 **
17133 ** For this low-level routine, we are guaranteed that nByte>0 because
17134 ** cases of nByte<=0 will be intercepted and dealt with by higher level
17135 ** routines.
17136 */
sqlite3MemMalloc(int nByte)17137 static void *sqlite3MemMalloc(int nByte){
17138 #ifdef SQLITE_MALLOCSIZE
17139   void *p = SQLITE_MALLOC( nByte );
17140   if( p==0 ){
17141     testcase( sqlite3GlobalConfig.xLog!=0 );
17142     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
17143   }
17144   return p;
17145 #else
17146   sqlite3_int64 *p;
17147   assert( nByte>0 );
17148   nByte = ROUND8(nByte);
17149   p = SQLITE_MALLOC( nByte+8 );
17150   if( p ){
17151     p[0] = nByte;
17152     p++;
17153   }else{
17154     testcase( sqlite3GlobalConfig.xLog!=0 );
17155     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
17156   }
17157   return (void *)p;
17158 #endif
17159 }
17160 
17161 /*
17162 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
17163 ** or sqlite3MemRealloc().
17164 **
17165 ** For this low-level routine, we already know that pPrior!=0 since
17166 ** cases where pPrior==0 will have been intecepted and dealt with
17167 ** by higher-level routines.
17168 */
sqlite3MemFree(void * pPrior)17169 static void sqlite3MemFree(void *pPrior){
17170 #ifdef SQLITE_MALLOCSIZE
17171   SQLITE_FREE(pPrior);
17172 #else
17173   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
17174   assert( pPrior!=0 );
17175   p--;
17176   SQLITE_FREE(p);
17177 #endif
17178 }
17179 
17180 /*
17181 ** Report the allocated size of a prior return from xMalloc()
17182 ** or xRealloc().
17183 */
sqlite3MemSize(void * pPrior)17184 static int sqlite3MemSize(void *pPrior){
17185 #ifdef SQLITE_MALLOCSIZE
17186   return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
17187 #else
17188   sqlite3_int64 *p;
17189   if( pPrior==0 ) return 0;
17190   p = (sqlite3_int64*)pPrior;
17191   p--;
17192   return (int)p[0];
17193 #endif
17194 }
17195 
17196 /*
17197 ** Like realloc().  Resize an allocation previously obtained from
17198 ** sqlite3MemMalloc().
17199 **
17200 ** For this low-level interface, we know that pPrior!=0.  Cases where
17201 ** pPrior==0 while have been intercepted by higher-level routine and
17202 ** redirected to xMalloc.  Similarly, we know that nByte>0 because
17203 ** cases where nByte<=0 will have been intercepted by higher-level
17204 ** routines and redirected to xFree.
17205 */
sqlite3MemRealloc(void * pPrior,int nByte)17206 static void *sqlite3MemRealloc(void *pPrior, int nByte){
17207 #ifdef SQLITE_MALLOCSIZE
17208   void *p = SQLITE_REALLOC(pPrior, nByte);
17209   if( p==0 ){
17210     testcase( sqlite3GlobalConfig.xLog!=0 );
17211     sqlite3_log(SQLITE_NOMEM,
17212       "failed memory resize %u to %u bytes",
17213       SQLITE_MALLOCSIZE(pPrior), nByte);
17214   }
17215   return p;
17216 #else
17217   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
17218   assert( pPrior!=0 && nByte>0 );
17219   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
17220   p--;
17221   p = SQLITE_REALLOC(p, nByte+8 );
17222   if( p ){
17223     p[0] = nByte;
17224     p++;
17225   }else{
17226     testcase( sqlite3GlobalConfig.xLog!=0 );
17227     sqlite3_log(SQLITE_NOMEM,
17228       "failed memory resize %u to %u bytes",
17229       sqlite3MemSize(pPrior), nByte);
17230   }
17231   return (void*)p;
17232 #endif
17233 }
17234 
17235 /*
17236 ** Round up a request size to the next valid allocation size.
17237 */
sqlite3MemRoundup(int n)17238 static int sqlite3MemRoundup(int n){
17239   return ROUND8(n);
17240 }
17241 
17242 /*
17243 ** Initialize this module.
17244 */
sqlite3MemInit(void * NotUsed)17245 static int sqlite3MemInit(void *NotUsed){
17246 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
17247   int cpuCount;
17248   size_t len;
17249   if( _sqliteZone_ ){
17250     return SQLITE_OK;
17251   }
17252   len = sizeof(cpuCount);
17253   /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
17254   sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
17255   if( cpuCount>1 ){
17256     /* defer MT decisions to system malloc */
17257     _sqliteZone_ = malloc_default_zone();
17258   }else{
17259     /* only 1 core, use our own zone to contention over global locks,
17260     ** e.g. we have our own dedicated locks */
17261     bool success;
17262     malloc_zone_t* newzone = malloc_create_zone(4096, 0);
17263     malloc_set_zone_name(newzone, "Sqlite_Heap");
17264     do{
17265       success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
17266                                  (void * volatile *)&_sqliteZone_);
17267     }while(!_sqliteZone_);
17268     if( !success ){
17269       /* somebody registered a zone first */
17270       malloc_destroy_zone(newzone);
17271     }
17272   }
17273 #endif
17274   UNUSED_PARAMETER(NotUsed);
17275   return SQLITE_OK;
17276 }
17277 
17278 /*
17279 ** Deinitialize this module.
17280 */
sqlite3MemShutdown(void * NotUsed)17281 static void sqlite3MemShutdown(void *NotUsed){
17282   UNUSED_PARAMETER(NotUsed);
17283   return;
17284 }
17285 
17286 /*
17287 ** This routine is the only routine in this file with external linkage.
17288 **
17289 ** Populate the low-level memory allocation function pointers in
17290 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
17291 */
sqlite3MemSetDefault(void)17292 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
17293   static const sqlite3_mem_methods defaultMethods = {
17294      sqlite3MemMalloc,
17295      sqlite3MemFree,
17296      sqlite3MemRealloc,
17297      sqlite3MemSize,
17298      sqlite3MemRoundup,
17299      sqlite3MemInit,
17300      sqlite3MemShutdown,
17301      0
17302   };
17303   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
17304 }
17305 
17306 #endif /* SQLITE_SYSTEM_MALLOC */
17307 
17308 /************** End of mem1.c ************************************************/
17309 /************** Begin file mem2.c ********************************************/
17310 /*
17311 ** 2007 August 15
17312 **
17313 ** The author disclaims copyright to this source code.  In place of
17314 ** a legal notice, here is a blessing:
17315 **
17316 **    May you do good and not evil.
17317 **    May you find forgiveness for yourself and forgive others.
17318 **    May you share freely, never taking more than you give.
17319 **
17320 *************************************************************************
17321 **
17322 ** This file contains low-level memory allocation drivers for when
17323 ** SQLite will use the standard C-library malloc/realloc/free interface
17324 ** to obtain the memory it needs while adding lots of additional debugging
17325 ** information to each allocation in order to help detect and fix memory
17326 ** leaks and memory usage errors.
17327 **
17328 ** This file contains implementations of the low-level memory allocation
17329 ** routines specified in the sqlite3_mem_methods object.
17330 */
17331 
17332 /*
17333 ** This version of the memory allocator is used only if the
17334 ** SQLITE_MEMDEBUG macro is defined
17335 */
17336 #ifdef SQLITE_MEMDEBUG
17337 
17338 /*
17339 ** The backtrace functionality is only available with GLIBC
17340 */
17341 #ifdef __GLIBC__
17342   extern int backtrace(void**,int);
17343   extern void backtrace_symbols_fd(void*const*,int,int);
17344 #else
17345 # define backtrace(A,B) 1
17346 # define backtrace_symbols_fd(A,B,C)
17347 #endif
17348 /* #include <stdio.h> */
17349 
17350 /*
17351 ** Each memory allocation looks like this:
17352 **
17353 **  ------------------------------------------------------------------------
17354 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
17355 **  ------------------------------------------------------------------------
17356 **
17357 ** The application code sees only a pointer to the allocation.  We have
17358 ** to back up from the allocation pointer to find the MemBlockHdr.  The
17359 ** MemBlockHdr tells us the size of the allocation and the number of
17360 ** backtrace pointers.  There is also a guard word at the end of the
17361 ** MemBlockHdr.
17362 */
17363 struct MemBlockHdr {
17364   i64 iSize;                          /* Size of this allocation */
17365   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
17366   char nBacktrace;                    /* Number of backtraces on this alloc */
17367   char nBacktraceSlots;               /* Available backtrace slots */
17368   u8 nTitle;                          /* Bytes of title; includes '\0' */
17369   u8 eType;                           /* Allocation type code */
17370   int iForeGuard;                     /* Guard word for sanity */
17371 };
17372 
17373 /*
17374 ** Guard words
17375 */
17376 #define FOREGUARD 0x80F5E153
17377 #define REARGUARD 0xE4676B53
17378 
17379 /*
17380 ** Number of malloc size increments to track.
17381 */
17382 #define NCSIZE  1000
17383 
17384 /*
17385 ** All of the static variables used by this module are collected
17386 ** into a single structure named "mem".  This is to keep the
17387 ** static variables organized and to reduce namespace pollution
17388 ** when this module is combined with other in the amalgamation.
17389 */
17390 static struct {
17391 
17392   /*
17393   ** Mutex to control access to the memory allocation subsystem.
17394   */
17395   sqlite3_mutex *mutex;
17396 
17397   /*
17398   ** Head and tail of a linked list of all outstanding allocations
17399   */
17400   struct MemBlockHdr *pFirst;
17401   struct MemBlockHdr *pLast;
17402 
17403   /*
17404   ** The number of levels of backtrace to save in new allocations.
17405   */
17406   int nBacktrace;
17407   void (*xBacktrace)(int, int, void **);
17408 
17409   /*
17410   ** Title text to insert in front of each block
17411   */
17412   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
17413   char zTitle[100];  /* The title text */
17414 
17415   /*
17416   ** sqlite3MallocDisallow() increments the following counter.
17417   ** sqlite3MallocAllow() decrements it.
17418   */
17419   int disallow; /* Do not allow memory allocation */
17420 
17421   /*
17422   ** Gather statistics on the sizes of memory allocations.
17423   ** nAlloc[i] is the number of allocation attempts of i*8
17424   ** bytes.  i==NCSIZE is the number of allocation attempts for
17425   ** sizes more than NCSIZE*8 bytes.
17426   */
17427   int nAlloc[NCSIZE];      /* Total number of allocations */
17428   int nCurrent[NCSIZE];    /* Current number of allocations */
17429   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
17430 
17431 } mem;
17432 
17433 
17434 /*
17435 ** Adjust memory usage statistics
17436 */
adjustStats(int iSize,int increment)17437 static void adjustStats(int iSize, int increment){
17438   int i = ROUND8(iSize)/8;
17439   if( i>NCSIZE-1 ){
17440     i = NCSIZE - 1;
17441   }
17442   if( increment>0 ){
17443     mem.nAlloc[i]++;
17444     mem.nCurrent[i]++;
17445     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
17446       mem.mxCurrent[i] = mem.nCurrent[i];
17447     }
17448   }else{
17449     mem.nCurrent[i]--;
17450     assert( mem.nCurrent[i]>=0 );
17451   }
17452 }
17453 
17454 /*
17455 ** Given an allocation, find the MemBlockHdr for that allocation.
17456 **
17457 ** This routine checks the guards at either end of the allocation and
17458 ** if they are incorrect it asserts.
17459 */
sqlite3MemsysGetHeader(void * pAllocation)17460 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
17461   struct MemBlockHdr *p;
17462   int *pInt;
17463   u8 *pU8;
17464   int nReserve;
17465 
17466   p = (struct MemBlockHdr*)pAllocation;
17467   p--;
17468   assert( p->iForeGuard==(int)FOREGUARD );
17469   nReserve = ROUND8(p->iSize);
17470   pInt = (int*)pAllocation;
17471   pU8 = (u8*)pAllocation;
17472   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
17473   /* This checks any of the "extra" bytes allocated due
17474   ** to rounding up to an 8 byte boundary to ensure
17475   ** they haven't been overwritten.
17476   */
17477   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
17478   return p;
17479 }
17480 
17481 /*
17482 ** Return the number of bytes currently allocated at address p.
17483 */
sqlite3MemSize(void * p)17484 static int sqlite3MemSize(void *p){
17485   struct MemBlockHdr *pHdr;
17486   if( !p ){
17487     return 0;
17488   }
17489   pHdr = sqlite3MemsysGetHeader(p);
17490   return (int)pHdr->iSize;
17491 }
17492 
17493 /*
17494 ** Initialize the memory allocation subsystem.
17495 */
sqlite3MemInit(void * NotUsed)17496 static int sqlite3MemInit(void *NotUsed){
17497   UNUSED_PARAMETER(NotUsed);
17498   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
17499   if( !sqlite3GlobalConfig.bMemstat ){
17500     /* If memory status is enabled, then the malloc.c wrapper will already
17501     ** hold the STATIC_MEM mutex when the routines here are invoked. */
17502     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17503   }
17504   return SQLITE_OK;
17505 }
17506 
17507 /*
17508 ** Deinitialize the memory allocation subsystem.
17509 */
sqlite3MemShutdown(void * NotUsed)17510 static void sqlite3MemShutdown(void *NotUsed){
17511   UNUSED_PARAMETER(NotUsed);
17512   mem.mutex = 0;
17513 }
17514 
17515 /*
17516 ** Round up a request size to the next valid allocation size.
17517 */
sqlite3MemRoundup(int n)17518 static int sqlite3MemRoundup(int n){
17519   return ROUND8(n);
17520 }
17521 
17522 /*
17523 ** Fill a buffer with pseudo-random bytes.  This is used to preset
17524 ** the content of a new memory allocation to unpredictable values and
17525 ** to clear the content of a freed allocation to unpredictable values.
17526 */
randomFill(char * pBuf,int nByte)17527 static void randomFill(char *pBuf, int nByte){
17528   unsigned int x, y, r;
17529   x = SQLITE_PTR_TO_INT(pBuf);
17530   y = nByte | 1;
17531   while( nByte >= 4 ){
17532     x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
17533     y = y*1103515245 + 12345;
17534     r = x ^ y;
17535     *(int*)pBuf = r;
17536     pBuf += 4;
17537     nByte -= 4;
17538   }
17539   while( nByte-- > 0 ){
17540     x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
17541     y = y*1103515245 + 12345;
17542     r = x ^ y;
17543     *(pBuf++) = r & 0xff;
17544   }
17545 }
17546 
17547 /*
17548 ** Allocate nByte bytes of memory.
17549 */
sqlite3MemMalloc(int nByte)17550 static void *sqlite3MemMalloc(int nByte){
17551   struct MemBlockHdr *pHdr;
17552   void **pBt;
17553   char *z;
17554   int *pInt;
17555   void *p = 0;
17556   int totalSize;
17557   int nReserve;
17558   sqlite3_mutex_enter(mem.mutex);
17559   assert( mem.disallow==0 );
17560   nReserve = ROUND8(nByte);
17561   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
17562                mem.nBacktrace*sizeof(void*) + mem.nTitle;
17563   p = malloc(totalSize);
17564   if( p ){
17565     z = p;
17566     pBt = (void**)&z[mem.nTitle];
17567     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
17568     pHdr->pNext = 0;
17569     pHdr->pPrev = mem.pLast;
17570     if( mem.pLast ){
17571       mem.pLast->pNext = pHdr;
17572     }else{
17573       mem.pFirst = pHdr;
17574     }
17575     mem.pLast = pHdr;
17576     pHdr->iForeGuard = FOREGUARD;
17577     pHdr->eType = MEMTYPE_HEAP;
17578     pHdr->nBacktraceSlots = mem.nBacktrace;
17579     pHdr->nTitle = mem.nTitle;
17580     if( mem.nBacktrace ){
17581       void *aAddr[40];
17582       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
17583       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
17584       assert(pBt[0]);
17585       if( mem.xBacktrace ){
17586         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
17587       }
17588     }else{
17589       pHdr->nBacktrace = 0;
17590     }
17591     if( mem.nTitle ){
17592       memcpy(z, mem.zTitle, mem.nTitle);
17593     }
17594     pHdr->iSize = nByte;
17595     adjustStats(nByte, +1);
17596     pInt = (int*)&pHdr[1];
17597     pInt[nReserve/sizeof(int)] = REARGUARD;
17598     randomFill((char*)pInt, nByte);
17599     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
17600     p = (void*)pInt;
17601   }
17602   sqlite3_mutex_leave(mem.mutex);
17603   return p;
17604 }
17605 
17606 /*
17607 ** Free memory.
17608 */
sqlite3MemFree(void * pPrior)17609 static void sqlite3MemFree(void *pPrior){
17610   struct MemBlockHdr *pHdr;
17611   void **pBt;
17612   char *z;
17613   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
17614        || mem.mutex!=0 );
17615   pHdr = sqlite3MemsysGetHeader(pPrior);
17616   pBt = (void**)pHdr;
17617   pBt -= pHdr->nBacktraceSlots;
17618   sqlite3_mutex_enter(mem.mutex);
17619   if( pHdr->pPrev ){
17620     assert( pHdr->pPrev->pNext==pHdr );
17621     pHdr->pPrev->pNext = pHdr->pNext;
17622   }else{
17623     assert( mem.pFirst==pHdr );
17624     mem.pFirst = pHdr->pNext;
17625   }
17626   if( pHdr->pNext ){
17627     assert( pHdr->pNext->pPrev==pHdr );
17628     pHdr->pNext->pPrev = pHdr->pPrev;
17629   }else{
17630     assert( mem.pLast==pHdr );
17631     mem.pLast = pHdr->pPrev;
17632   }
17633   z = (char*)pBt;
17634   z -= pHdr->nTitle;
17635   adjustStats((int)pHdr->iSize, -1);
17636   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
17637                 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
17638   free(z);
17639   sqlite3_mutex_leave(mem.mutex);
17640 }
17641 
17642 /*
17643 ** Change the size of an existing memory allocation.
17644 **
17645 ** For this debugging implementation, we *always* make a copy of the
17646 ** allocation into a new place in memory.  In this way, if the
17647 ** higher level code is using pointer to the old allocation, it is
17648 ** much more likely to break and we are much more liking to find
17649 ** the error.
17650 */
sqlite3MemRealloc(void * pPrior,int nByte)17651 static void *sqlite3MemRealloc(void *pPrior, int nByte){
17652   struct MemBlockHdr *pOldHdr;
17653   void *pNew;
17654   assert( mem.disallow==0 );
17655   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
17656   pOldHdr = sqlite3MemsysGetHeader(pPrior);
17657   pNew = sqlite3MemMalloc(nByte);
17658   if( pNew ){
17659     memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
17660     if( nByte>pOldHdr->iSize ){
17661       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
17662     }
17663     sqlite3MemFree(pPrior);
17664   }
17665   return pNew;
17666 }
17667 
17668 /*
17669 ** Populate the low-level memory allocation function pointers in
17670 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
17671 */
sqlite3MemSetDefault(void)17672 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
17673   static const sqlite3_mem_methods defaultMethods = {
17674      sqlite3MemMalloc,
17675      sqlite3MemFree,
17676      sqlite3MemRealloc,
17677      sqlite3MemSize,
17678      sqlite3MemRoundup,
17679      sqlite3MemInit,
17680      sqlite3MemShutdown,
17681      0
17682   };
17683   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
17684 }
17685 
17686 /*
17687 ** Set the "type" of an allocation.
17688 */
sqlite3MemdebugSetType(void * p,u8 eType)17689 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
17690   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
17691     struct MemBlockHdr *pHdr;
17692     pHdr = sqlite3MemsysGetHeader(p);
17693     assert( pHdr->iForeGuard==FOREGUARD );
17694     pHdr->eType = eType;
17695   }
17696 }
17697 
17698 /*
17699 ** Return TRUE if the mask of type in eType matches the type of the
17700 ** allocation p.  Also return true if p==NULL.
17701 **
17702 ** This routine is designed for use within an assert() statement, to
17703 ** verify the type of an allocation.  For example:
17704 **
17705 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17706 */
sqlite3MemdebugHasType(void * p,u8 eType)17707 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
17708   int rc = 1;
17709   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
17710     struct MemBlockHdr *pHdr;
17711     pHdr = sqlite3MemsysGetHeader(p);
17712     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
17713     if( (pHdr->eType&eType)==0 ){
17714       rc = 0;
17715     }
17716   }
17717   return rc;
17718 }
17719 
17720 /*
17721 ** Return TRUE if the mask of type in eType matches no bits of the type of the
17722 ** allocation p.  Also return true if p==NULL.
17723 **
17724 ** This routine is designed for use within an assert() statement, to
17725 ** verify the type of an allocation.  For example:
17726 **
17727 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
17728 */
sqlite3MemdebugNoType(void * p,u8 eType)17729 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
17730   int rc = 1;
17731   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
17732     struct MemBlockHdr *pHdr;
17733     pHdr = sqlite3MemsysGetHeader(p);
17734     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
17735     if( (pHdr->eType&eType)!=0 ){
17736       rc = 0;
17737     }
17738   }
17739   return rc;
17740 }
17741 
17742 /*
17743 ** Set the number of backtrace levels kept for each allocation.
17744 ** A value of zero turns off backtracing.  The number is always rounded
17745 ** up to a multiple of 2.
17746 */
sqlite3MemdebugBacktrace(int depth)17747 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
17748   if( depth<0 ){ depth = 0; }
17749   if( depth>20 ){ depth = 20; }
17750   depth = (depth+1)&0xfe;
17751   mem.nBacktrace = depth;
17752 }
17753 
sqlite3MemdebugBacktraceCallback(void (* xBacktrace)(int,int,void **))17754 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
17755   mem.xBacktrace = xBacktrace;
17756 }
17757 
17758 /*
17759 ** Set the title string for subsequent allocations.
17760 */
sqlite3MemdebugSettitle(const char * zTitle)17761 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
17762   unsigned int n = sqlite3Strlen30(zTitle) + 1;
17763   sqlite3_mutex_enter(mem.mutex);
17764   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
17765   memcpy(mem.zTitle, zTitle, n);
17766   mem.zTitle[n] = 0;
17767   mem.nTitle = ROUND8(n);
17768   sqlite3_mutex_leave(mem.mutex);
17769 }
17770 
sqlite3MemdebugSync()17771 SQLITE_PRIVATE void sqlite3MemdebugSync(){
17772   struct MemBlockHdr *pHdr;
17773   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
17774     void **pBt = (void**)pHdr;
17775     pBt -= pHdr->nBacktraceSlots;
17776     mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
17777   }
17778 }
17779 
17780 /*
17781 ** Open the file indicated and write a log of all unfreed memory
17782 ** allocations into that log.
17783 */
sqlite3MemdebugDump(const char * zFilename)17784 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
17785   FILE *out;
17786   struct MemBlockHdr *pHdr;
17787   void **pBt;
17788   int i;
17789   out = fopen(zFilename, "w");
17790   if( out==0 ){
17791     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17792                     zFilename);
17793     return;
17794   }
17795   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
17796     char *z = (char*)pHdr;
17797     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
17798     fprintf(out, "**** %lld bytes at %p from %s ****\n",
17799             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
17800     if( pHdr->nBacktrace ){
17801       fflush(out);
17802       pBt = (void**)pHdr;
17803       pBt -= pHdr->nBacktraceSlots;
17804       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
17805       fprintf(out, "\n");
17806     }
17807   }
17808   fprintf(out, "COUNTS:\n");
17809   for(i=0; i<NCSIZE-1; i++){
17810     if( mem.nAlloc[i] ){
17811       fprintf(out, "   %5d: %10d %10d %10d\n",
17812             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
17813     }
17814   }
17815   if( mem.nAlloc[NCSIZE-1] ){
17816     fprintf(out, "   %5d: %10d %10d %10d\n",
17817              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
17818              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
17819   }
17820   fclose(out);
17821 }
17822 
17823 /*
17824 ** Return the number of times sqlite3MemMalloc() has been called.
17825 */
sqlite3MemdebugMallocCount()17826 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
17827   int i;
17828   int nTotal = 0;
17829   for(i=0; i<NCSIZE; i++){
17830     nTotal += mem.nAlloc[i];
17831   }
17832   return nTotal;
17833 }
17834 
17835 
17836 #endif /* SQLITE_MEMDEBUG */
17837 
17838 /************** End of mem2.c ************************************************/
17839 /************** Begin file mem3.c ********************************************/
17840 /*
17841 ** 2007 October 14
17842 **
17843 ** The author disclaims copyright to this source code.  In place of
17844 ** a legal notice, here is a blessing:
17845 **
17846 **    May you do good and not evil.
17847 **    May you find forgiveness for yourself and forgive others.
17848 **    May you share freely, never taking more than you give.
17849 **
17850 *************************************************************************
17851 ** This file contains the C functions that implement a memory
17852 ** allocation subsystem for use by SQLite.
17853 **
17854 ** This version of the memory allocation subsystem omits all
17855 ** use of malloc(). The SQLite user supplies a block of memory
17856 ** before calling sqlite3_initialize() from which allocations
17857 ** are made and returned by the xMalloc() and xRealloc()
17858 ** implementations. Once sqlite3_initialize() has been called,
17859 ** the amount of memory available to SQLite is fixed and cannot
17860 ** be changed.
17861 **
17862 ** This version of the memory allocation subsystem is included
17863 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
17864 */
17865 
17866 /*
17867 ** This version of the memory allocator is only built into the library
17868 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
17869 ** mean that the library will use a memory-pool by default, just that
17870 ** it is available. The mempool allocator is activated by calling
17871 ** sqlite3_config().
17872 */
17873 #ifdef SQLITE_ENABLE_MEMSYS3
17874 
17875 /*
17876 ** Maximum size (in Mem3Blocks) of a "small" chunk.
17877 */
17878 #define MX_SMALL 10
17879 
17880 
17881 /*
17882 ** Number of freelist hash slots
17883 */
17884 #define N_HASH  61
17885 
17886 /*
17887 ** A memory allocation (also called a "chunk") consists of two or
17888 ** more blocks where each block is 8 bytes.  The first 8 bytes are
17889 ** a header that is not returned to the user.
17890 **
17891 ** A chunk is two or more blocks that is either checked out or
17892 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
17893 ** size of the allocation in blocks if the allocation is free.
17894 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
17895 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
17896 ** is true if the previous chunk is checked out and false if the
17897 ** previous chunk is free.  The u.hdr.prevSize field is the size of
17898 ** the previous chunk in blocks if the previous chunk is on the
17899 ** freelist. If the previous chunk is checked out, then
17900 ** u.hdr.prevSize can be part of the data for that chunk and should
17901 ** not be read or written.
17902 **
17903 ** We often identify a chunk by its index in mem3.aPool[].  When
17904 ** this is done, the chunk index refers to the second block of
17905 ** the chunk.  In this way, the first chunk has an index of 1.
17906 ** A chunk index of 0 means "no such chunk" and is the equivalent
17907 ** of a NULL pointer.
17908 **
17909 ** The second block of free chunks is of the form u.list.  The
17910 ** two fields form a double-linked list of chunks of related sizes.
17911 ** Pointers to the head of the list are stored in mem3.aiSmall[]
17912 ** for smaller chunks and mem3.aiHash[] for larger chunks.
17913 **
17914 ** The second block of a chunk is user data if the chunk is checked
17915 ** out.  If a chunk is checked out, the user data may extend into
17916 ** the u.hdr.prevSize value of the following chunk.
17917 */
17918 typedef struct Mem3Block Mem3Block;
17919 struct Mem3Block {
17920   union {
17921     struct {
17922       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
17923       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
17924     } hdr;
17925     struct {
17926       u32 next;       /* Index in mem3.aPool[] of next free chunk */
17927       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
17928     } list;
17929   } u;
17930 };
17931 
17932 /*
17933 ** All of the static variables used by this module are collected
17934 ** into a single structure named "mem3".  This is to keep the
17935 ** static variables organized and to reduce namespace pollution
17936 ** when this module is combined with other in the amalgamation.
17937 */
17938 static SQLITE_WSD struct Mem3Global {
17939   /*
17940   ** Memory available for allocation. nPool is the size of the array
17941   ** (in Mem3Blocks) pointed to by aPool less 2.
17942   */
17943   u32 nPool;
17944   Mem3Block *aPool;
17945 
17946   /*
17947   ** True if we are evaluating an out-of-memory callback.
17948   */
17949   int alarmBusy;
17950 
17951   /*
17952   ** Mutex to control access to the memory allocation subsystem.
17953   */
17954   sqlite3_mutex *mutex;
17955 
17956   /*
17957   ** The minimum amount of free space that we have seen.
17958   */
17959   u32 mnMaster;
17960 
17961   /*
17962   ** iMaster is the index of the master chunk.  Most new allocations
17963   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
17964   ** of the current master.  iMaster is 0 if there is not master chunk.
17965   ** The master chunk is not in either the aiHash[] or aiSmall[].
17966   */
17967   u32 iMaster;
17968   u32 szMaster;
17969 
17970   /*
17971   ** Array of lists of free blocks according to the block size
17972   ** for smaller chunks, or a hash on the block size for larger
17973   ** chunks.
17974   */
17975   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
17976   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
17977 } mem3 = { 97535575 };
17978 
17979 #define mem3 GLOBAL(struct Mem3Global, mem3)
17980 
17981 /*
17982 ** Unlink the chunk at mem3.aPool[i] from list it is currently
17983 ** on.  *pRoot is the list that i is a member of.
17984 */
memsys3UnlinkFromList(u32 i,u32 * pRoot)17985 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
17986   u32 next = mem3.aPool[i].u.list.next;
17987   u32 prev = mem3.aPool[i].u.list.prev;
17988   assert( sqlite3_mutex_held(mem3.mutex) );
17989   if( prev==0 ){
17990     *pRoot = next;
17991   }else{
17992     mem3.aPool[prev].u.list.next = next;
17993   }
17994   if( next ){
17995     mem3.aPool[next].u.list.prev = prev;
17996   }
17997   mem3.aPool[i].u.list.next = 0;
17998   mem3.aPool[i].u.list.prev = 0;
17999 }
18000 
18001 /*
18002 ** Unlink the chunk at index i from
18003 ** whatever list is currently a member of.
18004 */
memsys3Unlink(u32 i)18005 static void memsys3Unlink(u32 i){
18006   u32 size, hash;
18007   assert( sqlite3_mutex_held(mem3.mutex) );
18008   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
18009   assert( i>=1 );
18010   size = mem3.aPool[i-1].u.hdr.size4x/4;
18011   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
18012   assert( size>=2 );
18013   if( size <= MX_SMALL ){
18014     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
18015   }else{
18016     hash = size % N_HASH;
18017     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
18018   }
18019 }
18020 
18021 /*
18022 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
18023 ** at *pRoot.
18024 */
memsys3LinkIntoList(u32 i,u32 * pRoot)18025 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
18026   assert( sqlite3_mutex_held(mem3.mutex) );
18027   mem3.aPool[i].u.list.next = *pRoot;
18028   mem3.aPool[i].u.list.prev = 0;
18029   if( *pRoot ){
18030     mem3.aPool[*pRoot].u.list.prev = i;
18031   }
18032   *pRoot = i;
18033 }
18034 
18035 /*
18036 ** Link the chunk at index i into either the appropriate
18037 ** small chunk list, or into the large chunk hash table.
18038 */
memsys3Link(u32 i)18039 static void memsys3Link(u32 i){
18040   u32 size, hash;
18041   assert( sqlite3_mutex_held(mem3.mutex) );
18042   assert( i>=1 );
18043   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
18044   size = mem3.aPool[i-1].u.hdr.size4x/4;
18045   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
18046   assert( size>=2 );
18047   if( size <= MX_SMALL ){
18048     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
18049   }else{
18050     hash = size % N_HASH;
18051     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
18052   }
18053 }
18054 
18055 /*
18056 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
18057 ** will already be held (obtained by code in malloc.c) if
18058 ** sqlite3GlobalConfig.bMemStat is true.
18059 */
memsys3Enter(void)18060 static void memsys3Enter(void){
18061   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
18062     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18063   }
18064   sqlite3_mutex_enter(mem3.mutex);
18065 }
memsys3Leave(void)18066 static void memsys3Leave(void){
18067   sqlite3_mutex_leave(mem3.mutex);
18068 }
18069 
18070 /*
18071 ** Called when we are unable to satisfy an allocation of nBytes.
18072 */
memsys3OutOfMemory(int nByte)18073 static void memsys3OutOfMemory(int nByte){
18074   if( !mem3.alarmBusy ){
18075     mem3.alarmBusy = 1;
18076     assert( sqlite3_mutex_held(mem3.mutex) );
18077     sqlite3_mutex_leave(mem3.mutex);
18078     sqlite3_release_memory(nByte);
18079     sqlite3_mutex_enter(mem3.mutex);
18080     mem3.alarmBusy = 0;
18081   }
18082 }
18083 
18084 
18085 /*
18086 ** Chunk i is a free chunk that has been unlinked.  Adjust its
18087 ** size parameters for check-out and return a pointer to the
18088 ** user portion of the chunk.
18089 */
memsys3Checkout(u32 i,u32 nBlock)18090 static void *memsys3Checkout(u32 i, u32 nBlock){
18091   u32 x;
18092   assert( sqlite3_mutex_held(mem3.mutex) );
18093   assert( i>=1 );
18094   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
18095   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
18096   x = mem3.aPool[i-1].u.hdr.size4x;
18097   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
18098   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
18099   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
18100   return &mem3.aPool[i];
18101 }
18102 
18103 /*
18104 ** Carve a piece off of the end of the mem3.iMaster free chunk.
18105 ** Return a pointer to the new allocation.  Or, if the master chunk
18106 ** is not large enough, return 0.
18107 */
memsys3FromMaster(u32 nBlock)18108 static void *memsys3FromMaster(u32 nBlock){
18109   assert( sqlite3_mutex_held(mem3.mutex) );
18110   assert( mem3.szMaster>=nBlock );
18111   if( nBlock>=mem3.szMaster-1 ){
18112     /* Use the entire master */
18113     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
18114     mem3.iMaster = 0;
18115     mem3.szMaster = 0;
18116     mem3.mnMaster = 0;
18117     return p;
18118   }else{
18119     /* Split the master block.  Return the tail. */
18120     u32 newi, x;
18121     newi = mem3.iMaster + mem3.szMaster - nBlock;
18122     assert( newi > mem3.iMaster+1 );
18123     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
18124     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
18125     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
18126     mem3.szMaster -= nBlock;
18127     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
18128     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
18129     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
18130     if( mem3.szMaster < mem3.mnMaster ){
18131       mem3.mnMaster = mem3.szMaster;
18132     }
18133     return (void*)&mem3.aPool[newi];
18134   }
18135 }
18136 
18137 /*
18138 ** *pRoot is the head of a list of free chunks of the same size
18139 ** or same size hash.  In other words, *pRoot is an entry in either
18140 ** mem3.aiSmall[] or mem3.aiHash[].
18141 **
18142 ** This routine examines all entries on the given list and tries
18143 ** to coalesce each entries with adjacent free chunks.
18144 **
18145 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
18146 ** the current mem3.iMaster with the new larger chunk.  In order for
18147 ** this mem3.iMaster replacement to work, the master chunk must be
18148 ** linked into the hash tables.  That is not the normal state of
18149 ** affairs, of course.  The calling routine must link the master
18150 ** chunk before invoking this routine, then must unlink the (possibly
18151 ** changed) master chunk once this routine has finished.
18152 */
memsys3Merge(u32 * pRoot)18153 static void memsys3Merge(u32 *pRoot){
18154   u32 iNext, prev, size, i, x;
18155 
18156   assert( sqlite3_mutex_held(mem3.mutex) );
18157   for(i=*pRoot; i>0; i=iNext){
18158     iNext = mem3.aPool[i].u.list.next;
18159     size = mem3.aPool[i-1].u.hdr.size4x;
18160     assert( (size&1)==0 );
18161     if( (size&2)==0 ){
18162       memsys3UnlinkFromList(i, pRoot);
18163       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
18164       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
18165       if( prev==iNext ){
18166         iNext = mem3.aPool[prev].u.list.next;
18167       }
18168       memsys3Unlink(prev);
18169       size = i + size/4 - prev;
18170       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
18171       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
18172       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
18173       memsys3Link(prev);
18174       i = prev;
18175     }else{
18176       size /= 4;
18177     }
18178     if( size>mem3.szMaster ){
18179       mem3.iMaster = i;
18180       mem3.szMaster = size;
18181     }
18182   }
18183 }
18184 
18185 /*
18186 ** Return a block of memory of at least nBytes in size.
18187 ** Return NULL if unable.
18188 **
18189 ** This function assumes that the necessary mutexes, if any, are
18190 ** already held by the caller. Hence "Unsafe".
18191 */
memsys3MallocUnsafe(int nByte)18192 static void *memsys3MallocUnsafe(int nByte){
18193   u32 i;
18194   u32 nBlock;
18195   u32 toFree;
18196 
18197   assert( sqlite3_mutex_held(mem3.mutex) );
18198   assert( sizeof(Mem3Block)==8 );
18199   if( nByte<=12 ){
18200     nBlock = 2;
18201   }else{
18202     nBlock = (nByte + 11)/8;
18203   }
18204   assert( nBlock>=2 );
18205 
18206   /* STEP 1:
18207   ** Look for an entry of the correct size in either the small
18208   ** chunk table or in the large chunk hash table.  This is
18209   ** successful most of the time (about 9 times out of 10).
18210   */
18211   if( nBlock <= MX_SMALL ){
18212     i = mem3.aiSmall[nBlock-2];
18213     if( i>0 ){
18214       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
18215       return memsys3Checkout(i, nBlock);
18216     }
18217   }else{
18218     int hash = nBlock % N_HASH;
18219     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
18220       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
18221         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
18222         return memsys3Checkout(i, nBlock);
18223       }
18224     }
18225   }
18226 
18227   /* STEP 2:
18228   ** Try to satisfy the allocation by carving a piece off of the end
18229   ** of the master chunk.  This step usually works if step 1 fails.
18230   */
18231   if( mem3.szMaster>=nBlock ){
18232     return memsys3FromMaster(nBlock);
18233   }
18234 
18235 
18236   /* STEP 3:
18237   ** Loop through the entire memory pool.  Coalesce adjacent free
18238   ** chunks.  Recompute the master chunk as the largest free chunk.
18239   ** Then try again to satisfy the allocation by carving a piece off
18240   ** of the end of the master chunk.  This step happens very
18241   ** rarely (we hope!)
18242   */
18243   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
18244     memsys3OutOfMemory(toFree);
18245     if( mem3.iMaster ){
18246       memsys3Link(mem3.iMaster);
18247       mem3.iMaster = 0;
18248       mem3.szMaster = 0;
18249     }
18250     for(i=0; i<N_HASH; i++){
18251       memsys3Merge(&mem3.aiHash[i]);
18252     }
18253     for(i=0; i<MX_SMALL-1; i++){
18254       memsys3Merge(&mem3.aiSmall[i]);
18255     }
18256     if( mem3.szMaster ){
18257       memsys3Unlink(mem3.iMaster);
18258       if( mem3.szMaster>=nBlock ){
18259         return memsys3FromMaster(nBlock);
18260       }
18261     }
18262   }
18263 
18264   /* If none of the above worked, then we fail. */
18265   return 0;
18266 }
18267 
18268 /*
18269 ** Free an outstanding memory allocation.
18270 **
18271 ** This function assumes that the necessary mutexes, if any, are
18272 ** already held by the caller. Hence "Unsafe".
18273 */
memsys3FreeUnsafe(void * pOld)18274 static void memsys3FreeUnsafe(void *pOld){
18275   Mem3Block *p = (Mem3Block*)pOld;
18276   int i;
18277   u32 size, x;
18278   assert( sqlite3_mutex_held(mem3.mutex) );
18279   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
18280   i = p - mem3.aPool;
18281   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
18282   size = mem3.aPool[i-1].u.hdr.size4x/4;
18283   assert( i+size<=mem3.nPool+1 );
18284   mem3.aPool[i-1].u.hdr.size4x &= ~1;
18285   mem3.aPool[i+size-1].u.hdr.prevSize = size;
18286   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
18287   memsys3Link(i);
18288 
18289   /* Try to expand the master using the newly freed chunk */
18290   if( mem3.iMaster ){
18291     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
18292       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
18293       mem3.iMaster -= size;
18294       mem3.szMaster += size;
18295       memsys3Unlink(mem3.iMaster);
18296       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
18297       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
18298       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
18299     }
18300     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
18301     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
18302       memsys3Unlink(mem3.iMaster+mem3.szMaster);
18303       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
18304       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
18305       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
18306     }
18307   }
18308 }
18309 
18310 /*
18311 ** Return the size of an outstanding allocation, in bytes.  The
18312 ** size returned omits the 8-byte header overhead.  This only
18313 ** works for chunks that are currently checked out.
18314 */
memsys3Size(void * p)18315 static int memsys3Size(void *p){
18316   Mem3Block *pBlock;
18317   if( p==0 ) return 0;
18318   pBlock = (Mem3Block*)p;
18319   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
18320   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
18321 }
18322 
18323 /*
18324 ** Round up a request size to the next valid allocation size.
18325 */
memsys3Roundup(int n)18326 static int memsys3Roundup(int n){
18327   if( n<=12 ){
18328     return 12;
18329   }else{
18330     return ((n+11)&~7) - 4;
18331   }
18332 }
18333 
18334 /*
18335 ** Allocate nBytes of memory.
18336 */
memsys3Malloc(int nBytes)18337 static void *memsys3Malloc(int nBytes){
18338   sqlite3_int64 *p;
18339   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
18340   memsys3Enter();
18341   p = memsys3MallocUnsafe(nBytes);
18342   memsys3Leave();
18343   return (void*)p;
18344 }
18345 
18346 /*
18347 ** Free memory.
18348 */
memsys3Free(void * pPrior)18349 static void memsys3Free(void *pPrior){
18350   assert( pPrior );
18351   memsys3Enter();
18352   memsys3FreeUnsafe(pPrior);
18353   memsys3Leave();
18354 }
18355 
18356 /*
18357 ** Change the size of an existing memory allocation
18358 */
memsys3Realloc(void * pPrior,int nBytes)18359 static void *memsys3Realloc(void *pPrior, int nBytes){
18360   int nOld;
18361   void *p;
18362   if( pPrior==0 ){
18363     return sqlite3_malloc(nBytes);
18364   }
18365   if( nBytes<=0 ){
18366     sqlite3_free(pPrior);
18367     return 0;
18368   }
18369   nOld = memsys3Size(pPrior);
18370   if( nBytes<=nOld && nBytes>=nOld-128 ){
18371     return pPrior;
18372   }
18373   memsys3Enter();
18374   p = memsys3MallocUnsafe(nBytes);
18375   if( p ){
18376     if( nOld<nBytes ){
18377       memcpy(p, pPrior, nOld);
18378     }else{
18379       memcpy(p, pPrior, nBytes);
18380     }
18381     memsys3FreeUnsafe(pPrior);
18382   }
18383   memsys3Leave();
18384   return p;
18385 }
18386 
18387 /*
18388 ** Initialize this module.
18389 */
memsys3Init(void * NotUsed)18390 static int memsys3Init(void *NotUsed){
18391   UNUSED_PARAMETER(NotUsed);
18392   if( !sqlite3GlobalConfig.pHeap ){
18393     return SQLITE_ERROR;
18394   }
18395 
18396   /* Store a pointer to the memory block in global structure mem3. */
18397   assert( sizeof(Mem3Block)==8 );
18398   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
18399   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
18400 
18401   /* Initialize the master block. */
18402   mem3.szMaster = mem3.nPool;
18403   mem3.mnMaster = mem3.szMaster;
18404   mem3.iMaster = 1;
18405   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
18406   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
18407   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
18408 
18409   return SQLITE_OK;
18410 }
18411 
18412 /*
18413 ** Deinitialize this module.
18414 */
memsys3Shutdown(void * NotUsed)18415 static void memsys3Shutdown(void *NotUsed){
18416   UNUSED_PARAMETER(NotUsed);
18417   mem3.mutex = 0;
18418   return;
18419 }
18420 
18421 
18422 
18423 /*
18424 ** Open the file indicated and write a log of all unfreed memory
18425 ** allocations into that log.
18426 */
sqlite3Memsys3Dump(const char * zFilename)18427 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
18428 #ifdef SQLITE_DEBUG
18429   FILE *out;
18430   u32 i, j;
18431   u32 size;
18432   if( zFilename==0 || zFilename[0]==0 ){
18433     out = stdout;
18434   }else{
18435     out = fopen(zFilename, "w");
18436     if( out==0 ){
18437       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
18438                       zFilename);
18439       return;
18440     }
18441   }
18442   memsys3Enter();
18443   fprintf(out, "CHUNKS:\n");
18444   for(i=1; i<=mem3.nPool; i+=size/4){
18445     size = mem3.aPool[i-1].u.hdr.size4x;
18446     if( size/4<=1 ){
18447       fprintf(out, "%p size error\n", &mem3.aPool[i]);
18448       assert( 0 );
18449       break;
18450     }
18451     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
18452       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
18453       assert( 0 );
18454       break;
18455     }
18456     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
18457       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
18458       assert( 0 );
18459       break;
18460     }
18461     if( size&1 ){
18462       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
18463     }else{
18464       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
18465                   i==mem3.iMaster ? " **master**" : "");
18466     }
18467   }
18468   for(i=0; i<MX_SMALL-1; i++){
18469     if( mem3.aiSmall[i]==0 ) continue;
18470     fprintf(out, "small(%2d):", i);
18471     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
18472       fprintf(out, " %p(%d)", &mem3.aPool[j],
18473               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
18474     }
18475     fprintf(out, "\n");
18476   }
18477   for(i=0; i<N_HASH; i++){
18478     if( mem3.aiHash[i]==0 ) continue;
18479     fprintf(out, "hash(%2d):", i);
18480     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
18481       fprintf(out, " %p(%d)", &mem3.aPool[j],
18482               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
18483     }
18484     fprintf(out, "\n");
18485   }
18486   fprintf(out, "master=%d\n", mem3.iMaster);
18487   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
18488   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
18489   sqlite3_mutex_leave(mem3.mutex);
18490   if( out==stdout ){
18491     fflush(stdout);
18492   }else{
18493     fclose(out);
18494   }
18495 #else
18496   UNUSED_PARAMETER(zFilename);
18497 #endif
18498 }
18499 
18500 /*
18501 ** This routine is the only routine in this file with external
18502 ** linkage.
18503 **
18504 ** Populate the low-level memory allocation function pointers in
18505 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
18506 ** arguments specify the block of memory to manage.
18507 **
18508 ** This routine is only called by sqlite3_config(), and therefore
18509 ** is not required to be threadsafe (it is not).
18510 */
sqlite3MemGetMemsys3(void)18511 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
18512   static const sqlite3_mem_methods mempoolMethods = {
18513      memsys3Malloc,
18514      memsys3Free,
18515      memsys3Realloc,
18516      memsys3Size,
18517      memsys3Roundup,
18518      memsys3Init,
18519      memsys3Shutdown,
18520      0
18521   };
18522   return &mempoolMethods;
18523 }
18524 
18525 #endif /* SQLITE_ENABLE_MEMSYS3 */
18526 
18527 /************** End of mem3.c ************************************************/
18528 /************** Begin file mem5.c ********************************************/
18529 /*
18530 ** 2007 October 14
18531 **
18532 ** The author disclaims copyright to this source code.  In place of
18533 ** a legal notice, here is a blessing:
18534 **
18535 **    May you do good and not evil.
18536 **    May you find forgiveness for yourself and forgive others.
18537 **    May you share freely, never taking more than you give.
18538 **
18539 *************************************************************************
18540 ** This file contains the C functions that implement a memory
18541 ** allocation subsystem for use by SQLite.
18542 **
18543 ** This version of the memory allocation subsystem omits all
18544 ** use of malloc(). The application gives SQLite a block of memory
18545 ** before calling sqlite3_initialize() from which allocations
18546 ** are made and returned by the xMalloc() and xRealloc()
18547 ** implementations. Once sqlite3_initialize() has been called,
18548 ** the amount of memory available to SQLite is fixed and cannot
18549 ** be changed.
18550 **
18551 ** This version of the memory allocation subsystem is included
18552 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
18553 **
18554 ** This memory allocator uses the following algorithm:
18555 **
18556 **   1.  All memory allocations sizes are rounded up to a power of 2.
18557 **
18558 **   2.  If two adjacent free blocks are the halves of a larger block,
18559 **       then the two blocks are coalesced into the single larger block.
18560 **
18561 **   3.  New memory is allocated from the first available free block.
18562 **
18563 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
18564 ** Concerning Dynamic Storage Allocation". Journal of the Association for
18565 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
18566 **
18567 ** Let n be the size of the largest allocation divided by the minimum
18568 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
18569 ** be the maximum amount of memory ever outstanding at one time.  Let
18570 ** N be the total amount of memory available for allocation.  Robson
18571 ** proved that this memory allocator will never breakdown due to
18572 ** fragmentation as long as the following constraint holds:
18573 **
18574 **      N >=  M*(1 + log2(n)/2) - n + 1
18575 **
18576 ** The sqlite3_status() logic tracks the maximum values of n and M so
18577 ** that an application can, at any time, verify this constraint.
18578 */
18579 
18580 /*
18581 ** This version of the memory allocator is used only when
18582 ** SQLITE_ENABLE_MEMSYS5 is defined.
18583 */
18584 #ifdef SQLITE_ENABLE_MEMSYS5
18585 
18586 /*
18587 ** A minimum allocation is an instance of the following structure.
18588 ** Larger allocations are an array of these structures where the
18589 ** size of the array is a power of 2.
18590 **
18591 ** The size of this object must be a power of two.  That fact is
18592 ** verified in memsys5Init().
18593 */
18594 typedef struct Mem5Link Mem5Link;
18595 struct Mem5Link {
18596   int next;       /* Index of next free chunk */
18597   int prev;       /* Index of previous free chunk */
18598 };
18599 
18600 /*
18601 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
18602 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
18603 ** it is not actually possible to reach this limit.
18604 */
18605 #define LOGMAX 30
18606 
18607 /*
18608 ** Masks used for mem5.aCtrl[] elements.
18609 */
18610 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
18611 #define CTRL_FREE     0x20    /* True if not checked out */
18612 
18613 /*
18614 ** All of the static variables used by this module are collected
18615 ** into a single structure named "mem5".  This is to keep the
18616 ** static variables organized and to reduce namespace pollution
18617 ** when this module is combined with other in the amalgamation.
18618 */
18619 static SQLITE_WSD struct Mem5Global {
18620   /*
18621   ** Memory available for allocation
18622   */
18623   int szAtom;      /* Smallest possible allocation in bytes */
18624   int nBlock;      /* Number of szAtom sized blocks in zPool */
18625   u8 *zPool;       /* Memory available to be allocated */
18626 
18627   /*
18628   ** Mutex to control access to the memory allocation subsystem.
18629   */
18630   sqlite3_mutex *mutex;
18631 
18632   /*
18633   ** Performance statistics
18634   */
18635   u64 nAlloc;         /* Total number of calls to malloc */
18636   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
18637   u64 totalExcess;    /* Total internal fragmentation */
18638   u32 currentOut;     /* Current checkout, including internal fragmentation */
18639   u32 currentCount;   /* Current number of distinct checkouts */
18640   u32 maxOut;         /* Maximum instantaneous currentOut */
18641   u32 maxCount;       /* Maximum instantaneous currentCount */
18642   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
18643 
18644   /*
18645   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
18646   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
18647   ** and so forth.
18648   */
18649   int aiFreelist[LOGMAX+1];
18650 
18651   /*
18652   ** Space for tracking which blocks are checked out and the size
18653   ** of each block.  One byte per block.
18654   */
18655   u8 *aCtrl;
18656 
18657 } mem5;
18658 
18659 /*
18660 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
18661 */
18662 #define mem5 GLOBAL(struct Mem5Global, mem5)
18663 
18664 /*
18665 ** Assuming mem5.zPool is divided up into an array of Mem5Link
18666 ** structures, return a pointer to the idx-th such link.
18667 */
18668 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
18669 
18670 /*
18671 ** Unlink the chunk at mem5.aPool[i] from list it is currently
18672 ** on.  It should be found on mem5.aiFreelist[iLogsize].
18673 */
memsys5Unlink(int i,int iLogsize)18674 static void memsys5Unlink(int i, int iLogsize){
18675   int next, prev;
18676   assert( i>=0 && i<mem5.nBlock );
18677   assert( iLogsize>=0 && iLogsize<=LOGMAX );
18678   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
18679 
18680   next = MEM5LINK(i)->next;
18681   prev = MEM5LINK(i)->prev;
18682   if( prev<0 ){
18683     mem5.aiFreelist[iLogsize] = next;
18684   }else{
18685     MEM5LINK(prev)->next = next;
18686   }
18687   if( next>=0 ){
18688     MEM5LINK(next)->prev = prev;
18689   }
18690 }
18691 
18692 /*
18693 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
18694 ** free list.
18695 */
memsys5Link(int i,int iLogsize)18696 static void memsys5Link(int i, int iLogsize){
18697   int x;
18698   assert( sqlite3_mutex_held(mem5.mutex) );
18699   assert( i>=0 && i<mem5.nBlock );
18700   assert( iLogsize>=0 && iLogsize<=LOGMAX );
18701   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
18702 
18703   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
18704   MEM5LINK(i)->prev = -1;
18705   if( x>=0 ){
18706     assert( x<mem5.nBlock );
18707     MEM5LINK(x)->prev = i;
18708   }
18709   mem5.aiFreelist[iLogsize] = i;
18710 }
18711 
18712 /*
18713 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
18714 ** will already be held (obtained by code in malloc.c) if
18715 ** sqlite3GlobalConfig.bMemStat is true.
18716 */
memsys5Enter(void)18717 static void memsys5Enter(void){
18718   sqlite3_mutex_enter(mem5.mutex);
18719 }
memsys5Leave(void)18720 static void memsys5Leave(void){
18721   sqlite3_mutex_leave(mem5.mutex);
18722 }
18723 
18724 /*
18725 ** Return the size of an outstanding allocation, in bytes.  The
18726 ** size returned omits the 8-byte header overhead.  This only
18727 ** works for chunks that are currently checked out.
18728 */
memsys5Size(void * p)18729 static int memsys5Size(void *p){
18730   int iSize = 0;
18731   if( p ){
18732     int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
18733     assert( i>=0 && i<mem5.nBlock );
18734     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
18735   }
18736   return iSize;
18737 }
18738 
18739 /*
18740 ** Return a block of memory of at least nBytes in size.
18741 ** Return NULL if unable.  Return NULL if nBytes==0.
18742 **
18743 ** The caller guarantees that nByte is positive.
18744 **
18745 ** The caller has obtained a mutex prior to invoking this
18746 ** routine so there is never any chance that two or more
18747 ** threads can be in this routine at the same time.
18748 */
memsys5MallocUnsafe(int nByte)18749 static void *memsys5MallocUnsafe(int nByte){
18750   int i;           /* Index of a mem5.aPool[] slot */
18751   int iBin;        /* Index into mem5.aiFreelist[] */
18752   int iFullSz;     /* Size of allocation rounded up to power of 2 */
18753   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
18754 
18755   /* nByte must be a positive */
18756   assert( nByte>0 );
18757 
18758   /* Keep track of the maximum allocation request.  Even unfulfilled
18759   ** requests are counted */
18760   if( (u32)nByte>mem5.maxRequest ){
18761     mem5.maxRequest = nByte;
18762   }
18763 
18764   /* Abort if the requested allocation size is larger than the largest
18765   ** power of two that we can represent using 32-bit signed integers.
18766   */
18767   if( nByte > 0x40000000 ){
18768     return 0;
18769   }
18770 
18771   /* Round nByte up to the next valid power of two */
18772   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
18773 
18774   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
18775   ** block.  If not, then split a block of the next larger power of
18776   ** two in order to create a new free block of size iLogsize.
18777   */
18778   for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
18779   if( iBin>LOGMAX ){
18780     testcase( sqlite3GlobalConfig.xLog!=0 );
18781     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
18782     return 0;
18783   }
18784   i = mem5.aiFreelist[iBin];
18785   memsys5Unlink(i, iBin);
18786   while( iBin>iLogsize ){
18787     int newSize;
18788 
18789     iBin--;
18790     newSize = 1 << iBin;
18791     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
18792     memsys5Link(i+newSize, iBin);
18793   }
18794   mem5.aCtrl[i] = iLogsize;
18795 
18796   /* Update allocator performance statistics. */
18797   mem5.nAlloc++;
18798   mem5.totalAlloc += iFullSz;
18799   mem5.totalExcess += iFullSz - nByte;
18800   mem5.currentCount++;
18801   mem5.currentOut += iFullSz;
18802   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
18803   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
18804 
18805 #ifdef SQLITE_DEBUG
18806   /* Make sure the allocated memory does not assume that it is set to zero
18807   ** or retains a value from a previous allocation */
18808   memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
18809 #endif
18810 
18811   /* Return a pointer to the allocated memory. */
18812   return (void*)&mem5.zPool[i*mem5.szAtom];
18813 }
18814 
18815 /*
18816 ** Free an outstanding memory allocation.
18817 */
memsys5FreeUnsafe(void * pOld)18818 static void memsys5FreeUnsafe(void *pOld){
18819   u32 size, iLogsize;
18820   int iBlock;
18821 
18822   /* Set iBlock to the index of the block pointed to by pOld in
18823   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
18824   */
18825   iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
18826 
18827   /* Check that the pointer pOld points to a valid, non-free block. */
18828   assert( iBlock>=0 && iBlock<mem5.nBlock );
18829   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
18830   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
18831 
18832   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
18833   size = 1<<iLogsize;
18834   assert( iBlock+size-1<(u32)mem5.nBlock );
18835 
18836   mem5.aCtrl[iBlock] |= CTRL_FREE;
18837   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
18838   assert( mem5.currentCount>0 );
18839   assert( mem5.currentOut>=(size*mem5.szAtom) );
18840   mem5.currentCount--;
18841   mem5.currentOut -= size*mem5.szAtom;
18842   assert( mem5.currentOut>0 || mem5.currentCount==0 );
18843   assert( mem5.currentCount>0 || mem5.currentOut==0 );
18844 
18845   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18846   while( ALWAYS(iLogsize<LOGMAX) ){
18847     int iBuddy;
18848     if( (iBlock>>iLogsize) & 1 ){
18849       iBuddy = iBlock - size;
18850     }else{
18851       iBuddy = iBlock + size;
18852     }
18853     assert( iBuddy>=0 );
18854     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
18855     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
18856     memsys5Unlink(iBuddy, iLogsize);
18857     iLogsize++;
18858     if( iBuddy<iBlock ){
18859       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
18860       mem5.aCtrl[iBlock] = 0;
18861       iBlock = iBuddy;
18862     }else{
18863       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18864       mem5.aCtrl[iBuddy] = 0;
18865     }
18866     size *= 2;
18867   }
18868 
18869 #ifdef SQLITE_DEBUG
18870   /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
18871   ** not used after being freed */
18872   memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
18873 #endif
18874 
18875   memsys5Link(iBlock, iLogsize);
18876 }
18877 
18878 /*
18879 ** Allocate nBytes of memory.
18880 */
memsys5Malloc(int nBytes)18881 static void *memsys5Malloc(int nBytes){
18882   sqlite3_int64 *p = 0;
18883   if( nBytes>0 ){
18884     memsys5Enter();
18885     p = memsys5MallocUnsafe(nBytes);
18886     memsys5Leave();
18887   }
18888   return (void*)p;
18889 }
18890 
18891 /*
18892 ** Free memory.
18893 **
18894 ** The outer layer memory allocator prevents this routine from
18895 ** being called with pPrior==0.
18896 */
memsys5Free(void * pPrior)18897 static void memsys5Free(void *pPrior){
18898   assert( pPrior!=0 );
18899   memsys5Enter();
18900   memsys5FreeUnsafe(pPrior);
18901   memsys5Leave();
18902 }
18903 
18904 /*
18905 ** Change the size of an existing memory allocation.
18906 **
18907 ** The outer layer memory allocator prevents this routine from
18908 ** being called with pPrior==0.
18909 **
18910 ** nBytes is always a value obtained from a prior call to
18911 ** memsys5Round().  Hence nBytes is always a non-negative power
18912 ** of two.  If nBytes==0 that means that an oversize allocation
18913 ** (an allocation larger than 0x40000000) was requested and this
18914 ** routine should return 0 without freeing pPrior.
18915 */
memsys5Realloc(void * pPrior,int nBytes)18916 static void *memsys5Realloc(void *pPrior, int nBytes){
18917   int nOld;
18918   void *p;
18919   assert( pPrior!=0 );
18920   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
18921   assert( nBytes>=0 );
18922   if( nBytes==0 ){
18923     return 0;
18924   }
18925   nOld = memsys5Size(pPrior);
18926   if( nBytes<=nOld ){
18927     return pPrior;
18928   }
18929   memsys5Enter();
18930   p = memsys5MallocUnsafe(nBytes);
18931   if( p ){
18932     memcpy(p, pPrior, nOld);
18933     memsys5FreeUnsafe(pPrior);
18934   }
18935   memsys5Leave();
18936   return p;
18937 }
18938 
18939 /*
18940 ** Round up a request size to the next valid allocation size.  If
18941 ** the allocation is too large to be handled by this allocation system,
18942 ** return 0.
18943 **
18944 ** All allocations must be a power of two and must be expressed by a
18945 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
18946 ** or 1073741824 bytes.
18947 */
memsys5Roundup(int n)18948 static int memsys5Roundup(int n){
18949   int iFullSz;
18950   if( n > 0x40000000 ) return 0;
18951   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
18952   return iFullSz;
18953 }
18954 
18955 /*
18956 ** Return the ceiling of the logarithm base 2 of iValue.
18957 **
18958 ** Examples:   memsys5Log(1) -> 0
18959 **             memsys5Log(2) -> 1
18960 **             memsys5Log(4) -> 2
18961 **             memsys5Log(5) -> 3
18962 **             memsys5Log(8) -> 3
18963 **             memsys5Log(9) -> 4
18964 */
memsys5Log(int iValue)18965 static int memsys5Log(int iValue){
18966   int iLog;
18967   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
18968   return iLog;
18969 }
18970 
18971 /*
18972 ** Initialize the memory allocator.
18973 **
18974 ** This routine is not threadsafe.  The caller must be holding a mutex
18975 ** to prevent multiple threads from entering at the same time.
18976 */
memsys5Init(void * NotUsed)18977 static int memsys5Init(void *NotUsed){
18978   int ii;            /* Loop counter */
18979   int nByte;         /* Number of bytes of memory available to this allocator */
18980   u8 *zByte;         /* Memory usable by this allocator */
18981   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
18982   int iOffset;       /* An offset into mem5.aCtrl[] */
18983 
18984   UNUSED_PARAMETER(NotUsed);
18985 
18986   /* For the purposes of this routine, disable the mutex */
18987   mem5.mutex = 0;
18988 
18989   /* The size of a Mem5Link object must be a power of two.  Verify that
18990   ** this is case.
18991   */
18992   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
18993 
18994   nByte = sqlite3GlobalConfig.nHeap;
18995   zByte = (u8*)sqlite3GlobalConfig.pHeap;
18996   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
18997 
18998   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
18999   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
19000   mem5.szAtom = (1<<nMinLog);
19001   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
19002     mem5.szAtom = mem5.szAtom << 1;
19003   }
19004 
19005   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
19006   mem5.zPool = zByte;
19007   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
19008 
19009   for(ii=0; ii<=LOGMAX; ii++){
19010     mem5.aiFreelist[ii] = -1;
19011   }
19012 
19013   iOffset = 0;
19014   for(ii=LOGMAX; ii>=0; ii--){
19015     int nAlloc = (1<<ii);
19016     if( (iOffset+nAlloc)<=mem5.nBlock ){
19017       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
19018       memsys5Link(iOffset, ii);
19019       iOffset += nAlloc;
19020     }
19021     assert((iOffset+nAlloc)>mem5.nBlock);
19022   }
19023 
19024   /* If a mutex is required for normal operation, allocate one */
19025   if( sqlite3GlobalConfig.bMemstat==0 ){
19026     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
19027   }
19028 
19029   return SQLITE_OK;
19030 }
19031 
19032 /*
19033 ** Deinitialize this module.
19034 */
memsys5Shutdown(void * NotUsed)19035 static void memsys5Shutdown(void *NotUsed){
19036   UNUSED_PARAMETER(NotUsed);
19037   mem5.mutex = 0;
19038   return;
19039 }
19040 
19041 #ifdef SQLITE_TEST
19042 /*
19043 ** Open the file indicated and write a log of all unfreed memory
19044 ** allocations into that log.
19045 */
sqlite3Memsys5Dump(const char * zFilename)19046 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
19047   FILE *out;
19048   int i, j, n;
19049   int nMinLog;
19050 
19051   if( zFilename==0 || zFilename[0]==0 ){
19052     out = stdout;
19053   }else{
19054     out = fopen(zFilename, "w");
19055     if( out==0 ){
19056       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
19057                       zFilename);
19058       return;
19059     }
19060   }
19061   memsys5Enter();
19062   nMinLog = memsys5Log(mem5.szAtom);
19063   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
19064     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
19065     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
19066   }
19067   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
19068   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
19069   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
19070   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
19071   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
19072   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
19073   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
19074   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
19075   memsys5Leave();
19076   if( out==stdout ){
19077     fflush(stdout);
19078   }else{
19079     fclose(out);
19080   }
19081 }
19082 #endif
19083 
19084 /*
19085 ** This routine is the only routine in this file with external
19086 ** linkage. It returns a pointer to a static sqlite3_mem_methods
19087 ** struct populated with the memsys5 methods.
19088 */
sqlite3MemGetMemsys5(void)19089 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
19090   static const sqlite3_mem_methods memsys5Methods = {
19091      memsys5Malloc,
19092      memsys5Free,
19093      memsys5Realloc,
19094      memsys5Size,
19095      memsys5Roundup,
19096      memsys5Init,
19097      memsys5Shutdown,
19098      0
19099   };
19100   return &memsys5Methods;
19101 }
19102 
19103 #endif /* SQLITE_ENABLE_MEMSYS5 */
19104 
19105 /************** End of mem5.c ************************************************/
19106 /************** Begin file mutex.c *******************************************/
19107 /*
19108 ** 2007 August 14
19109 **
19110 ** The author disclaims copyright to this source code.  In place of
19111 ** a legal notice, here is a blessing:
19112 **
19113 **    May you do good and not evil.
19114 **    May you find forgiveness for yourself and forgive others.
19115 **    May you share freely, never taking more than you give.
19116 **
19117 *************************************************************************
19118 ** This file contains the C functions that implement mutexes.
19119 **
19120 ** This file contains code that is common across all mutex implementations.
19121 */
19122 
19123 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
19124 /*
19125 ** For debugging purposes, record when the mutex subsystem is initialized
19126 ** and uninitialized so that we can assert() if there is an attempt to
19127 ** allocate a mutex while the system is uninitialized.
19128 */
19129 static SQLITE_WSD int mutexIsInit = 0;
19130 #endif /* SQLITE_DEBUG */
19131 
19132 
19133 #ifndef SQLITE_MUTEX_OMIT
19134 /*
19135 ** Initialize the mutex system.
19136 */
sqlite3MutexInit(void)19137 SQLITE_PRIVATE int sqlite3MutexInit(void){
19138   int rc = SQLITE_OK;
19139   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
19140     /* If the xMutexAlloc method has not been set, then the user did not
19141     ** install a mutex implementation via sqlite3_config() prior to
19142     ** sqlite3_initialize() being called. This block copies pointers to
19143     ** the default implementation into the sqlite3GlobalConfig structure.
19144     */
19145     sqlite3_mutex_methods const *pFrom;
19146     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
19147 
19148     if( sqlite3GlobalConfig.bCoreMutex ){
19149       pFrom = sqlite3DefaultMutex();
19150     }else{
19151       pFrom = sqlite3NoopMutex();
19152     }
19153     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
19154     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
19155            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
19156     pTo->xMutexAlloc = pFrom->xMutexAlloc;
19157   }
19158   rc = sqlite3GlobalConfig.mutex.xMutexInit();
19159 
19160 #ifdef SQLITE_DEBUG
19161   GLOBAL(int, mutexIsInit) = 1;
19162 #endif
19163 
19164   return rc;
19165 }
19166 
19167 /*
19168 ** Shutdown the mutex system. This call frees resources allocated by
19169 ** sqlite3MutexInit().
19170 */
sqlite3MutexEnd(void)19171 SQLITE_PRIVATE int sqlite3MutexEnd(void){
19172   int rc = SQLITE_OK;
19173   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
19174     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
19175   }
19176 
19177 #ifdef SQLITE_DEBUG
19178   GLOBAL(int, mutexIsInit) = 0;
19179 #endif
19180 
19181   return rc;
19182 }
19183 
19184 /*
19185 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
19186 */
sqlite3_mutex_alloc(int id)19187 SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int id){
19188 #ifndef SQLITE_OMIT_AUTOINIT
19189   if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
19190   if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
19191 #endif
19192   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
19193 }
19194 
sqlite3MutexAlloc(int id)19195 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
19196   if( !sqlite3GlobalConfig.bCoreMutex ){
19197     return 0;
19198   }
19199   assert( GLOBAL(int, mutexIsInit) );
19200   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
19201 }
19202 
19203 /*
19204 ** Free a dynamic mutex.
19205 */
sqlite3_mutex_free(sqlite3_mutex * p)19206 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex *p){
19207   if( p ){
19208     sqlite3GlobalConfig.mutex.xMutexFree(p);
19209   }
19210 }
19211 
19212 /*
19213 ** Obtain the mutex p. If some other thread already has the mutex, block
19214 ** until it can be obtained.
19215 */
sqlite3_mutex_enter(sqlite3_mutex * p)19216 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex *p){
19217   if( p ){
19218     sqlite3GlobalConfig.mutex.xMutexEnter(p);
19219   }
19220 }
19221 
19222 /*
19223 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
19224 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
19225 */
sqlite3_mutex_try(sqlite3_mutex * p)19226 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex *p){
19227   int rc = SQLITE_OK;
19228   if( p ){
19229     return sqlite3GlobalConfig.mutex.xMutexTry(p);
19230   }
19231   return rc;
19232 }
19233 
19234 /*
19235 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
19236 ** entered by the same thread.  The behavior is undefined if the mutex
19237 ** is not currently entered. If a NULL pointer is passed as an argument
19238 ** this function is a no-op.
19239 */
sqlite3_mutex_leave(sqlite3_mutex * p)19240 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex *p){
19241   if( p ){
19242     sqlite3GlobalConfig.mutex.xMutexLeave(p);
19243   }
19244 }
19245 
19246 #ifndef NDEBUG
19247 /*
19248 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
19249 ** intended for use inside assert() statements.
19250 */
sqlite3_mutex_held(sqlite3_mutex * p)19251 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex *p){
19252   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
19253 }
sqlite3_mutex_notheld(sqlite3_mutex * p)19254 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex *p){
19255   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
19256 }
19257 #endif
19258 
19259 #endif /* !defined(SQLITE_MUTEX_OMIT) */
19260 
19261 /************** End of mutex.c ***********************************************/
19262 /************** Begin file mutex_noop.c **************************************/
19263 /*
19264 ** 2008 October 07
19265 **
19266 ** The author disclaims copyright to this source code.  In place of
19267 ** a legal notice, here is a blessing:
19268 **
19269 **    May you do good and not evil.
19270 **    May you find forgiveness for yourself and forgive others.
19271 **    May you share freely, never taking more than you give.
19272 **
19273 *************************************************************************
19274 ** This file contains the C functions that implement mutexes.
19275 **
19276 ** This implementation in this file does not provide any mutual
19277 ** exclusion and is thus suitable for use only in applications
19278 ** that use SQLite in a single thread.  The routines defined
19279 ** here are place-holders.  Applications can substitute working
19280 ** mutex routines at start-time using the
19281 **
19282 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
19283 **
19284 ** interface.
19285 **
19286 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
19287 ** that does error checking on mutexes to make sure they are being
19288 ** called correctly.
19289 */
19290 
19291 #ifndef SQLITE_MUTEX_OMIT
19292 
19293 #ifndef SQLITE_DEBUG
19294 /*
19295 ** Stub routines for all mutex methods.
19296 **
19297 ** This routines provide no mutual exclusion or error checking.
19298 */
noopMutexInit(void)19299 static int noopMutexInit(void){ return SQLITE_OK; }
noopMutexEnd(void)19300 static int noopMutexEnd(void){ return SQLITE_OK; }
noopMutexAlloc(int id)19301 static sqlite3_mutex *noopMutexAlloc(int id){
19302   UNUSED_PARAMETER(id);
19303   return (sqlite3_mutex*)8;
19304 }
noopMutexFree(sqlite3_mutex * p)19305 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
noopMutexEnter(sqlite3_mutex * p)19306 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
noopMutexTry(sqlite3_mutex * p)19307 static int noopMutexTry(sqlite3_mutex *p){
19308   UNUSED_PARAMETER(p);
19309   return SQLITE_OK;
19310 }
noopMutexLeave(sqlite3_mutex * p)19311 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
19312 
sqlite3NoopMutex(void)19313 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
19314   static const sqlite3_mutex_methods sMutex = {
19315     noopMutexInit,
19316     noopMutexEnd,
19317     noopMutexAlloc,
19318     noopMutexFree,
19319     noopMutexEnter,
19320     noopMutexTry,
19321     noopMutexLeave,
19322 
19323     0,
19324     0,
19325   };
19326 
19327   return &sMutex;
19328 }
19329 #endif /* !SQLITE_DEBUG */
19330 
19331 #ifdef SQLITE_DEBUG
19332 /*
19333 ** In this implementation, error checking is provided for testing
19334 ** and debugging purposes.  The mutexes still do not provide any
19335 ** mutual exclusion.
19336 */
19337 
19338 /*
19339 ** The mutex object
19340 */
19341 typedef struct sqlite3_debug_mutex {
19342   int id;     /* The mutex type */
19343   int cnt;    /* Number of entries without a matching leave */
19344 } sqlite3_debug_mutex;
19345 
19346 /*
19347 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
19348 ** intended for use inside assert() statements.
19349 */
debugMutexHeld(sqlite3_mutex * pX)19350 static int debugMutexHeld(sqlite3_mutex *pX){
19351   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
19352   return p==0 || p->cnt>0;
19353 }
debugMutexNotheld(sqlite3_mutex * pX)19354 static int debugMutexNotheld(sqlite3_mutex *pX){
19355   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
19356   return p==0 || p->cnt==0;
19357 }
19358 
19359 /*
19360 ** Initialize and deinitialize the mutex subsystem.
19361 */
debugMutexInit(void)19362 static int debugMutexInit(void){ return SQLITE_OK; }
debugMutexEnd(void)19363 static int debugMutexEnd(void){ return SQLITE_OK; }
19364 
19365 /*
19366 ** The sqlite3_mutex_alloc() routine allocates a new
19367 ** mutex and returns a pointer to it.  If it returns NULL
19368 ** that means that a mutex could not be allocated.
19369 */
debugMutexAlloc(int id)19370 static sqlite3_mutex *debugMutexAlloc(int id){
19371   static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_APP3 - 1];
19372   sqlite3_debug_mutex *pNew = 0;
19373   switch( id ){
19374     case SQLITE_MUTEX_FAST:
19375     case SQLITE_MUTEX_RECURSIVE: {
19376       pNew = sqlite3Malloc(sizeof(*pNew));
19377       if( pNew ){
19378         pNew->id = id;
19379         pNew->cnt = 0;
19380       }
19381       break;
19382     }
19383     default: {
19384 #ifdef SQLITE_ENABLE_API_ARMOR
19385       if( id-2<0 || id-2>=ArraySize(aStatic) ){
19386         (void)SQLITE_MISUSE_BKPT;
19387         return 0;
19388       }
19389 #endif
19390       pNew = &aStatic[id-2];
19391       pNew->id = id;
19392       break;
19393     }
19394   }
19395   return (sqlite3_mutex*)pNew;
19396 }
19397 
19398 /*
19399 ** This routine deallocates a previously allocated mutex.
19400 */
debugMutexFree(sqlite3_mutex * pX)19401 static void debugMutexFree(sqlite3_mutex *pX){
19402   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
19403   assert( p->cnt==0 );
19404   if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
19405     sqlite3_free(p);
19406   }else{
19407 #ifdef SQLITE_ENABLE_API_ARMOR
19408     (void)SQLITE_MISUSE_BKPT;
19409 #endif
19410   }
19411 }
19412 
19413 /*
19414 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
19415 ** to enter a mutex.  If another thread is already within the mutex,
19416 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
19417 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
19418 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
19419 ** be entered multiple times by the same thread.  In such cases the,
19420 ** mutex must be exited an equal number of times before another thread
19421 ** can enter.  If the same thread tries to enter any other kind of mutex
19422 ** more than once, the behavior is undefined.
19423 */
debugMutexEnter(sqlite3_mutex * pX)19424 static void debugMutexEnter(sqlite3_mutex *pX){
19425   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
19426   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
19427   p->cnt++;
19428 }
debugMutexTry(sqlite3_mutex * pX)19429 static int debugMutexTry(sqlite3_mutex *pX){
19430   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
19431   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
19432   p->cnt++;
19433   return SQLITE_OK;
19434 }
19435 
19436 /*
19437 ** The sqlite3_mutex_leave() routine exits a mutex that was
19438 ** previously entered by the same thread.  The behavior
19439 ** is undefined if the mutex is not currently entered or
19440 ** is not currently allocated.  SQLite will never do either.
19441 */
debugMutexLeave(sqlite3_mutex * pX)19442 static void debugMutexLeave(sqlite3_mutex *pX){
19443   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
19444   assert( debugMutexHeld(pX) );
19445   p->cnt--;
19446   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
19447 }
19448 
sqlite3NoopMutex(void)19449 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
19450   static const sqlite3_mutex_methods sMutex = {
19451     debugMutexInit,
19452     debugMutexEnd,
19453     debugMutexAlloc,
19454     debugMutexFree,
19455     debugMutexEnter,
19456     debugMutexTry,
19457     debugMutexLeave,
19458 
19459     debugMutexHeld,
19460     debugMutexNotheld
19461   };
19462 
19463   return &sMutex;
19464 }
19465 #endif /* SQLITE_DEBUG */
19466 
19467 /*
19468 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
19469 ** is used regardless of the run-time threadsafety setting.
19470 */
19471 #ifdef SQLITE_MUTEX_NOOP
sqlite3DefaultMutex(void)19472 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
19473   return sqlite3NoopMutex();
19474 }
19475 #endif /* defined(SQLITE_MUTEX_NOOP) */
19476 #endif /* !defined(SQLITE_MUTEX_OMIT) */
19477 
19478 /************** End of mutex_noop.c ******************************************/
19479 /************** Begin file mutex_unix.c **************************************/
19480 /*
19481 ** 2007 August 28
19482 **
19483 ** The author disclaims copyright to this source code.  In place of
19484 ** a legal notice, here is a blessing:
19485 **
19486 **    May you do good and not evil.
19487 **    May you find forgiveness for yourself and forgive others.
19488 **    May you share freely, never taking more than you give.
19489 **
19490 *************************************************************************
19491 ** This file contains the C functions that implement mutexes for pthreads
19492 */
19493 
19494 /*
19495 ** The code in this file is only used if we are compiling threadsafe
19496 ** under unix with pthreads.
19497 **
19498 ** Note that this implementation requires a version of pthreads that
19499 ** supports recursive mutexes.
19500 */
19501 #ifdef SQLITE_MUTEX_PTHREADS
19502 
19503 #include <pthread.h>
19504 
19505 /*
19506 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
19507 ** are necessary under two condidtions:  (1) Debug builds and (2) using
19508 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
19509 */
19510 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
19511 # define SQLITE_MUTEX_NREF 1
19512 #else
19513 # define SQLITE_MUTEX_NREF 0
19514 #endif
19515 
19516 /*
19517 ** Each recursive mutex is an instance of the following structure.
19518 */
19519 struct sqlite3_mutex {
19520   pthread_mutex_t mutex;     /* Mutex controlling the lock */
19521 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
19522   int id;                    /* Mutex type */
19523 #endif
19524 #if SQLITE_MUTEX_NREF
19525   volatile int nRef;         /* Number of entrances */
19526   volatile pthread_t owner;  /* Thread that is within this mutex */
19527   int trace;                 /* True to trace changes */
19528 #endif
19529 };
19530 #if SQLITE_MUTEX_NREF
19531 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
19532 #else
19533 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
19534 #endif
19535 
19536 /*
19537 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
19538 ** intended for use only inside assert() statements.  On some platforms,
19539 ** there might be race conditions that can cause these routines to
19540 ** deliver incorrect results.  In particular, if pthread_equal() is
19541 ** not an atomic operation, then these routines might delivery
19542 ** incorrect results.  On most platforms, pthread_equal() is a
19543 ** comparison of two integers and is therefore atomic.  But we are
19544 ** told that HPUX is not such a platform.  If so, then these routines
19545 ** will not always work correctly on HPUX.
19546 **
19547 ** On those platforms where pthread_equal() is not atomic, SQLite
19548 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
19549 ** make sure no assert() statements are evaluated and hence these
19550 ** routines are never called.
19551 */
19552 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
pthreadMutexHeld(sqlite3_mutex * p)19553 static int pthreadMutexHeld(sqlite3_mutex *p){
19554   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
19555 }
pthreadMutexNotheld(sqlite3_mutex * p)19556 static int pthreadMutexNotheld(sqlite3_mutex *p){
19557   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
19558 }
19559 #endif
19560 
19561 /*
19562 ** Initialize and deinitialize the mutex subsystem.
19563 */
pthreadMutexInit(void)19564 static int pthreadMutexInit(void){ return SQLITE_OK; }
pthreadMutexEnd(void)19565 static int pthreadMutexEnd(void){ return SQLITE_OK; }
19566 
19567 /*
19568 ** The sqlite3_mutex_alloc() routine allocates a new
19569 ** mutex and returns a pointer to it.  If it returns NULL
19570 ** that means that a mutex could not be allocated.  SQLite
19571 ** will unwind its stack and return an error.  The argument
19572 ** to sqlite3_mutex_alloc() is one of these integer constants:
19573 **
19574 ** <ul>
19575 ** <li>  SQLITE_MUTEX_FAST
19576 ** <li>  SQLITE_MUTEX_RECURSIVE
19577 ** <li>  SQLITE_MUTEX_STATIC_MASTER
19578 ** <li>  SQLITE_MUTEX_STATIC_MEM
19579 ** <li>  SQLITE_MUTEX_STATIC_OPEN
19580 ** <li>  SQLITE_MUTEX_STATIC_PRNG
19581 ** <li>  SQLITE_MUTEX_STATIC_LRU
19582 ** <li>  SQLITE_MUTEX_STATIC_PMEM
19583 ** <li>  SQLITE_MUTEX_STATIC_APP1
19584 ** <li>  SQLITE_MUTEX_STATIC_APP2
19585 ** <li>  SQLITE_MUTEX_STATIC_APP3
19586 ** </ul>
19587 **
19588 ** The first two constants cause sqlite3_mutex_alloc() to create
19589 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
19590 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
19591 ** The mutex implementation does not need to make a distinction
19592 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
19593 ** not want to.  But SQLite will only request a recursive mutex in
19594 ** cases where it really needs one.  If a faster non-recursive mutex
19595 ** implementation is available on the host platform, the mutex subsystem
19596 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
19597 **
19598 ** The other allowed parameters to sqlite3_mutex_alloc() each return
19599 ** a pointer to a static preexisting mutex.  Six static mutexes are
19600 ** used by the current version of SQLite.  Future versions of SQLite
19601 ** may add additional static mutexes.  Static mutexes are for internal
19602 ** use by SQLite only.  Applications that use SQLite mutexes should
19603 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
19604 ** SQLITE_MUTEX_RECURSIVE.
19605 **
19606 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
19607 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
19608 ** returns a different mutex on every call.  But for the static
19609 ** mutex types, the same mutex is returned on every call that has
19610 ** the same type number.
19611 */
pthreadMutexAlloc(int iType)19612 static sqlite3_mutex *pthreadMutexAlloc(int iType){
19613   static sqlite3_mutex staticMutexes[] = {
19614     SQLITE3_MUTEX_INITIALIZER,
19615     SQLITE3_MUTEX_INITIALIZER,
19616     SQLITE3_MUTEX_INITIALIZER,
19617     SQLITE3_MUTEX_INITIALIZER,
19618     SQLITE3_MUTEX_INITIALIZER,
19619     SQLITE3_MUTEX_INITIALIZER,
19620     SQLITE3_MUTEX_INITIALIZER,
19621     SQLITE3_MUTEX_INITIALIZER,
19622     SQLITE3_MUTEX_INITIALIZER
19623   };
19624   sqlite3_mutex *p;
19625   switch( iType ){
19626     case SQLITE_MUTEX_RECURSIVE: {
19627       p = sqlite3MallocZero( sizeof(*p) );
19628       if( p ){
19629 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19630         /* If recursive mutexes are not available, we will have to
19631         ** build our own.  See below. */
19632         pthread_mutex_init(&p->mutex, 0);
19633 #else
19634         /* Use a recursive mutex if it is available */
19635         pthread_mutexattr_t recursiveAttr;
19636         pthread_mutexattr_init(&recursiveAttr);
19637         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
19638         pthread_mutex_init(&p->mutex, &recursiveAttr);
19639         pthread_mutexattr_destroy(&recursiveAttr);
19640 #endif
19641       }
19642       break;
19643     }
19644     case SQLITE_MUTEX_FAST: {
19645       p = sqlite3MallocZero( sizeof(*p) );
19646       if( p ){
19647         pthread_mutex_init(&p->mutex, 0);
19648       }
19649       break;
19650     }
19651     default: {
19652 #ifdef SQLITE_ENABLE_API_ARMOR
19653       if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
19654         (void)SQLITE_MISUSE_BKPT;
19655         return 0;
19656       }
19657 #endif
19658       p = &staticMutexes[iType-2];
19659       break;
19660     }
19661   }
19662 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
19663   if( p ) p->id = iType;
19664 #endif
19665   return p;
19666 }
19667 
19668 
19669 /*
19670 ** This routine deallocates a previously
19671 ** allocated mutex.  SQLite is careful to deallocate every
19672 ** mutex that it allocates.
19673 */
pthreadMutexFree(sqlite3_mutex * p)19674 static void pthreadMutexFree(sqlite3_mutex *p){
19675   assert( p->nRef==0 );
19676 #if SQLITE_ENABLE_API_ARMOR
19677   if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
19678 #endif
19679   {
19680     pthread_mutex_destroy(&p->mutex);
19681     sqlite3_free(p);
19682   }
19683 #ifdef SQLITE_ENABLE_API_ARMOR
19684   else{
19685     (void)SQLITE_MISUSE_BKPT;
19686   }
19687 #endif
19688 }
19689 
19690 /*
19691 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
19692 ** to enter a mutex.  If another thread is already within the mutex,
19693 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
19694 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
19695 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
19696 ** be entered multiple times by the same thread.  In such cases the,
19697 ** mutex must be exited an equal number of times before another thread
19698 ** can enter.  If the same thread tries to enter any other kind of mutex
19699 ** more than once, the behavior is undefined.
19700 */
pthreadMutexEnter(sqlite3_mutex * p)19701 static void pthreadMutexEnter(sqlite3_mutex *p){
19702   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
19703 
19704 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19705   /* If recursive mutexes are not available, then we have to grow
19706   ** our own.  This implementation assumes that pthread_equal()
19707   ** is atomic - that it cannot be deceived into thinking self
19708   ** and p->owner are equal if p->owner changes between two values
19709   ** that are not equal to self while the comparison is taking place.
19710   ** This implementation also assumes a coherent cache - that
19711   ** separate processes cannot read different values from the same
19712   ** address at the same time.  If either of these two conditions
19713   ** are not met, then the mutexes will fail and problems will result.
19714   */
19715   {
19716     pthread_t self = pthread_self();
19717     if( p->nRef>0 && pthread_equal(p->owner, self) ){
19718       p->nRef++;
19719     }else{
19720       pthread_mutex_lock(&p->mutex);
19721       assert( p->nRef==0 );
19722       p->owner = self;
19723       p->nRef = 1;
19724     }
19725   }
19726 #else
19727   /* Use the built-in recursive mutexes if they are available.
19728   */
19729   pthread_mutex_lock(&p->mutex);
19730 #if SQLITE_MUTEX_NREF
19731   assert( p->nRef>0 || p->owner==0 );
19732   p->owner = pthread_self();
19733   p->nRef++;
19734 #endif
19735 #endif
19736 
19737 #ifdef SQLITE_DEBUG
19738   if( p->trace ){
19739     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19740   }
19741 #endif
19742 }
pthreadMutexTry(sqlite3_mutex * p)19743 static int pthreadMutexTry(sqlite3_mutex *p){
19744   int rc;
19745   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
19746 
19747 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19748   /* If recursive mutexes are not available, then we have to grow
19749   ** our own.  This implementation assumes that pthread_equal()
19750   ** is atomic - that it cannot be deceived into thinking self
19751   ** and p->owner are equal if p->owner changes between two values
19752   ** that are not equal to self while the comparison is taking place.
19753   ** This implementation also assumes a coherent cache - that
19754   ** separate processes cannot read different values from the same
19755   ** address at the same time.  If either of these two conditions
19756   ** are not met, then the mutexes will fail and problems will result.
19757   */
19758   {
19759     pthread_t self = pthread_self();
19760     if( p->nRef>0 && pthread_equal(p->owner, self) ){
19761       p->nRef++;
19762       rc = SQLITE_OK;
19763     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
19764       assert( p->nRef==0 );
19765       p->owner = self;
19766       p->nRef = 1;
19767       rc = SQLITE_OK;
19768     }else{
19769       rc = SQLITE_BUSY;
19770     }
19771   }
19772 #else
19773   /* Use the built-in recursive mutexes if they are available.
19774   */
19775   if( pthread_mutex_trylock(&p->mutex)==0 ){
19776 #if SQLITE_MUTEX_NREF
19777     p->owner = pthread_self();
19778     p->nRef++;
19779 #endif
19780     rc = SQLITE_OK;
19781   }else{
19782     rc = SQLITE_BUSY;
19783   }
19784 #endif
19785 
19786 #ifdef SQLITE_DEBUG
19787   if( rc==SQLITE_OK && p->trace ){
19788     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19789   }
19790 #endif
19791   return rc;
19792 }
19793 
19794 /*
19795 ** The sqlite3_mutex_leave() routine exits a mutex that was
19796 ** previously entered by the same thread.  The behavior
19797 ** is undefined if the mutex is not currently entered or
19798 ** is not currently allocated.  SQLite will never do either.
19799 */
pthreadMutexLeave(sqlite3_mutex * p)19800 static void pthreadMutexLeave(sqlite3_mutex *p){
19801   assert( pthreadMutexHeld(p) );
19802 #if SQLITE_MUTEX_NREF
19803   p->nRef--;
19804   if( p->nRef==0 ) p->owner = 0;
19805 #endif
19806   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
19807 
19808 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19809   if( p->nRef==0 ){
19810     pthread_mutex_unlock(&p->mutex);
19811   }
19812 #else
19813   pthread_mutex_unlock(&p->mutex);
19814 #endif
19815 
19816 #ifdef SQLITE_DEBUG
19817   if( p->trace ){
19818     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19819   }
19820 #endif
19821 }
19822 
sqlite3DefaultMutex(void)19823 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
19824   static const sqlite3_mutex_methods sMutex = {
19825     pthreadMutexInit,
19826     pthreadMutexEnd,
19827     pthreadMutexAlloc,
19828     pthreadMutexFree,
19829     pthreadMutexEnter,
19830     pthreadMutexTry,
19831     pthreadMutexLeave,
19832 #ifdef SQLITE_DEBUG
19833     pthreadMutexHeld,
19834     pthreadMutexNotheld
19835 #else
19836     0,
19837     0
19838 #endif
19839   };
19840 
19841   return &sMutex;
19842 }
19843 
19844 #endif /* SQLITE_MUTEX_PTHREADS */
19845 
19846 /************** End of mutex_unix.c ******************************************/
19847 /************** Begin file mutex_w32.c ***************************************/
19848 /*
19849 ** 2007 August 14
19850 **
19851 ** The author disclaims copyright to this source code.  In place of
19852 ** a legal notice, here is a blessing:
19853 **
19854 **    May you do good and not evil.
19855 **    May you find forgiveness for yourself and forgive others.
19856 **    May you share freely, never taking more than you give.
19857 **
19858 *************************************************************************
19859 ** This file contains the C functions that implement mutexes for Win32.
19860 */
19861 
19862 #if SQLITE_OS_WIN
19863 /*
19864 ** Include code that is common to all os_*.c files
19865 */
19866 /************** Include os_common.h in the middle of mutex_w32.c *************/
19867 /************** Begin file os_common.h ***************************************/
19868 /*
19869 ** 2004 May 22
19870 **
19871 ** The author disclaims copyright to this source code.  In place of
19872 ** a legal notice, here is a blessing:
19873 **
19874 **    May you do good and not evil.
19875 **    May you find forgiveness for yourself and forgive others.
19876 **    May you share freely, never taking more than you give.
19877 **
19878 ******************************************************************************
19879 **
19880 ** This file contains macros and a little bit of code that is common to
19881 ** all of the platform-specific files (os_*.c) and is #included into those
19882 ** files.
19883 **
19884 ** This file should be #included by the os_*.c files only.  It is not a
19885 ** general purpose header file.
19886 */
19887 #ifndef _OS_COMMON_H_
19888 #define _OS_COMMON_H_
19889 
19890 /*
19891 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
19892 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
19893 ** switch.  The following code should catch this problem at compile-time.
19894 */
19895 #ifdef MEMORY_DEBUG
19896 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
19897 #endif
19898 
19899 /*
19900 ** Macros for performance tracing.  Normally turned off.  Only works
19901 ** on i486 hardware.
19902 */
19903 #ifdef SQLITE_PERFORMANCE_TRACE
19904 
19905 /*
19906 ** hwtime.h contains inline assembler code for implementing
19907 ** high-performance timing routines.
19908 */
19909 /************** Include hwtime.h in the middle of os_common.h ****************/
19910 /************** Begin file hwtime.h ******************************************/
19911 /*
19912 ** 2008 May 27
19913 **
19914 ** The author disclaims copyright to this source code.  In place of
19915 ** a legal notice, here is a blessing:
19916 **
19917 **    May you do good and not evil.
19918 **    May you find forgiveness for yourself and forgive others.
19919 **    May you share freely, never taking more than you give.
19920 **
19921 ******************************************************************************
19922 **
19923 ** This file contains inline asm code for retrieving "high-performance"
19924 ** counters for x86 class CPUs.
19925 */
19926 #ifndef _HWTIME_H_
19927 #define _HWTIME_H_
19928 
19929 /*
19930 ** The following routine only works on pentium-class (or newer) processors.
19931 ** It uses the RDTSC opcode to read the cycle count value out of the
19932 ** processor and returns that value.  This can be used for high-res
19933 ** profiling.
19934 */
19935 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
19936       (defined(i386) || defined(__i386__) || defined(_M_IX86))
19937 
19938   #if defined(__GNUC__)
19939 
sqlite3Hwtime(void)19940   __inline__ sqlite_uint64 sqlite3Hwtime(void){
19941      unsigned int lo, hi;
19942      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
19943      return (sqlite_uint64)hi << 32 | lo;
19944   }
19945 
19946   #elif defined(_MSC_VER)
19947 
sqlite3Hwtime(void)19948   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
19949      __asm {
19950         rdtsc
19951         ret       ; return value at EDX:EAX
19952      }
19953   }
19954 
19955   #endif
19956 
19957 #elif (defined(__GNUC__) && defined(__x86_64__))
19958 
19959   __inline__ sqlite_uint64 sqlite3Hwtime(void){
19960       unsigned long val;
19961       __asm__ __volatile__ ("rdtsc" : "=A" (val));
19962       return val;
19963   }
19964 
19965 #elif (defined(__GNUC__) && defined(__ppc__))
19966 
19967   __inline__ sqlite_uint64 sqlite3Hwtime(void){
19968       unsigned long long retval;
19969       unsigned long junk;
19970       __asm__ __volatile__ ("\n\
19971           1:      mftbu   %1\n\
19972                   mftb    %L0\n\
19973                   mftbu   %0\n\
19974                   cmpw    %0,%1\n\
19975                   bne     1b"
19976                   : "=r" (retval), "=r" (junk));
19977       return retval;
19978   }
19979 
19980 #else
19981 
19982   #error Need implementation of sqlite3Hwtime() for your platform.
19983 
19984   /*
19985   ** To compile without implementing sqlite3Hwtime() for your platform,
19986   ** you can remove the above #error and use the following
19987   ** stub function.  You will lose timing support for many
19988   ** of the debugging and testing utilities, but it should at
19989   ** least compile and run.
19990   */
19991 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
19992 
19993 #endif
19994 
19995 #endif /* !defined(_HWTIME_H_) */
19996 
19997 /************** End of hwtime.h **********************************************/
19998 /************** Continuing where we left off in os_common.h ******************/
19999 
20000 static sqlite_uint64 g_start;
20001 static sqlite_uint64 g_elapsed;
20002 #define TIMER_START       g_start=sqlite3Hwtime()
20003 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
20004 #define TIMER_ELAPSED     g_elapsed
20005 #else
20006 #define TIMER_START
20007 #define TIMER_END
20008 #define TIMER_ELAPSED     ((sqlite_uint64)0)
20009 #endif
20010 
20011 /*
20012 ** If we compile with the SQLITE_TEST macro set, then the following block
20013 ** of code will give us the ability to simulate a disk I/O error.  This
20014 ** is used for testing the I/O recovery logic.
20015 */
20016 #ifdef SQLITE_TEST
20017 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
20018 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
20019 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
20020 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
20021 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
20022 SQLITE_API int sqlite3_diskfull_pending = 0;
20023 SQLITE_API int sqlite3_diskfull = 0;
20024 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
20025 #define SimulateIOError(CODE)  \
20026   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
20027        || sqlite3_io_error_pending-- == 1 )  \
20028               { local_ioerr(); CODE; }
20029 static void local_ioerr(){
20030   IOTRACE(("IOERR\n"));
20031   sqlite3_io_error_hit++;
20032   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
20033 }
20034 #define SimulateDiskfullError(CODE) \
20035    if( sqlite3_diskfull_pending ){ \
20036      if( sqlite3_diskfull_pending == 1 ){ \
20037        local_ioerr(); \
20038        sqlite3_diskfull = 1; \
20039        sqlite3_io_error_hit = 1; \
20040        CODE; \
20041      }else{ \
20042        sqlite3_diskfull_pending--; \
20043      } \
20044    }
20045 #else
20046 #define SimulateIOErrorBenign(X)
20047 #define SimulateIOError(A)
20048 #define SimulateDiskfullError(A)
20049 #endif
20050 
20051 /*
20052 ** When testing, keep a count of the number of open files.
20053 */
20054 #ifdef SQLITE_TEST
20055 SQLITE_API int sqlite3_open_file_count = 0;
20056 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
20057 #else
20058 #define OpenCounter(X)
20059 #endif
20060 
20061 #endif /* !defined(_OS_COMMON_H_) */
20062 
20063 /************** End of os_common.h *******************************************/
20064 /************** Continuing where we left off in mutex_w32.c ******************/
20065 
20066 /*
20067 ** Include the header file for the Windows VFS.
20068 */
20069 /************** Include os_win.h in the middle of mutex_w32.c ****************/
20070 /************** Begin file os_win.h ******************************************/
20071 /*
20072 ** 2013 November 25
20073 **
20074 ** The author disclaims copyright to this source code.  In place of
20075 ** a legal notice, here is a blessing:
20076 **
20077 **    May you do good and not evil.
20078 **    May you find forgiveness for yourself and forgive others.
20079 **    May you share freely, never taking more than you give.
20080 **
20081 ******************************************************************************
20082 **
20083 ** This file contains code that is specific to Windows.
20084 */
20085 #ifndef _OS_WIN_H_
20086 #define _OS_WIN_H_
20087 
20088 /*
20089 ** Include the primary Windows SDK header file.
20090 */
20091 #include "windows.h"
20092 
20093 #ifdef __CYGWIN__
20094 # include <sys/cygwin.h>
20095 # include <errno.h> /* amalgamator: dontcache */
20096 #endif
20097 
20098 /*
20099 ** Determine if we are dealing with Windows NT.
20100 **
20101 ** We ought to be able to determine if we are compiling for Windows 9x or
20102 ** Windows NT using the _WIN32_WINNT macro as follows:
20103 **
20104 ** #if defined(_WIN32_WINNT)
20105 ** # define SQLITE_OS_WINNT 1
20106 ** #else
20107 ** # define SQLITE_OS_WINNT 0
20108 ** #endif
20109 **
20110 ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
20111 ** it ought to, so the above test does not work.  We'll just assume that
20112 ** everything is Windows NT unless the programmer explicitly says otherwise
20113 ** by setting SQLITE_OS_WINNT to 0.
20114 */
20115 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
20116 # define SQLITE_OS_WINNT 1
20117 #endif
20118 
20119 /*
20120 ** Determine if we are dealing with Windows CE - which has a much reduced
20121 ** API.
20122 */
20123 #if defined(_WIN32_WCE)
20124 # define SQLITE_OS_WINCE 1
20125 #else
20126 # define SQLITE_OS_WINCE 0
20127 #endif
20128 
20129 /*
20130 ** Determine if we are dealing with WinRT, which provides only a subset of
20131 ** the full Win32 API.
20132 */
20133 #if !defined(SQLITE_OS_WINRT)
20134 # define SQLITE_OS_WINRT 0
20135 #endif
20136 
20137 /*
20138 ** For WinCE, some API function parameters do not appear to be declared as
20139 ** volatile.
20140 */
20141 #if SQLITE_OS_WINCE
20142 # define SQLITE_WIN32_VOLATILE
20143 #else
20144 # define SQLITE_WIN32_VOLATILE volatile
20145 #endif
20146 
20147 /*
20148 ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
20149 ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
20150 */
20151 #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
20152     SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
20153 # define SQLITE_OS_WIN_THREADS 1
20154 #else
20155 # define SQLITE_OS_WIN_THREADS 0
20156 #endif
20157 
20158 #endif /* _OS_WIN_H_ */
20159 
20160 /************** End of os_win.h **********************************************/
20161 /************** Continuing where we left off in mutex_w32.c ******************/
20162 #endif
20163 
20164 /*
20165 ** The code in this file is only used if we are compiling multithreaded
20166 ** on a Win32 system.
20167 */
20168 #ifdef SQLITE_MUTEX_W32
20169 
20170 /*
20171 ** Each recursive mutex is an instance of the following structure.
20172 */
20173 struct sqlite3_mutex {
20174   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
20175   int id;                    /* Mutex type */
20176 #ifdef SQLITE_DEBUG
20177   volatile int nRef;         /* Number of enterances */
20178   volatile DWORD owner;      /* Thread holding this mutex */
20179   volatile int trace;        /* True to trace changes */
20180 #endif
20181 };
20182 
20183 /*
20184 ** These are the initializer values used when declaring a "static" mutex
20185 ** on Win32.  It should be noted that all mutexes require initialization
20186 ** on the Win32 platform.
20187 */
20188 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
20189 
20190 #ifdef SQLITE_DEBUG
20191 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
20192                                     0L, (DWORD)0, 0 }
20193 #else
20194 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
20195 #endif
20196 
20197 #ifdef SQLITE_DEBUG
20198 /*
20199 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
20200 ** intended for use only inside assert() statements.
20201 */
20202 static int winMutexHeld(sqlite3_mutex *p){
20203   return p->nRef!=0 && p->owner==GetCurrentThreadId();
20204 }
20205 
20206 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
20207   return p->nRef==0 || p->owner!=tid;
20208 }
20209 
20210 static int winMutexNotheld(sqlite3_mutex *p){
20211   DWORD tid = GetCurrentThreadId();
20212   return winMutexNotheld2(p, tid);
20213 }
20214 #endif
20215 
20216 /*
20217 ** Initialize and deinitialize the mutex subsystem.
20218 */
20219 static sqlite3_mutex winMutex_staticMutexes[] = {
20220   SQLITE3_MUTEX_INITIALIZER,
20221   SQLITE3_MUTEX_INITIALIZER,
20222   SQLITE3_MUTEX_INITIALIZER,
20223   SQLITE3_MUTEX_INITIALIZER,
20224   SQLITE3_MUTEX_INITIALIZER,
20225   SQLITE3_MUTEX_INITIALIZER,
20226   SQLITE3_MUTEX_INITIALIZER,
20227   SQLITE3_MUTEX_INITIALIZER,
20228   SQLITE3_MUTEX_INITIALIZER
20229 };
20230 
20231 static int winMutex_isInit = 0;
20232 static int winMutex_isNt = -1; /* <0 means "need to query" */
20233 
20234 /* As the winMutexInit() and winMutexEnd() functions are called as part
20235 ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
20236 ** "interlocked" magic used here is probably not strictly necessary.
20237 */
20238 static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
20239 
20240 SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void); /* os_win.c */
20241 SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
20242 
20243 static int winMutexInit(void){
20244   /* The first to increment to 1 does actual initialization */
20245   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
20246     int i;
20247     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
20248 #if SQLITE_OS_WINRT
20249       InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
20250 #else
20251       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
20252 #endif
20253     }
20254     winMutex_isInit = 1;
20255   }else{
20256     /* Another thread is (in the process of) initializing the static
20257     ** mutexes */
20258     while( !winMutex_isInit ){
20259       sqlite3_win32_sleep(1);
20260     }
20261   }
20262   return SQLITE_OK;
20263 }
20264 
20265 static int winMutexEnd(void){
20266   /* The first to decrement to 0 does actual shutdown
20267   ** (which should be the last to shutdown.) */
20268   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
20269     if( winMutex_isInit==1 ){
20270       int i;
20271       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
20272         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
20273       }
20274       winMutex_isInit = 0;
20275     }
20276   }
20277   return SQLITE_OK;
20278 }
20279 
20280 /*
20281 ** The sqlite3_mutex_alloc() routine allocates a new
20282 ** mutex and returns a pointer to it.  If it returns NULL
20283 ** that means that a mutex could not be allocated.  SQLite
20284 ** will unwind its stack and return an error.  The argument
20285 ** to sqlite3_mutex_alloc() is one of these integer constants:
20286 **
20287 ** <ul>
20288 ** <li>  SQLITE_MUTEX_FAST
20289 ** <li>  SQLITE_MUTEX_RECURSIVE
20290 ** <li>  SQLITE_MUTEX_STATIC_MASTER
20291 ** <li>  SQLITE_MUTEX_STATIC_MEM
20292 ** <li>  SQLITE_MUTEX_STATIC_OPEN
20293 ** <li>  SQLITE_MUTEX_STATIC_PRNG
20294 ** <li>  SQLITE_MUTEX_STATIC_LRU
20295 ** <li>  SQLITE_MUTEX_STATIC_PMEM
20296 ** <li>  SQLITE_MUTEX_STATIC_APP1
20297 ** <li>  SQLITE_MUTEX_STATIC_APP2
20298 ** <li>  SQLITE_MUTEX_STATIC_APP3
20299 ** </ul>
20300 **
20301 ** The first two constants cause sqlite3_mutex_alloc() to create
20302 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
20303 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
20304 ** The mutex implementation does not need to make a distinction
20305 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
20306 ** not want to.  But SQLite will only request a recursive mutex in
20307 ** cases where it really needs one.  If a faster non-recursive mutex
20308 ** implementation is available on the host platform, the mutex subsystem
20309 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
20310 **
20311 ** The other allowed parameters to sqlite3_mutex_alloc() each return
20312 ** a pointer to a static preexisting mutex.  Six static mutexes are
20313 ** used by the current version of SQLite.  Future versions of SQLite
20314 ** may add additional static mutexes.  Static mutexes are for internal
20315 ** use by SQLite only.  Applications that use SQLite mutexes should
20316 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
20317 ** SQLITE_MUTEX_RECURSIVE.
20318 **
20319 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
20320 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
20321 ** returns a different mutex on every call.  But for the static
20322 ** mutex types, the same mutex is returned on every call that has
20323 ** the same type number.
20324 */
20325 static sqlite3_mutex *winMutexAlloc(int iType){
20326   sqlite3_mutex *p;
20327 
20328   switch( iType ){
20329     case SQLITE_MUTEX_FAST:
20330     case SQLITE_MUTEX_RECURSIVE: {
20331       p = sqlite3MallocZero( sizeof(*p) );
20332       if( p ){
20333         p->id = iType;
20334 #ifdef SQLITE_DEBUG
20335 #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
20336         p->trace = 1;
20337 #endif
20338 #endif
20339 #if SQLITE_OS_WINRT
20340         InitializeCriticalSectionEx(&p->mutex, 0, 0);
20341 #else
20342         InitializeCriticalSection(&p->mutex);
20343 #endif
20344       }
20345       break;
20346     }
20347     default: {
20348 #ifdef SQLITE_ENABLE_API_ARMOR
20349       if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
20350         (void)SQLITE_MISUSE_BKPT;
20351         return 0;
20352       }
20353 #endif
20354       p = &winMutex_staticMutexes[iType-2];
20355       p->id = iType;
20356 #ifdef SQLITE_DEBUG
20357 #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
20358       p->trace = 1;
20359 #endif
20360 #endif
20361       break;
20362     }
20363   }
20364   return p;
20365 }
20366 
20367 
20368 /*
20369 ** This routine deallocates a previously
20370 ** allocated mutex.  SQLite is careful to deallocate every
20371 ** mutex that it allocates.
20372 */
20373 static void winMutexFree(sqlite3_mutex *p){
20374   assert( p );
20375   assert( p->nRef==0 && p->owner==0 );
20376   if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
20377     DeleteCriticalSection(&p->mutex);
20378     sqlite3_free(p);
20379   }else{
20380 #ifdef SQLITE_ENABLE_API_ARMOR
20381     (void)SQLITE_MISUSE_BKPT;
20382 #endif
20383   }
20384 }
20385 
20386 /*
20387 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
20388 ** to enter a mutex.  If another thread is already within the mutex,
20389 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
20390 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
20391 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
20392 ** be entered multiple times by the same thread.  In such cases the,
20393 ** mutex must be exited an equal number of times before another thread
20394 ** can enter.  If the same thread tries to enter any other kind of mutex
20395 ** more than once, the behavior is undefined.
20396 */
20397 static void winMutexEnter(sqlite3_mutex *p){
20398 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
20399   DWORD tid = GetCurrentThreadId();
20400 #endif
20401 #ifdef SQLITE_DEBUG
20402   assert( p );
20403   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
20404 #else
20405   assert( p );
20406 #endif
20407   assert( winMutex_isInit==1 );
20408   EnterCriticalSection(&p->mutex);
20409 #ifdef SQLITE_DEBUG
20410   assert( p->nRef>0 || p->owner==0 );
20411   p->owner = tid;
20412   p->nRef++;
20413   if( p->trace ){
20414     OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
20415              tid, p, p->trace, p->nRef));
20416   }
20417 #endif
20418 }
20419 
20420 static int winMutexTry(sqlite3_mutex *p){
20421 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
20422   DWORD tid = GetCurrentThreadId();
20423 #endif
20424   int rc = SQLITE_BUSY;
20425   assert( p );
20426   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
20427   /*
20428   ** The sqlite3_mutex_try() routine is very rarely used, and when it
20429   ** is used it is merely an optimization.  So it is OK for it to always
20430   ** fail.
20431   **
20432   ** The TryEnterCriticalSection() interface is only available on WinNT.
20433   ** And some windows compilers complain if you try to use it without
20434   ** first doing some #defines that prevent SQLite from building on Win98.
20435   ** For that reason, we will omit this optimization for now.  See
20436   ** ticket #2685.
20437   */
20438 #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
20439   assert( winMutex_isInit==1 );
20440   assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
20441   if( winMutex_isNt<0 ){
20442     winMutex_isNt = sqlite3_win32_is_nt();
20443   }
20444   assert( winMutex_isNt==0 || winMutex_isNt==1 );
20445   if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
20446 #ifdef SQLITE_DEBUG
20447     p->owner = tid;
20448     p->nRef++;
20449 #endif
20450     rc = SQLITE_OK;
20451   }
20452 #else
20453   UNUSED_PARAMETER(p);
20454 #endif
20455 #ifdef SQLITE_DEBUG
20456   if( p->trace ){
20457     OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
20458              tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
20459   }
20460 #endif
20461   return rc;
20462 }
20463 
20464 /*
20465 ** The sqlite3_mutex_leave() routine exits a mutex that was
20466 ** previously entered by the same thread.  The behavior
20467 ** is undefined if the mutex is not currently entered or
20468 ** is not currently allocated.  SQLite will never do either.
20469 */
20470 static void winMutexLeave(sqlite3_mutex *p){
20471 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
20472   DWORD tid = GetCurrentThreadId();
20473 #endif
20474   assert( p );
20475 #ifdef SQLITE_DEBUG
20476   assert( p->nRef>0 );
20477   assert( p->owner==tid );
20478   p->nRef--;
20479   if( p->nRef==0 ) p->owner = 0;
20480   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
20481 #endif
20482   assert( winMutex_isInit==1 );
20483   LeaveCriticalSection(&p->mutex);
20484 #ifdef SQLITE_DEBUG
20485   if( p->trace ){
20486     OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
20487              tid, p, p->trace, p->nRef));
20488   }
20489 #endif
20490 }
20491 
20492 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
20493   static const sqlite3_mutex_methods sMutex = {
20494     winMutexInit,
20495     winMutexEnd,
20496     winMutexAlloc,
20497     winMutexFree,
20498     winMutexEnter,
20499     winMutexTry,
20500     winMutexLeave,
20501 #ifdef SQLITE_DEBUG
20502     winMutexHeld,
20503     winMutexNotheld
20504 #else
20505     0,
20506     0
20507 #endif
20508   };
20509   return &sMutex;
20510 }
20511 
20512 #endif /* SQLITE_MUTEX_W32 */
20513 
20514 /************** End of mutex_w32.c *******************************************/
20515 /************** Begin file malloc.c ******************************************/
20516 /*
20517 ** 2001 September 15
20518 **
20519 ** The author disclaims copyright to this source code.  In place of
20520 ** a legal notice, here is a blessing:
20521 **
20522 **    May you do good and not evil.
20523 **    May you find forgiveness for yourself and forgive others.
20524 **    May you share freely, never taking more than you give.
20525 **
20526 *************************************************************************
20527 **
20528 ** Memory allocation functions used throughout sqlite.
20529 */
20530 /* #include <stdarg.h> */
20531 
20532 /*
20533 ** Attempt to release up to n bytes of non-essential memory currently
20534 ** held by SQLite. An example of non-essential memory is memory used to
20535 ** cache database pages that are not currently in use.
20536 */
20537 SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int n){
20538 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20539   return sqlite3PcacheReleaseMemory(n);
20540 #else
20541   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
20542   ** is a no-op returning zero if SQLite is not compiled with
20543   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
20544   UNUSED_PARAMETER(n);
20545   return 0;
20546 #endif
20547 }
20548 
20549 /*
20550 ** An instance of the following object records the location of
20551 ** each unused scratch buffer.
20552 */
20553 typedef struct ScratchFreeslot {
20554   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
20555 } ScratchFreeslot;
20556 
20557 /*
20558 ** State information local to the memory allocation subsystem.
20559 */
20560 static SQLITE_WSD struct Mem0Global {
20561   sqlite3_mutex *mutex;         /* Mutex to serialize access */
20562 
20563   /*
20564   ** The alarm callback and its arguments.  The mem0.mutex lock will
20565   ** be held while the callback is running.  Recursive calls into
20566   ** the memory subsystem are allowed, but no new callbacks will be
20567   ** issued.
20568   */
20569   sqlite3_int64 alarmThreshold;
20570   void (*alarmCallback)(void*, sqlite3_int64,int);
20571   void *alarmArg;
20572 
20573   /*
20574   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
20575   ** (so that a range test can be used to determine if an allocation
20576   ** being freed came from pScratch) and a pointer to the list of
20577   ** unused scratch allocations.
20578   */
20579   void *pScratchEnd;
20580   ScratchFreeslot *pScratchFree;
20581   u32 nScratchFree;
20582 
20583   /*
20584   ** True if heap is nearly "full" where "full" is defined by the
20585   ** sqlite3_soft_heap_limit() setting.
20586   */
20587   int nearlyFull;
20588 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
20589 
20590 #define mem0 GLOBAL(struct Mem0Global, mem0)
20591 
20592 /*
20593 ** Return the memory allocator mutex. sqlite3_status() needs it.
20594 */
20595 SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
20596   return mem0.mutex;
20597 }
20598 
20599 /*
20600 ** This routine runs when the memory allocator sees that the
20601 ** total memory allocation is about to exceed the soft heap
20602 ** limit.
20603 */
20604 static void softHeapLimitEnforcer(
20605   void *NotUsed,
20606   sqlite3_int64 NotUsed2,
20607   int allocSize
20608 ){
20609   UNUSED_PARAMETER2(NotUsed, NotUsed2);
20610   sqlite3_release_memory(allocSize);
20611 }
20612 
20613 /*
20614 ** Change the alarm callback
20615 */
20616 static int sqlite3MemoryAlarm(
20617   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
20618   void *pArg,
20619   sqlite3_int64 iThreshold
20620 ){
20621   sqlite3_int64 nUsed;
20622   sqlite3_mutex_enter(mem0.mutex);
20623   mem0.alarmCallback = xCallback;
20624   mem0.alarmArg = pArg;
20625   mem0.alarmThreshold = iThreshold;
20626   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20627   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
20628   sqlite3_mutex_leave(mem0.mutex);
20629   return SQLITE_OK;
20630 }
20631 
20632 #ifndef SQLITE_OMIT_DEPRECATED
20633 /*
20634 ** Deprecated external interface.  Internal/core SQLite code
20635 ** should call sqlite3MemoryAlarm.
20636 */
20637 SQLITE_API int SQLITE_STDCALL sqlite3_memory_alarm(
20638   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
20639   void *pArg,
20640   sqlite3_int64 iThreshold
20641 ){
20642   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
20643 }
20644 #endif
20645 
20646 /*
20647 ** Set the soft heap-size limit for the library. Passing a zero or
20648 ** negative value indicates no limit.
20649 */
20650 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 n){
20651   sqlite3_int64 priorLimit;
20652   sqlite3_int64 excess;
20653 #ifndef SQLITE_OMIT_AUTOINIT
20654   int rc = sqlite3_initialize();
20655   if( rc ) return -1;
20656 #endif
20657   sqlite3_mutex_enter(mem0.mutex);
20658   priorLimit = mem0.alarmThreshold;
20659   sqlite3_mutex_leave(mem0.mutex);
20660   if( n<0 ) return priorLimit;
20661   if( n>0 ){
20662     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
20663   }else{
20664     sqlite3MemoryAlarm(0, 0, 0);
20665   }
20666   excess = sqlite3_memory_used() - n;
20667   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
20668   return priorLimit;
20669 }
20670 SQLITE_API void SQLITE_STDCALL sqlite3_soft_heap_limit(int n){
20671   if( n<0 ) n = 0;
20672   sqlite3_soft_heap_limit64(n);
20673 }
20674 
20675 /*
20676 ** Initialize the memory allocation subsystem.
20677 */
20678 SQLITE_PRIVATE int sqlite3MallocInit(void){
20679   int rc;
20680   if( sqlite3GlobalConfig.m.xMalloc==0 ){
20681     sqlite3MemSetDefault();
20682   }
20683   memset(&mem0, 0, sizeof(mem0));
20684   if( sqlite3GlobalConfig.bCoreMutex ){
20685     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
20686   }
20687   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
20688       && sqlite3GlobalConfig.nScratch>0 ){
20689     int i, n, sz;
20690     ScratchFreeslot *pSlot;
20691     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
20692     sqlite3GlobalConfig.szScratch = sz;
20693     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
20694     n = sqlite3GlobalConfig.nScratch;
20695     mem0.pScratchFree = pSlot;
20696     mem0.nScratchFree = n;
20697     for(i=0; i<n-1; i++){
20698       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
20699       pSlot = pSlot->pNext;
20700     }
20701     pSlot->pNext = 0;
20702     mem0.pScratchEnd = (void*)&pSlot[1];
20703   }else{
20704     mem0.pScratchEnd = 0;
20705     sqlite3GlobalConfig.pScratch = 0;
20706     sqlite3GlobalConfig.szScratch = 0;
20707     sqlite3GlobalConfig.nScratch = 0;
20708   }
20709   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
20710       || sqlite3GlobalConfig.nPage<1 ){
20711     sqlite3GlobalConfig.pPage = 0;
20712     sqlite3GlobalConfig.szPage = 0;
20713     sqlite3GlobalConfig.nPage = 0;
20714   }
20715   rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
20716   if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
20717   return rc;
20718 }
20719 
20720 /*
20721 ** Return true if the heap is currently under memory pressure - in other
20722 ** words if the amount of heap used is close to the limit set by
20723 ** sqlite3_soft_heap_limit().
20724 */
20725 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
20726   return mem0.nearlyFull;
20727 }
20728 
20729 /*
20730 ** Deinitialize the memory allocation subsystem.
20731 */
20732 SQLITE_PRIVATE void sqlite3MallocEnd(void){
20733   if( sqlite3GlobalConfig.m.xShutdown ){
20734     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
20735   }
20736   memset(&mem0, 0, sizeof(mem0));
20737 }
20738 
20739 /*
20740 ** Return the amount of memory currently checked out.
20741 */
20742 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void){
20743   int n, mx;
20744   sqlite3_int64 res;
20745   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
20746   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
20747   return res;
20748 }
20749 
20750 /*
20751 ** Return the maximum amount of memory that has ever been
20752 ** checked out since either the beginning of this process
20753 ** or since the most recent reset.
20754 */
20755 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag){
20756   int n, mx;
20757   sqlite3_int64 res;
20758   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
20759   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
20760   return res;
20761 }
20762 
20763 /*
20764 ** Trigger the alarm
20765 */
20766 static void sqlite3MallocAlarm(int nByte){
20767   void (*xCallback)(void*,sqlite3_int64,int);
20768   sqlite3_int64 nowUsed;
20769   void *pArg;
20770   if( mem0.alarmCallback==0 ) return;
20771   xCallback = mem0.alarmCallback;
20772   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20773   pArg = mem0.alarmArg;
20774   mem0.alarmCallback = 0;
20775   sqlite3_mutex_leave(mem0.mutex);
20776   xCallback(pArg, nowUsed, nByte);
20777   sqlite3_mutex_enter(mem0.mutex);
20778   mem0.alarmCallback = xCallback;
20779   mem0.alarmArg = pArg;
20780 }
20781 
20782 /*
20783 ** Do a memory allocation with statistics and alarms.  Assume the
20784 ** lock is already held.
20785 */
20786 static int mallocWithAlarm(int n, void **pp){
20787   int nFull;
20788   void *p;
20789   assert( sqlite3_mutex_held(mem0.mutex) );
20790   nFull = sqlite3GlobalConfig.m.xRoundup(n);
20791   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
20792   if( mem0.alarmCallback!=0 ){
20793     sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20794     if( nUsed >= mem0.alarmThreshold - nFull ){
20795       mem0.nearlyFull = 1;
20796       sqlite3MallocAlarm(nFull);
20797     }else{
20798       mem0.nearlyFull = 0;
20799     }
20800   }
20801   p = sqlite3GlobalConfig.m.xMalloc(nFull);
20802 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20803   if( p==0 && mem0.alarmCallback ){
20804     sqlite3MallocAlarm(nFull);
20805     p = sqlite3GlobalConfig.m.xMalloc(nFull);
20806   }
20807 #endif
20808   if( p ){
20809     nFull = sqlite3MallocSize(p);
20810     sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
20811     sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
20812   }
20813   *pp = p;
20814   return nFull;
20815 }
20816 
20817 /*
20818 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
20819 ** assumes the memory subsystem has already been initialized.
20820 */
20821 SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
20822   void *p;
20823   if( n==0 || n>=0x7fffff00 ){
20824     /* A memory allocation of a number of bytes which is near the maximum
20825     ** signed integer value might cause an integer overflow inside of the
20826     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
20827     ** 255 bytes of overhead.  SQLite itself will never use anything near
20828     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
20829     p = 0;
20830   }else if( sqlite3GlobalConfig.bMemstat ){
20831     sqlite3_mutex_enter(mem0.mutex);
20832     mallocWithAlarm((int)n, &p);
20833     sqlite3_mutex_leave(mem0.mutex);
20834   }else{
20835     p = sqlite3GlobalConfig.m.xMalloc((int)n);
20836   }
20837   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
20838   return p;
20839 }
20840 
20841 /*
20842 ** This version of the memory allocation is for use by the application.
20843 ** First make sure the memory subsystem is initialized, then do the
20844 ** allocation.
20845 */
20846 SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int n){
20847 #ifndef SQLITE_OMIT_AUTOINIT
20848   if( sqlite3_initialize() ) return 0;
20849 #endif
20850   return n<=0 ? 0 : sqlite3Malloc(n);
20851 }
20852 SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64 n){
20853 #ifndef SQLITE_OMIT_AUTOINIT
20854   if( sqlite3_initialize() ) return 0;
20855 #endif
20856   return sqlite3Malloc(n);
20857 }
20858 
20859 /*
20860 ** Each thread may only have a single outstanding allocation from
20861 ** xScratchMalloc().  We verify this constraint in the single-threaded
20862 ** case by setting scratchAllocOut to 1 when an allocation
20863 ** is outstanding clearing it when the allocation is freed.
20864 */
20865 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
20866 static int scratchAllocOut = 0;
20867 #endif
20868 
20869 
20870 /*
20871 ** Allocate memory that is to be used and released right away.
20872 ** This routine is similar to alloca() in that it is not intended
20873 ** for situations where the memory might be held long-term.  This
20874 ** routine is intended to get memory to old large transient data
20875 ** structures that would not normally fit on the stack of an
20876 ** embedded processor.
20877 */
20878 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
20879   void *p;
20880   assert( n>0 );
20881 
20882   sqlite3_mutex_enter(mem0.mutex);
20883   sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
20884   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
20885     p = mem0.pScratchFree;
20886     mem0.pScratchFree = mem0.pScratchFree->pNext;
20887     mem0.nScratchFree--;
20888     sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
20889     sqlite3_mutex_leave(mem0.mutex);
20890   }else{
20891     sqlite3_mutex_leave(mem0.mutex);
20892     p = sqlite3Malloc(n);
20893     if( sqlite3GlobalConfig.bMemstat && p ){
20894       sqlite3_mutex_enter(mem0.mutex);
20895       sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
20896       sqlite3_mutex_leave(mem0.mutex);
20897     }
20898     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
20899   }
20900   assert( sqlite3_mutex_notheld(mem0.mutex) );
20901 
20902 
20903 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
20904   /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
20905   ** buffers per thread.
20906   **
20907   ** This can only be checked in single-threaded mode.
20908   */
20909   assert( scratchAllocOut==0 );
20910   if( p ) scratchAllocOut++;
20911 #endif
20912 
20913   return p;
20914 }
20915 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
20916   if( p ){
20917 
20918 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
20919     /* Verify that no more than two scratch allocation per thread
20920     ** is outstanding at one time.  (This is only checked in the
20921     ** single-threaded case since checking in the multi-threaded case
20922     ** would be much more complicated.) */
20923     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
20924     scratchAllocOut--;
20925 #endif
20926 
20927     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
20928       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
20929       ScratchFreeslot *pSlot;
20930       pSlot = (ScratchFreeslot*)p;
20931       sqlite3_mutex_enter(mem0.mutex);
20932       pSlot->pNext = mem0.pScratchFree;
20933       mem0.pScratchFree = pSlot;
20934       mem0.nScratchFree++;
20935       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
20936       sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
20937       sqlite3_mutex_leave(mem0.mutex);
20938     }else{
20939       /* Release memory back to the heap */
20940       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
20941       assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
20942       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
20943       if( sqlite3GlobalConfig.bMemstat ){
20944         int iSize = sqlite3MallocSize(p);
20945         sqlite3_mutex_enter(mem0.mutex);
20946         sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
20947         sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
20948         sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
20949         sqlite3GlobalConfig.m.xFree(p);
20950         sqlite3_mutex_leave(mem0.mutex);
20951       }else{
20952         sqlite3GlobalConfig.m.xFree(p);
20953       }
20954     }
20955   }
20956 }
20957 
20958 /*
20959 ** TRUE if p is a lookaside memory allocation from db
20960 */
20961 #ifndef SQLITE_OMIT_LOOKASIDE
20962 static int isLookaside(sqlite3 *db, void *p){
20963   return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
20964 }
20965 #else
20966 #define isLookaside(A,B) 0
20967 #endif
20968 
20969 /*
20970 ** Return the size of a memory allocation previously obtained from
20971 ** sqlite3Malloc() or sqlite3_malloc().
20972 */
20973 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
20974   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20975   return sqlite3GlobalConfig.m.xSize(p);
20976 }
20977 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
20978   if( db==0 ){
20979     assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
20980     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20981     return sqlite3MallocSize(p);
20982   }else{
20983     assert( sqlite3_mutex_held(db->mutex) );
20984     if( isLookaside(db, p) ){
20985       return db->lookaside.sz;
20986     }else{
20987       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20988       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20989       return sqlite3GlobalConfig.m.xSize(p);
20990     }
20991   }
20992 }
20993 SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void *p){
20994   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
20995   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20996   return (sqlite3_uint64)sqlite3GlobalConfig.m.xSize(p);
20997 }
20998 
20999 /*
21000 ** Free memory previously obtained from sqlite3Malloc().
21001 */
21002 SQLITE_API void SQLITE_STDCALL sqlite3_free(void *p){
21003   if( p==0 ) return;  /* IMP: R-49053-54554 */
21004   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
21005   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
21006   if( sqlite3GlobalConfig.bMemstat ){
21007     sqlite3_mutex_enter(mem0.mutex);
21008     sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
21009     sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
21010     sqlite3GlobalConfig.m.xFree(p);
21011     sqlite3_mutex_leave(mem0.mutex);
21012   }else{
21013     sqlite3GlobalConfig.m.xFree(p);
21014   }
21015 }
21016 
21017 /*
21018 ** Add the size of memory allocation "p" to the count in
21019 ** *db->pnBytesFreed.
21020 */
21021 static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
21022   *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
21023 }
21024 
21025 /*
21026 ** Free memory that might be associated with a particular database
21027 ** connection.
21028 */
21029 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
21030   assert( db==0 || sqlite3_mutex_held(db->mutex) );
21031   if( p==0 ) return;
21032   if( db ){
21033     if( db->pnBytesFreed ){
21034       measureAllocationSize(db, p);
21035       return;
21036     }
21037     if( isLookaside(db, p) ){
21038       LookasideSlot *pBuf = (LookasideSlot*)p;
21039 #if SQLITE_DEBUG
21040       /* Trash all content in the buffer being freed */
21041       memset(p, 0xaa, db->lookaside.sz);
21042 #endif
21043       pBuf->pNext = db->lookaside.pFree;
21044       db->lookaside.pFree = pBuf;
21045       db->lookaside.nOut--;
21046       return;
21047     }
21048   }
21049   assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
21050   assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
21051   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
21052   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
21053   sqlite3_free(p);
21054 }
21055 
21056 /*
21057 ** Change the size of an existing memory allocation
21058 */
21059 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
21060   int nOld, nNew, nDiff;
21061   void *pNew;
21062   assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
21063   assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
21064   if( pOld==0 ){
21065     return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
21066   }
21067   if( nBytes==0 ){
21068     sqlite3_free(pOld); /* IMP: R-26507-47431 */
21069     return 0;
21070   }
21071   if( nBytes>=0x7fffff00 ){
21072     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
21073     return 0;
21074   }
21075   nOld = sqlite3MallocSize(pOld);
21076   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
21077   ** argument to xRealloc is always a value returned by a prior call to
21078   ** xRoundup. */
21079   nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
21080   if( nOld==nNew ){
21081     pNew = pOld;
21082   }else if( sqlite3GlobalConfig.bMemstat ){
21083     sqlite3_mutex_enter(mem0.mutex);
21084     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
21085     nDiff = nNew - nOld;
21086     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
21087           mem0.alarmThreshold-nDiff ){
21088       sqlite3MallocAlarm(nDiff);
21089     }
21090     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
21091     if( pNew==0 && mem0.alarmCallback ){
21092       sqlite3MallocAlarm((int)nBytes);
21093       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
21094     }
21095     if( pNew ){
21096       nNew = sqlite3MallocSize(pNew);
21097       sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
21098     }
21099     sqlite3_mutex_leave(mem0.mutex);
21100   }else{
21101     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
21102   }
21103   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
21104   return pNew;
21105 }
21106 
21107 /*
21108 ** The public interface to sqlite3Realloc.  Make sure that the memory
21109 ** subsystem is initialized prior to invoking sqliteRealloc.
21110 */
21111 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void *pOld, int n){
21112 #ifndef SQLITE_OMIT_AUTOINIT
21113   if( sqlite3_initialize() ) return 0;
21114 #endif
21115   if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
21116   return sqlite3Realloc(pOld, n);
21117 }
21118 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
21119 #ifndef SQLITE_OMIT_AUTOINIT
21120   if( sqlite3_initialize() ) return 0;
21121 #endif
21122   return sqlite3Realloc(pOld, n);
21123 }
21124 
21125 
21126 /*
21127 ** Allocate and zero memory.
21128 */
21129 SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
21130   void *p = sqlite3Malloc(n);
21131   if( p ){
21132     memset(p, 0, (size_t)n);
21133   }
21134   return p;
21135 }
21136 
21137 /*
21138 ** Allocate and zero memory.  If the allocation fails, make
21139 ** the mallocFailed flag in the connection pointer.
21140 */
21141 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
21142   void *p = sqlite3DbMallocRaw(db, n);
21143   if( p ){
21144     memset(p, 0, (size_t)n);
21145   }
21146   return p;
21147 }
21148 
21149 /*
21150 ** Allocate and zero memory.  If the allocation fails, make
21151 ** the mallocFailed flag in the connection pointer.
21152 **
21153 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
21154 ** failure on the same database connection) then always return 0.
21155 ** Hence for a particular database connection, once malloc starts
21156 ** failing, it fails consistently until mallocFailed is reset.
21157 ** This is an important assumption.  There are many places in the
21158 ** code that do things like this:
21159 **
21160 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
21161 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
21162 **         if( b ) a[10] = 9;
21163 **
21164 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
21165 ** that all prior mallocs (ex: "a") worked too.
21166 */
21167 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
21168   void *p;
21169   assert( db==0 || sqlite3_mutex_held(db->mutex) );
21170   assert( db==0 || db->pnBytesFreed==0 );
21171 #ifndef SQLITE_OMIT_LOOKASIDE
21172   if( db ){
21173     LookasideSlot *pBuf;
21174     if( db->mallocFailed ){
21175       return 0;
21176     }
21177     if( db->lookaside.bEnabled ){
21178       if( n>db->lookaside.sz ){
21179         db->lookaside.anStat[1]++;
21180       }else if( (pBuf = db->lookaside.pFree)==0 ){
21181         db->lookaside.anStat[2]++;
21182       }else{
21183         db->lookaside.pFree = pBuf->pNext;
21184         db->lookaside.nOut++;
21185         db->lookaside.anStat[0]++;
21186         if( db->lookaside.nOut>db->lookaside.mxOut ){
21187           db->lookaside.mxOut = db->lookaside.nOut;
21188         }
21189         return (void*)pBuf;
21190       }
21191     }
21192   }
21193 #else
21194   if( db && db->mallocFailed ){
21195     return 0;
21196   }
21197 #endif
21198   p = sqlite3Malloc(n);
21199   if( !p && db ){
21200     db->mallocFailed = 1;
21201   }
21202   sqlite3MemdebugSetType(p,
21203          (db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
21204   return p;
21205 }
21206 
21207 /*
21208 ** Resize the block of memory pointed to by p to n bytes. If the
21209 ** resize fails, set the mallocFailed flag in the connection object.
21210 */
21211 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
21212   void *pNew = 0;
21213   assert( db!=0 );
21214   assert( sqlite3_mutex_held(db->mutex) );
21215   if( db->mallocFailed==0 ){
21216     if( p==0 ){
21217       return sqlite3DbMallocRaw(db, n);
21218     }
21219     if( isLookaside(db, p) ){
21220       if( n<=db->lookaside.sz ){
21221         return p;
21222       }
21223       pNew = sqlite3DbMallocRaw(db, n);
21224       if( pNew ){
21225         memcpy(pNew, p, db->lookaside.sz);
21226         sqlite3DbFree(db, p);
21227       }
21228     }else{
21229       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
21230       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
21231       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
21232       pNew = sqlite3_realloc64(p, n);
21233       if( !pNew ){
21234         db->mallocFailed = 1;
21235       }
21236       sqlite3MemdebugSetType(pNew,
21237             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
21238     }
21239   }
21240   return pNew;
21241 }
21242 
21243 /*
21244 ** Attempt to reallocate p.  If the reallocation fails, then free p
21245 ** and set the mallocFailed flag in the database connection.
21246 */
21247 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
21248   void *pNew;
21249   pNew = sqlite3DbRealloc(db, p, n);
21250   if( !pNew ){
21251     sqlite3DbFree(db, p);
21252   }
21253   return pNew;
21254 }
21255 
21256 /*
21257 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
21258 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
21259 ** is because when memory debugging is turned on, these two functions are
21260 ** called via macros that record the current file and line number in the
21261 ** ThreadData structure.
21262 */
21263 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
21264   char *zNew;
21265   size_t n;
21266   if( z==0 ){
21267     return 0;
21268   }
21269   n = sqlite3Strlen30(z) + 1;
21270   assert( (n&0x7fffffff)==n );
21271   zNew = sqlite3DbMallocRaw(db, (int)n);
21272   if( zNew ){
21273     memcpy(zNew, z, n);
21274   }
21275   return zNew;
21276 }
21277 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
21278   char *zNew;
21279   if( z==0 ){
21280     return 0;
21281   }
21282   assert( (n&0x7fffffff)==n );
21283   zNew = sqlite3DbMallocRaw(db, n+1);
21284   if( zNew ){
21285     memcpy(zNew, z, (size_t)n);
21286     zNew[n] = 0;
21287   }
21288   return zNew;
21289 }
21290 
21291 /*
21292 ** Create a string from the zFromat argument and the va_list that follows.
21293 ** Store the string in memory obtained from sqliteMalloc() and make *pz
21294 ** point to that string.
21295 */
21296 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
21297   va_list ap;
21298   char *z;
21299 
21300   va_start(ap, zFormat);
21301   z = sqlite3VMPrintf(db, zFormat, ap);
21302   va_end(ap);
21303   sqlite3DbFree(db, *pz);
21304   *pz = z;
21305 }
21306 
21307 /*
21308 ** Take actions at the end of an API call to indicate an OOM error
21309 */
21310 static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
21311   db->mallocFailed = 0;
21312   sqlite3Error(db, SQLITE_NOMEM);
21313   return SQLITE_NOMEM;
21314 }
21315 
21316 /*
21317 ** This function must be called before exiting any API function (i.e.
21318 ** returning control to the user) that has called sqlite3_malloc or
21319 ** sqlite3_realloc.
21320 **
21321 ** The returned value is normally a copy of the second argument to this
21322 ** function. However, if a malloc() failure has occurred since the previous
21323 ** invocation SQLITE_NOMEM is returned instead.
21324 **
21325 ** If the first argument, db, is not NULL and a malloc() error has occurred,
21326 ** then the connection error-code (the value returned by sqlite3_errcode())
21327 ** is set to SQLITE_NOMEM.
21328 */
21329 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
21330   /* If the db handle is not NULL, then we must hold the connection handle
21331   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
21332   ** is unsafe, as is the call to sqlite3Error().
21333   */
21334   assert( !db || sqlite3_mutex_held(db->mutex) );
21335   if( db==0 ) return rc & 0xff;
21336   if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
21337     return apiOomError(db);
21338   }
21339   return rc & db->errMask;
21340 }
21341 
21342 /************** End of malloc.c **********************************************/
21343 /************** Begin file printf.c ******************************************/
21344 /*
21345 ** The "printf" code that follows dates from the 1980's.  It is in
21346 ** the public domain.  The original comments are included here for
21347 ** completeness.  They are very out-of-date but might be useful as
21348 ** an historical reference.  Most of the "enhancements" have been backed
21349 ** out so that the functionality is now the same as standard printf().
21350 **
21351 **************************************************************************
21352 **
21353 ** This file contains code for a set of "printf"-like routines.  These
21354 ** routines format strings much like the printf() from the standard C
21355 ** library, though the implementation here has enhancements to support
21356 ** SQLlite.
21357 */
21358 
21359 /*
21360 ** Conversion types fall into various categories as defined by the
21361 ** following enumeration.
21362 */
21363 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
21364 #define etFLOAT       2 /* Floating point.  %f */
21365 #define etEXP         3 /* Exponentional notation. %e and %E */
21366 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
21367 #define etSIZE        5 /* Return number of characters processed so far. %n */
21368 #define etSTRING      6 /* Strings. %s */
21369 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
21370 #define etPERCENT     8 /* Percent symbol. %% */
21371 #define etCHARX       9 /* Characters. %c */
21372 /* The rest are extensions, not normally found in printf() */
21373 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
21374 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
21375                           NULL pointers replaced by SQL NULL.  %Q */
21376 #define etTOKEN      12 /* a pointer to a Token structure */
21377 #define etSRCLIST    13 /* a pointer to a SrcList */
21378 #define etPOINTER    14 /* The %p conversion */
21379 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
21380 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
21381 
21382 #define etINVALID     0 /* Any unrecognized conversion type */
21383 
21384 
21385 /*
21386 ** An "etByte" is an 8-bit unsigned value.
21387 */
21388 typedef unsigned char etByte;
21389 
21390 /*
21391 ** Each builtin conversion character (ex: the 'd' in "%d") is described
21392 ** by an instance of the following structure
21393 */
21394 typedef struct et_info {   /* Information about each format field */
21395   char fmttype;            /* The format field code letter */
21396   etByte base;             /* The base for radix conversion */
21397   etByte flags;            /* One or more of FLAG_ constants below */
21398   etByte type;             /* Conversion paradigm */
21399   etByte charset;          /* Offset into aDigits[] of the digits string */
21400   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
21401 } et_info;
21402 
21403 /*
21404 ** Allowed values for et_info.flags
21405 */
21406 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
21407 #define FLAG_INTERN  2     /* True if for internal use only */
21408 #define FLAG_STRING  4     /* Allow infinity precision */
21409 
21410 
21411 /*
21412 ** The following table is searched linearly, so it is good to put the
21413 ** most frequently used conversion types first.
21414 */
21415 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
21416 static const char aPrefix[] = "-x0\000X0";
21417 static const et_info fmtinfo[] = {
21418   {  'd', 10, 1, etRADIX,      0,  0 },
21419   {  's',  0, 4, etSTRING,     0,  0 },
21420   {  'g',  0, 1, etGENERIC,    30, 0 },
21421   {  'z',  0, 4, etDYNSTRING,  0,  0 },
21422   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
21423   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
21424   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
21425   {  'c',  0, 0, etCHARX,      0,  0 },
21426   {  'o',  8, 0, etRADIX,      0,  2 },
21427   {  'u', 10, 0, etRADIX,      0,  0 },
21428   {  'x', 16, 0, etRADIX,      16, 1 },
21429   {  'X', 16, 0, etRADIX,      0,  4 },
21430 #ifndef SQLITE_OMIT_FLOATING_POINT
21431   {  'f',  0, 1, etFLOAT,      0,  0 },
21432   {  'e',  0, 1, etEXP,        30, 0 },
21433   {  'E',  0, 1, etEXP,        14, 0 },
21434   {  'G',  0, 1, etGENERIC,    14, 0 },
21435 #endif
21436   {  'i', 10, 1, etRADIX,      0,  0 },
21437   {  'n',  0, 0, etSIZE,       0,  0 },
21438   {  '%',  0, 0, etPERCENT,    0,  0 },
21439   {  'p', 16, 0, etPOINTER,    0,  1 },
21440 
21441 /* All the rest have the FLAG_INTERN bit set and are thus for internal
21442 ** use only */
21443   {  'T',  0, 2, etTOKEN,      0,  0 },
21444   {  'S',  0, 2, etSRCLIST,    0,  0 },
21445   {  'r', 10, 3, etORDINAL,    0,  0 },
21446 };
21447 
21448 /*
21449 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
21450 ** conversions will work.
21451 */
21452 #ifndef SQLITE_OMIT_FLOATING_POINT
21453 /*
21454 ** "*val" is a double such that 0.1 <= *val < 10.0
21455 ** Return the ascii code for the leading digit of *val, then
21456 ** multiply "*val" by 10.0 to renormalize.
21457 **
21458 ** Example:
21459 **     input:     *val = 3.14159
21460 **     output:    *val = 1.4159    function return = '3'
21461 **
21462 ** The counter *cnt is incremented each time.  After counter exceeds
21463 ** 16 (the number of significant digits in a 64-bit float) '0' is
21464 ** always returned.
21465 */
21466 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
21467   int digit;
21468   LONGDOUBLE_TYPE d;
21469   if( (*cnt)<=0 ) return '0';
21470   (*cnt)--;
21471   digit = (int)*val;
21472   d = digit;
21473   digit += '0';
21474   *val = (*val - d)*10.0;
21475   return (char)digit;
21476 }
21477 #endif /* SQLITE_OMIT_FLOATING_POINT */
21478 
21479 /*
21480 ** Set the StrAccum object to an error mode.
21481 */
21482 static void setStrAccumError(StrAccum *p, u8 eError){
21483   assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
21484   p->accError = eError;
21485   p->nAlloc = 0;
21486 }
21487 
21488 /*
21489 ** Extra argument values from a PrintfArguments object
21490 */
21491 static sqlite3_int64 getIntArg(PrintfArguments *p){
21492   if( p->nArg<=p->nUsed ) return 0;
21493   return sqlite3_value_int64(p->apArg[p->nUsed++]);
21494 }
21495 static double getDoubleArg(PrintfArguments *p){
21496   if( p->nArg<=p->nUsed ) return 0.0;
21497   return sqlite3_value_double(p->apArg[p->nUsed++]);
21498 }
21499 static char *getTextArg(PrintfArguments *p){
21500   if( p->nArg<=p->nUsed ) return 0;
21501   return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
21502 }
21503 
21504 
21505 /*
21506 ** On machines with a small stack size, you can redefine the
21507 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
21508 */
21509 #ifndef SQLITE_PRINT_BUF_SIZE
21510 # define SQLITE_PRINT_BUF_SIZE 70
21511 #endif
21512 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
21513 
21514 /*
21515 ** Render a string given by "fmt" into the StrAccum object.
21516 */
21517 SQLITE_PRIVATE void sqlite3VXPrintf(
21518   StrAccum *pAccum,          /* Accumulate results here */
21519   u32 bFlags,                /* SQLITE_PRINTF_* flags */
21520   const char *fmt,           /* Format string */
21521   va_list ap                 /* arguments */
21522 ){
21523   int c;                     /* Next character in the format string */
21524   char *bufpt;               /* Pointer to the conversion buffer */
21525   int precision;             /* Precision of the current field */
21526   int length;                /* Length of the field */
21527   int idx;                   /* A general purpose loop counter */
21528   int width;                 /* Width of the current field */
21529   etByte flag_leftjustify;   /* True if "-" flag is present */
21530   etByte flag_plussign;      /* True if "+" flag is present */
21531   etByte flag_blanksign;     /* True if " " flag is present */
21532   etByte flag_alternateform; /* True if "#" flag is present */
21533   etByte flag_altform2;      /* True if "!" flag is present */
21534   etByte flag_zeropad;       /* True if field width constant starts with zero */
21535   etByte flag_long;          /* True if "l" flag is present */
21536   etByte flag_longlong;      /* True if the "ll" flag is present */
21537   etByte done;               /* Loop termination flag */
21538   etByte xtype = 0;          /* Conversion paradigm */
21539   u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
21540   u8 useIntern;              /* Ok to use internal conversions (ex: %T) */
21541   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
21542   sqlite_uint64 longvalue;   /* Value for integer types */
21543   LONGDOUBLE_TYPE realvalue; /* Value for real types */
21544   const et_info *infop;      /* Pointer to the appropriate info structure */
21545   char *zOut;                /* Rendering buffer */
21546   int nOut;                  /* Size of the rendering buffer */
21547   char *zExtra = 0;          /* Malloced memory used by some conversion */
21548 #ifndef SQLITE_OMIT_FLOATING_POINT
21549   int  exp, e2;              /* exponent of real numbers */
21550   int nsd;                   /* Number of significant digits returned */
21551   double rounder;            /* Used for rounding floating point values */
21552   etByte flag_dp;            /* True if decimal point should be shown */
21553   etByte flag_rtz;           /* True if trailing zeros should be removed */
21554 #endif
21555   PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
21556   char buf[etBUFSIZE];       /* Conversion buffer */
21557 
21558   bufpt = 0;
21559   if( bFlags ){
21560     if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
21561       pArgList = va_arg(ap, PrintfArguments*);
21562     }
21563     useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
21564   }else{
21565     bArgList = useIntern = 0;
21566   }
21567   for(; (c=(*fmt))!=0; ++fmt){
21568     if( c!='%' ){
21569       bufpt = (char *)fmt;
21570 #if HAVE_STRCHRNUL
21571       fmt = strchrnul(fmt, '%');
21572 #else
21573       do{ fmt++; }while( *fmt && *fmt != '%' );
21574 #endif
21575       sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
21576       if( *fmt==0 ) break;
21577     }
21578     if( (c=(*++fmt))==0 ){
21579       sqlite3StrAccumAppend(pAccum, "%", 1);
21580       break;
21581     }
21582     /* Find out what flags are present */
21583     flag_leftjustify = flag_plussign = flag_blanksign =
21584      flag_alternateform = flag_altform2 = flag_zeropad = 0;
21585     done = 0;
21586     do{
21587       switch( c ){
21588         case '-':   flag_leftjustify = 1;     break;
21589         case '+':   flag_plussign = 1;        break;
21590         case ' ':   flag_blanksign = 1;       break;
21591         case '#':   flag_alternateform = 1;   break;
21592         case '!':   flag_altform2 = 1;        break;
21593         case '0':   flag_zeropad = 1;         break;
21594         default:    done = 1;                 break;
21595       }
21596     }while( !done && (c=(*++fmt))!=0 );
21597     /* Get the field width */
21598     if( c=='*' ){
21599       if( bArgList ){
21600         width = (int)getIntArg(pArgList);
21601       }else{
21602         width = va_arg(ap,int);
21603       }
21604       if( width<0 ){
21605         flag_leftjustify = 1;
21606         width = width >= -2147483647 ? -width : 0;
21607       }
21608       c = *++fmt;
21609     }else{
21610       unsigned wx = 0;
21611       while( c>='0' && c<='9' ){
21612         wx = wx*10 + c - '0';
21613         c = *++fmt;
21614       }
21615       testcase( wx>0x7fffffff );
21616       width = wx & 0x7fffffff;
21617     }
21618 
21619     /* Get the precision */
21620     if( c=='.' ){
21621       c = *++fmt;
21622       if( c=='*' ){
21623         if( bArgList ){
21624           precision = (int)getIntArg(pArgList);
21625         }else{
21626           precision = va_arg(ap,int);
21627         }
21628         c = *++fmt;
21629         if( precision<0 ){
21630           precision = precision >= -2147483647 ? -precision : -1;
21631         }
21632       }else{
21633         unsigned px = 0;
21634         while( c>='0' && c<='9' ){
21635           px = px*10 + c - '0';
21636           c = *++fmt;
21637         }
21638         testcase( px>0x7fffffff );
21639         precision = px & 0x7fffffff;
21640       }
21641     }else{
21642       precision = -1;
21643     }
21644     /* Get the conversion type modifier */
21645     if( c=='l' ){
21646       flag_long = 1;
21647       c = *++fmt;
21648       if( c=='l' ){
21649         flag_longlong = 1;
21650         c = *++fmt;
21651       }else{
21652         flag_longlong = 0;
21653       }
21654     }else{
21655       flag_long = flag_longlong = 0;
21656     }
21657     /* Fetch the info entry for the field */
21658     infop = &fmtinfo[0];
21659     xtype = etINVALID;
21660     for(idx=0; idx<ArraySize(fmtinfo); idx++){
21661       if( c==fmtinfo[idx].fmttype ){
21662         infop = &fmtinfo[idx];
21663         if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
21664           xtype = infop->type;
21665         }else{
21666           return;
21667         }
21668         break;
21669       }
21670     }
21671 
21672     /*
21673     ** At this point, variables are initialized as follows:
21674     **
21675     **   flag_alternateform          TRUE if a '#' is present.
21676     **   flag_altform2               TRUE if a '!' is present.
21677     **   flag_plussign               TRUE if a '+' is present.
21678     **   flag_leftjustify            TRUE if a '-' is present or if the
21679     **                               field width was negative.
21680     **   flag_zeropad                TRUE if the width began with 0.
21681     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
21682     **                               the conversion character.
21683     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
21684     **                               the conversion character.
21685     **   flag_blanksign              TRUE if a ' ' is present.
21686     **   width                       The specified field width.  This is
21687     **                               always non-negative.  Zero is the default.
21688     **   precision                   The specified precision.  The default
21689     **                               is -1.
21690     **   xtype                       The class of the conversion.
21691     **   infop                       Pointer to the appropriate info struct.
21692     */
21693     switch( xtype ){
21694       case etPOINTER:
21695         flag_longlong = sizeof(char*)==sizeof(i64);
21696         flag_long = sizeof(char*)==sizeof(long int);
21697         /* Fall through into the next case */
21698       case etORDINAL:
21699       case etRADIX:
21700         if( infop->flags & FLAG_SIGNED ){
21701           i64 v;
21702           if( bArgList ){
21703             v = getIntArg(pArgList);
21704           }else if( flag_longlong ){
21705             v = va_arg(ap,i64);
21706           }else if( flag_long ){
21707             v = va_arg(ap,long int);
21708           }else{
21709             v = va_arg(ap,int);
21710           }
21711           if( v<0 ){
21712             if( v==SMALLEST_INT64 ){
21713               longvalue = ((u64)1)<<63;
21714             }else{
21715               longvalue = -v;
21716             }
21717             prefix = '-';
21718           }else{
21719             longvalue = v;
21720             if( flag_plussign )        prefix = '+';
21721             else if( flag_blanksign )  prefix = ' ';
21722             else                       prefix = 0;
21723           }
21724         }else{
21725           if( bArgList ){
21726             longvalue = (u64)getIntArg(pArgList);
21727           }else if( flag_longlong ){
21728             longvalue = va_arg(ap,u64);
21729           }else if( flag_long ){
21730             longvalue = va_arg(ap,unsigned long int);
21731           }else{
21732             longvalue = va_arg(ap,unsigned int);
21733           }
21734           prefix = 0;
21735         }
21736         if( longvalue==0 ) flag_alternateform = 0;
21737         if( flag_zeropad && precision<width-(prefix!=0) ){
21738           precision = width-(prefix!=0);
21739         }
21740         if( precision<etBUFSIZE-10 ){
21741           nOut = etBUFSIZE;
21742           zOut = buf;
21743         }else{
21744           nOut = precision + 10;
21745           zOut = zExtra = sqlite3Malloc( nOut );
21746           if( zOut==0 ){
21747             setStrAccumError(pAccum, STRACCUM_NOMEM);
21748             return;
21749           }
21750         }
21751         bufpt = &zOut[nOut-1];
21752         if( xtype==etORDINAL ){
21753           static const char zOrd[] = "thstndrd";
21754           int x = (int)(longvalue % 10);
21755           if( x>=4 || (longvalue/10)%10==1 ){
21756             x = 0;
21757           }
21758           *(--bufpt) = zOrd[x*2+1];
21759           *(--bufpt) = zOrd[x*2];
21760         }
21761         {
21762           const char *cset = &aDigits[infop->charset];
21763           u8 base = infop->base;
21764           do{                                           /* Convert to ascii */
21765             *(--bufpt) = cset[longvalue%base];
21766             longvalue = longvalue/base;
21767           }while( longvalue>0 );
21768         }
21769         length = (int)(&zOut[nOut-1]-bufpt);
21770         for(idx=precision-length; idx>0; idx--){
21771           *(--bufpt) = '0';                             /* Zero pad */
21772         }
21773         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
21774         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
21775           const char *pre;
21776           char x;
21777           pre = &aPrefix[infop->prefix];
21778           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
21779         }
21780         length = (int)(&zOut[nOut-1]-bufpt);
21781         break;
21782       case etFLOAT:
21783       case etEXP:
21784       case etGENERIC:
21785         if( bArgList ){
21786           realvalue = getDoubleArg(pArgList);
21787         }else{
21788           realvalue = va_arg(ap,double);
21789         }
21790 #ifdef SQLITE_OMIT_FLOATING_POINT
21791         length = 0;
21792 #else
21793         if( precision<0 ) precision = 6;         /* Set default precision */
21794         if( realvalue<0.0 ){
21795           realvalue = -realvalue;
21796           prefix = '-';
21797         }else{
21798           if( flag_plussign )          prefix = '+';
21799           else if( flag_blanksign )    prefix = ' ';
21800           else                         prefix = 0;
21801         }
21802         if( xtype==etGENERIC && precision>0 ) precision--;
21803         testcase( precision>0xfff );
21804         for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
21805         if( xtype==etFLOAT ) realvalue += rounder;
21806         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
21807         exp = 0;
21808         if( sqlite3IsNaN((double)realvalue) ){
21809           bufpt = "NaN";
21810           length = 3;
21811           break;
21812         }
21813         if( realvalue>0.0 ){
21814           LONGDOUBLE_TYPE scale = 1.0;
21815           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
21816           while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
21817           while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
21818           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
21819           realvalue /= scale;
21820           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
21821           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
21822           if( exp>350 ){
21823             if( prefix=='-' ){
21824               bufpt = "-Inf";
21825             }else if( prefix=='+' ){
21826               bufpt = "+Inf";
21827             }else{
21828               bufpt = "Inf";
21829             }
21830             length = sqlite3Strlen30(bufpt);
21831             break;
21832           }
21833         }
21834         bufpt = buf;
21835         /*
21836         ** If the field type is etGENERIC, then convert to either etEXP
21837         ** or etFLOAT, as appropriate.
21838         */
21839         if( xtype!=etFLOAT ){
21840           realvalue += rounder;
21841           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
21842         }
21843         if( xtype==etGENERIC ){
21844           flag_rtz = !flag_alternateform;
21845           if( exp<-4 || exp>precision ){
21846             xtype = etEXP;
21847           }else{
21848             precision = precision - exp;
21849             xtype = etFLOAT;
21850           }
21851         }else{
21852           flag_rtz = flag_altform2;
21853         }
21854         if( xtype==etEXP ){
21855           e2 = 0;
21856         }else{
21857           e2 = exp;
21858         }
21859         if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
21860           bufpt = zExtra
21861               = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
21862           if( bufpt==0 ){
21863             setStrAccumError(pAccum, STRACCUM_NOMEM);
21864             return;
21865           }
21866         }
21867         zOut = bufpt;
21868         nsd = 16 + flag_altform2*10;
21869         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
21870         /* The sign in front of the number */
21871         if( prefix ){
21872           *(bufpt++) = prefix;
21873         }
21874         /* Digits prior to the decimal point */
21875         if( e2<0 ){
21876           *(bufpt++) = '0';
21877         }else{
21878           for(; e2>=0; e2--){
21879             *(bufpt++) = et_getdigit(&realvalue,&nsd);
21880           }
21881         }
21882         /* The decimal point */
21883         if( flag_dp ){
21884           *(bufpt++) = '.';
21885         }
21886         /* "0" digits after the decimal point but before the first
21887         ** significant digit of the number */
21888         for(e2++; e2<0; precision--, e2++){
21889           assert( precision>0 );
21890           *(bufpt++) = '0';
21891         }
21892         /* Significant digits after the decimal point */
21893         while( (precision--)>0 ){
21894           *(bufpt++) = et_getdigit(&realvalue,&nsd);
21895         }
21896         /* Remove trailing zeros and the "." if no digits follow the "." */
21897         if( flag_rtz && flag_dp ){
21898           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
21899           assert( bufpt>zOut );
21900           if( bufpt[-1]=='.' ){
21901             if( flag_altform2 ){
21902               *(bufpt++) = '0';
21903             }else{
21904               *(--bufpt) = 0;
21905             }
21906           }
21907         }
21908         /* Add the "eNNN" suffix */
21909         if( xtype==etEXP ){
21910           *(bufpt++) = aDigits[infop->charset];
21911           if( exp<0 ){
21912             *(bufpt++) = '-'; exp = -exp;
21913           }else{
21914             *(bufpt++) = '+';
21915           }
21916           if( exp>=100 ){
21917             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
21918             exp %= 100;
21919           }
21920           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
21921           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
21922         }
21923         *bufpt = 0;
21924 
21925         /* The converted number is in buf[] and zero terminated. Output it.
21926         ** Note that the number is in the usual order, not reversed as with
21927         ** integer conversions. */
21928         length = (int)(bufpt-zOut);
21929         bufpt = zOut;
21930 
21931         /* Special case:  Add leading zeros if the flag_zeropad flag is
21932         ** set and we are not left justified */
21933         if( flag_zeropad && !flag_leftjustify && length < width){
21934           int i;
21935           int nPad = width - length;
21936           for(i=width; i>=nPad; i--){
21937             bufpt[i] = bufpt[i-nPad];
21938           }
21939           i = prefix!=0;
21940           while( nPad-- ) bufpt[i++] = '0';
21941           length = width;
21942         }
21943 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
21944         break;
21945       case etSIZE:
21946         if( !bArgList ){
21947           *(va_arg(ap,int*)) = pAccum->nChar;
21948         }
21949         length = width = 0;
21950         break;
21951       case etPERCENT:
21952         buf[0] = '%';
21953         bufpt = buf;
21954         length = 1;
21955         break;
21956       case etCHARX:
21957         if( bArgList ){
21958           bufpt = getTextArg(pArgList);
21959           c = bufpt ? bufpt[0] : 0;
21960         }else{
21961           c = va_arg(ap,int);
21962         }
21963         if( precision>1 ){
21964           width -= precision-1;
21965           if( width>1 && !flag_leftjustify ){
21966             sqlite3AppendChar(pAccum, width-1, ' ');
21967             width = 0;
21968           }
21969           sqlite3AppendChar(pAccum, precision-1, c);
21970         }
21971         length = 1;
21972         buf[0] = c;
21973         bufpt = buf;
21974         break;
21975       case etSTRING:
21976       case etDYNSTRING:
21977         if( bArgList ){
21978           bufpt = getTextArg(pArgList);
21979         }else{
21980           bufpt = va_arg(ap,char*);
21981         }
21982         if( bufpt==0 ){
21983           bufpt = "";
21984         }else if( xtype==etDYNSTRING && !bArgList ){
21985           zExtra = bufpt;
21986         }
21987         if( precision>=0 ){
21988           for(length=0; length<precision && bufpt[length]; length++){}
21989         }else{
21990           length = sqlite3Strlen30(bufpt);
21991         }
21992         break;
21993       case etSQLESCAPE:
21994       case etSQLESCAPE2:
21995       case etSQLESCAPE3: {
21996         int i, j, k, n, isnull;
21997         int needQuote;
21998         char ch;
21999         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
22000         char *escarg;
22001 
22002         if( bArgList ){
22003           escarg = getTextArg(pArgList);
22004         }else{
22005           escarg = va_arg(ap,char*);
22006         }
22007         isnull = escarg==0;
22008         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
22009         k = precision;
22010         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
22011           if( ch==q )  n++;
22012         }
22013         needQuote = !isnull && xtype==etSQLESCAPE2;
22014         n += i + 1 + needQuote*2;
22015         if( n>etBUFSIZE ){
22016           bufpt = zExtra = sqlite3Malloc( n );
22017           if( bufpt==0 ){
22018             setStrAccumError(pAccum, STRACCUM_NOMEM);
22019             return;
22020           }
22021         }else{
22022           bufpt = buf;
22023         }
22024         j = 0;
22025         if( needQuote ) bufpt[j++] = q;
22026         k = i;
22027         for(i=0; i<k; i++){
22028           bufpt[j++] = ch = escarg[i];
22029           if( ch==q ) bufpt[j++] = ch;
22030         }
22031         if( needQuote ) bufpt[j++] = q;
22032         bufpt[j] = 0;
22033         length = j;
22034         /* The precision in %q and %Q means how many input characters to
22035         ** consume, not the length of the output...
22036         ** if( precision>=0 && precision<length ) length = precision; */
22037         break;
22038       }
22039       case etTOKEN: {
22040         Token *pToken = va_arg(ap, Token*);
22041         assert( bArgList==0 );
22042         if( pToken && pToken->n ){
22043           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
22044         }
22045         length = width = 0;
22046         break;
22047       }
22048       case etSRCLIST: {
22049         SrcList *pSrc = va_arg(ap, SrcList*);
22050         int k = va_arg(ap, int);
22051         struct SrcList_item *pItem = &pSrc->a[k];
22052         assert( bArgList==0 );
22053         assert( k>=0 && k<pSrc->nSrc );
22054         if( pItem->zDatabase ){
22055           sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
22056           sqlite3StrAccumAppend(pAccum, ".", 1);
22057         }
22058         sqlite3StrAccumAppendAll(pAccum, pItem->zName);
22059         length = width = 0;
22060         break;
22061       }
22062       default: {
22063         assert( xtype==etINVALID );
22064         return;
22065       }
22066     }/* End switch over the format type */
22067     /*
22068     ** The text of the conversion is pointed to by "bufpt" and is
22069     ** "length" characters long.  The field width is "width".  Do
22070     ** the output.
22071     */
22072     width -= length;
22073     if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
22074     sqlite3StrAccumAppend(pAccum, bufpt, length);
22075     if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
22076 
22077     if( zExtra ){
22078       sqlite3_free(zExtra);
22079       zExtra = 0;
22080     }
22081   }/* End for loop over the format string */
22082 } /* End of function */
22083 
22084 /*
22085 ** Enlarge the memory allocation on a StrAccum object so that it is
22086 ** able to accept at least N more bytes of text.
22087 **
22088 ** Return the number of bytes of text that StrAccum is able to accept
22089 ** after the attempted enlargement.  The value returned might be zero.
22090 */
22091 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
22092   char *zNew;
22093   assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
22094   if( p->accError ){
22095     testcase(p->accError==STRACCUM_TOOBIG);
22096     testcase(p->accError==STRACCUM_NOMEM);
22097     return 0;
22098   }
22099   if( p->mxAlloc==0 ){
22100     N = p->nAlloc - p->nChar - 1;
22101     setStrAccumError(p, STRACCUM_TOOBIG);
22102     return N;
22103   }else{
22104     char *zOld = (p->zText==p->zBase ? 0 : p->zText);
22105     i64 szNew = p->nChar;
22106     szNew += N + 1;
22107     if( szNew+p->nChar<=p->mxAlloc ){
22108       /* Force exponential buffer size growth as long as it does not overflow,
22109       ** to avoid having to call this routine too often */
22110       szNew += p->nChar;
22111     }
22112     if( szNew > p->mxAlloc ){
22113       sqlite3StrAccumReset(p);
22114       setStrAccumError(p, STRACCUM_TOOBIG);
22115       return 0;
22116     }else{
22117       p->nAlloc = (int)szNew;
22118     }
22119     if( p->db ){
22120       zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
22121     }else{
22122       zNew = sqlite3_realloc64(zOld, p->nAlloc);
22123     }
22124     if( zNew ){
22125       assert( p->zText!=0 || p->nChar==0 );
22126       if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
22127       p->zText = zNew;
22128       p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
22129     }else{
22130       sqlite3StrAccumReset(p);
22131       setStrAccumError(p, STRACCUM_NOMEM);
22132       return 0;
22133     }
22134   }
22135   return N;
22136 }
22137 
22138 /*
22139 ** Append N copies of character c to the given string buffer.
22140 */
22141 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
22142   testcase( p->nChar + (i64)N > 0x7fffffff );
22143   if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
22144     return;
22145   }
22146   while( (N--)>0 ) p->zText[p->nChar++] = c;
22147 }
22148 
22149 /*
22150 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
22151 ** So enlarge if first, then do the append.
22152 **
22153 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
22154 ** work (enlarging the buffer) using tail recursion, so that the
22155 ** sqlite3StrAccumAppend() routine can use fast calling semantics.
22156 */
22157 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
22158   N = sqlite3StrAccumEnlarge(p, N);
22159   if( N>0 ){
22160     memcpy(&p->zText[p->nChar], z, N);
22161     p->nChar += N;
22162   }
22163 }
22164 
22165 /*
22166 ** Append N bytes of text from z to the StrAccum object.  Increase the
22167 ** size of the memory allocation for StrAccum if necessary.
22168 */
22169 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
22170   assert( z!=0 || N==0 );
22171   assert( p->zText!=0 || p->nChar==0 || p->accError );
22172   assert( N>=0 );
22173   assert( p->accError==0 || p->nAlloc==0 );
22174   if( p->nChar+N >= p->nAlloc ){
22175     enlargeAndAppend(p,z,N);
22176   }else{
22177     assert( p->zText );
22178     p->nChar += N;
22179     memcpy(&p->zText[p->nChar-N], z, N);
22180   }
22181 }
22182 
22183 /*
22184 ** Append the complete text of zero-terminated string z[] to the p string.
22185 */
22186 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
22187   sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
22188 }
22189 
22190 
22191 /*
22192 ** Finish off a string by making sure it is zero-terminated.
22193 ** Return a pointer to the resulting string.  Return a NULL
22194 ** pointer if any kind of error was encountered.
22195 */
22196 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
22197   if( p->zText ){
22198     p->zText[p->nChar] = 0;
22199     if( p->mxAlloc>0 && p->zText==p->zBase ){
22200       p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
22201       if( p->zText ){
22202         memcpy(p->zText, p->zBase, p->nChar+1);
22203       }else{
22204         setStrAccumError(p, STRACCUM_NOMEM);
22205       }
22206     }
22207   }
22208   return p->zText;
22209 }
22210 
22211 /*
22212 ** Reset an StrAccum string.  Reclaim all malloced memory.
22213 */
22214 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
22215   if( p->zText!=p->zBase ){
22216     sqlite3DbFree(p->db, p->zText);
22217   }
22218   p->zText = 0;
22219 }
22220 
22221 /*
22222 ** Initialize a string accumulator.
22223 **
22224 ** p:     The accumulator to be initialized.
22225 ** db:    Pointer to a database connection.  May be NULL.  Lookaside
22226 **        memory is used if not NULL. db->mallocFailed is set appropriately
22227 **        when not NULL.
22228 ** zBase: An initial buffer.  May be NULL in which case the initial buffer
22229 **        is malloced.
22230 ** n:     Size of zBase in bytes.  If total space requirements never exceed
22231 **        n then no memory allocations ever occur.
22232 ** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
22233 **        allocations will ever occur.
22234 */
22235 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
22236   p->zText = p->zBase = zBase;
22237   p->db = db;
22238   p->nChar = 0;
22239   p->nAlloc = n;
22240   p->mxAlloc = mx;
22241   p->accError = 0;
22242 }
22243 
22244 /*
22245 ** Print into memory obtained from sqliteMalloc().  Use the internal
22246 ** %-conversion extensions.
22247 */
22248 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
22249   char *z;
22250   char zBase[SQLITE_PRINT_BUF_SIZE];
22251   StrAccum acc;
22252   assert( db!=0 );
22253   sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
22254                       db->aLimit[SQLITE_LIMIT_LENGTH]);
22255   sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
22256   z = sqlite3StrAccumFinish(&acc);
22257   if( acc.accError==STRACCUM_NOMEM ){
22258     db->mallocFailed = 1;
22259   }
22260   return z;
22261 }
22262 
22263 /*
22264 ** Print into memory obtained from sqliteMalloc().  Use the internal
22265 ** %-conversion extensions.
22266 */
22267 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
22268   va_list ap;
22269   char *z;
22270   va_start(ap, zFormat);
22271   z = sqlite3VMPrintf(db, zFormat, ap);
22272   va_end(ap);
22273   return z;
22274 }
22275 
22276 /*
22277 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
22278 ** the string and before returning.  This routine is intended to be used
22279 ** to modify an existing string.  For example:
22280 **
22281 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
22282 **
22283 */
22284 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
22285   va_list ap;
22286   char *z;
22287   va_start(ap, zFormat);
22288   z = sqlite3VMPrintf(db, zFormat, ap);
22289   va_end(ap);
22290   sqlite3DbFree(db, zStr);
22291   return z;
22292 }
22293 
22294 /*
22295 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
22296 ** %-conversion extensions.
22297 */
22298 SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char *zFormat, va_list ap){
22299   char *z;
22300   char zBase[SQLITE_PRINT_BUF_SIZE];
22301   StrAccum acc;
22302 
22303 #ifdef SQLITE_ENABLE_API_ARMOR
22304   if( zFormat==0 ){
22305     (void)SQLITE_MISUSE_BKPT;
22306     return 0;
22307   }
22308 #endif
22309 #ifndef SQLITE_OMIT_AUTOINIT
22310   if( sqlite3_initialize() ) return 0;
22311 #endif
22312   sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
22313   sqlite3VXPrintf(&acc, 0, zFormat, ap);
22314   z = sqlite3StrAccumFinish(&acc);
22315   return z;
22316 }
22317 
22318 /*
22319 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
22320 ** %-conversion extensions.
22321 */
22322 SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char *zFormat, ...){
22323   va_list ap;
22324   char *z;
22325 #ifndef SQLITE_OMIT_AUTOINIT
22326   if( sqlite3_initialize() ) return 0;
22327 #endif
22328   va_start(ap, zFormat);
22329   z = sqlite3_vmprintf(zFormat, ap);
22330   va_end(ap);
22331   return z;
22332 }
22333 
22334 /*
22335 ** sqlite3_snprintf() works like snprintf() except that it ignores the
22336 ** current locale settings.  This is important for SQLite because we
22337 ** are not able to use a "," as the decimal point in place of "." as
22338 ** specified by some locales.
22339 **
22340 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
22341 ** from the snprintf() standard.  Unfortunately, it is too late to change
22342 ** this without breaking compatibility, so we just have to live with the
22343 ** mistake.
22344 **
22345 ** sqlite3_vsnprintf() is the varargs version.
22346 */
22347 SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
22348   StrAccum acc;
22349   if( n<=0 ) return zBuf;
22350 #ifdef SQLITE_ENABLE_API_ARMOR
22351   if( zBuf==0 || zFormat==0 ) {
22352     (void)SQLITE_MISUSE_BKPT;
22353     if( zBuf ) zBuf[0] = 0;
22354     return zBuf;
22355   }
22356 #endif
22357   sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
22358   sqlite3VXPrintf(&acc, 0, zFormat, ap);
22359   return sqlite3StrAccumFinish(&acc);
22360 }
22361 SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
22362   char *z;
22363   va_list ap;
22364   va_start(ap,zFormat);
22365   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
22366   va_end(ap);
22367   return z;
22368 }
22369 
22370 /*
22371 ** This is the routine that actually formats the sqlite3_log() message.
22372 ** We house it in a separate routine from sqlite3_log() to avoid using
22373 ** stack space on small-stack systems when logging is disabled.
22374 **
22375 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
22376 ** allocate memory because it might be called while the memory allocator
22377 ** mutex is held.
22378 */
22379 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
22380   StrAccum acc;                          /* String accumulator */
22381   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
22382 
22383   sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
22384   sqlite3VXPrintf(&acc, 0, zFormat, ap);
22385   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
22386                            sqlite3StrAccumFinish(&acc));
22387 }
22388 
22389 /*
22390 ** Format and write a message to the log if logging is enabled.
22391 */
22392 SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...){
22393   va_list ap;                             /* Vararg list */
22394   if( sqlite3GlobalConfig.xLog ){
22395     va_start(ap, zFormat);
22396     renderLogMsg(iErrCode, zFormat, ap);
22397     va_end(ap);
22398   }
22399 }
22400 
22401 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
22402 /*
22403 ** A version of printf() that understands %lld.  Used for debugging.
22404 ** The printf() built into some versions of windows does not understand %lld
22405 ** and segfaults if you give it a long long int.
22406 */
22407 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
22408   va_list ap;
22409   StrAccum acc;
22410   char zBuf[500];
22411   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
22412   va_start(ap,zFormat);
22413   sqlite3VXPrintf(&acc, 0, zFormat, ap);
22414   va_end(ap);
22415   sqlite3StrAccumFinish(&acc);
22416   fprintf(stdout,"%s", zBuf);
22417   fflush(stdout);
22418 }
22419 #endif
22420 
22421 #ifdef SQLITE_DEBUG
22422 /*************************************************************************
22423 ** Routines for implementing the "TreeView" display of hierarchical
22424 ** data structures for debugging.
22425 **
22426 ** The main entry points (coded elsewhere) are:
22427 **     sqlite3TreeViewExpr(0, pExpr, 0);
22428 **     sqlite3TreeViewExprList(0, pList, 0, 0);
22429 **     sqlite3TreeViewSelect(0, pSelect, 0);
22430 ** Insert calls to those routines while debugging in order to display
22431 ** a diagram of Expr, ExprList, and Select objects.
22432 **
22433 */
22434 /* Add a new subitem to the tree.  The moreToFollow flag indicates that this
22435 ** is not the last item in the tree. */
22436 SQLITE_PRIVATE TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
22437   if( p==0 ){
22438     p = sqlite3_malloc64( sizeof(*p) );
22439     if( p==0 ) return 0;
22440     memset(p, 0, sizeof(*p));
22441   }else{
22442     p->iLevel++;
22443   }
22444   assert( moreToFollow==0 || moreToFollow==1 );
22445   if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
22446   return p;
22447 }
22448 /* Finished with one layer of the tree */
22449 SQLITE_PRIVATE void sqlite3TreeViewPop(TreeView *p){
22450   if( p==0 ) return;
22451   p->iLevel--;
22452   if( p->iLevel<0 ) sqlite3_free(p);
22453 }
22454 /* Generate a single line of output for the tree, with a prefix that contains
22455 ** all the appropriate tree lines */
22456 SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
22457   va_list ap;
22458   int i;
22459   StrAccum acc;
22460   char zBuf[500];
22461   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
22462   if( p ){
22463     for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
22464       sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|   " : "    ", 4);
22465     }
22466     sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
22467   }
22468   va_start(ap, zFormat);
22469   sqlite3VXPrintf(&acc, 0, zFormat, ap);
22470   va_end(ap);
22471   if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
22472   sqlite3StrAccumFinish(&acc);
22473   fprintf(stdout,"%s", zBuf);
22474   fflush(stdout);
22475 }
22476 /* Shorthand for starting a new tree item that consists of a single label */
22477 SQLITE_PRIVATE void sqlite3TreeViewItem(TreeView *p, const char *zLabel, u8 moreToFollow){
22478   p = sqlite3TreeViewPush(p, moreToFollow);
22479   sqlite3TreeViewLine(p, "%s", zLabel);
22480 }
22481 #endif /* SQLITE_DEBUG */
22482 
22483 /*
22484 ** variable-argument wrapper around sqlite3VXPrintf().
22485 */
22486 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
22487   va_list ap;
22488   va_start(ap,zFormat);
22489   sqlite3VXPrintf(p, bFlags, zFormat, ap);
22490   va_end(ap);
22491 }
22492 
22493 /************** End of printf.c **********************************************/
22494 /************** Begin file random.c ******************************************/
22495 /*
22496 ** 2001 September 15
22497 **
22498 ** The author disclaims copyright to this source code.  In place of
22499 ** a legal notice, here is a blessing:
22500 **
22501 **    May you do good and not evil.
22502 **    May you find forgiveness for yourself and forgive others.
22503 **    May you share freely, never taking more than you give.
22504 **
22505 *************************************************************************
22506 ** This file contains code to implement a pseudo-random number
22507 ** generator (PRNG) for SQLite.
22508 **
22509 ** Random numbers are used by some of the database backends in order
22510 ** to generate random integer keys for tables or random filenames.
22511 */
22512 
22513 
22514 /* All threads share a single random number generator.
22515 ** This structure is the current state of the generator.
22516 */
22517 static SQLITE_WSD struct sqlite3PrngType {
22518   unsigned char isInit;          /* True if initialized */
22519   unsigned char i, j;            /* State variables */
22520   unsigned char s[256];          /* State variables */
22521 } sqlite3Prng;
22522 
22523 /*
22524 ** Return N random bytes.
22525 */
22526 SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *pBuf){
22527   unsigned char t;
22528   unsigned char *zBuf = pBuf;
22529 
22530   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
22531   ** state vector.  If writable static data is unsupported on the target,
22532   ** we have to locate the state vector at run-time.  In the more common
22533   ** case where writable static data is supported, wsdPrng can refer directly
22534   ** to the "sqlite3Prng" state vector declared above.
22535   */
22536 #ifdef SQLITE_OMIT_WSD
22537   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
22538 # define wsdPrng p[0]
22539 #else
22540 # define wsdPrng sqlite3Prng
22541 #endif
22542 
22543 #if SQLITE_THREADSAFE
22544   sqlite3_mutex *mutex;
22545 #endif
22546 
22547 #ifndef SQLITE_OMIT_AUTOINIT
22548   if( sqlite3_initialize() ) return;
22549 #endif
22550 
22551 #if SQLITE_THREADSAFE
22552   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
22553 #endif
22554 
22555   sqlite3_mutex_enter(mutex);
22556   if( N<=0 || pBuf==0 ){
22557     wsdPrng.isInit = 0;
22558     sqlite3_mutex_leave(mutex);
22559     return;
22560   }
22561 
22562   /* Initialize the state of the random number generator once,
22563   ** the first time this routine is called.  The seed value does
22564   ** not need to contain a lot of randomness since we are not
22565   ** trying to do secure encryption or anything like that...
22566   **
22567   ** Nothing in this file or anywhere else in SQLite does any kind of
22568   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
22569   ** number generator) not as an encryption device.
22570   */
22571   if( !wsdPrng.isInit ){
22572     int i;
22573     char k[256];
22574     wsdPrng.j = 0;
22575     wsdPrng.i = 0;
22576     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
22577     for(i=0; i<256; i++){
22578       wsdPrng.s[i] = (u8)i;
22579     }
22580     for(i=0; i<256; i++){
22581       wsdPrng.j += wsdPrng.s[i] + k[i];
22582       t = wsdPrng.s[wsdPrng.j];
22583       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
22584       wsdPrng.s[i] = t;
22585     }
22586     wsdPrng.isInit = 1;
22587   }
22588 
22589   assert( N>0 );
22590   do{
22591     wsdPrng.i++;
22592     t = wsdPrng.s[wsdPrng.i];
22593     wsdPrng.j += t;
22594     wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
22595     wsdPrng.s[wsdPrng.j] = t;
22596     t += wsdPrng.s[wsdPrng.i];
22597     *(zBuf++) = wsdPrng.s[t];
22598   }while( --N );
22599   sqlite3_mutex_leave(mutex);
22600 }
22601 
22602 #ifndef SQLITE_OMIT_BUILTIN_TEST
22603 /*
22604 ** For testing purposes, we sometimes want to preserve the state of
22605 ** PRNG and restore the PRNG to its saved state at a later time, or
22606 ** to reset the PRNG to its initial state.  These routines accomplish
22607 ** those tasks.
22608 **
22609 ** The sqlite3_test_control() interface calls these routines to
22610 ** control the PRNG.
22611 */
22612 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
22613 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
22614   memcpy(
22615     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
22616     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
22617     sizeof(sqlite3Prng)
22618   );
22619 }
22620 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
22621   memcpy(
22622     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
22623     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
22624     sizeof(sqlite3Prng)
22625   );
22626 }
22627 #endif /* SQLITE_OMIT_BUILTIN_TEST */
22628 
22629 /************** End of random.c **********************************************/
22630 /************** Begin file threads.c *****************************************/
22631 /*
22632 ** 2012 July 21
22633 **
22634 ** The author disclaims copyright to this source code.  In place of
22635 ** a legal notice, here is a blessing:
22636 **
22637 **    May you do good and not evil.
22638 **    May you find forgiveness for yourself and forgive others.
22639 **    May you share freely, never taking more than you give.
22640 **
22641 ******************************************************************************
22642 **
22643 ** This file presents a simple cross-platform threading interface for
22644 ** use internally by SQLite.
22645 **
22646 ** A "thread" can be created using sqlite3ThreadCreate().  This thread
22647 ** runs independently of its creator until it is joined using
22648 ** sqlite3ThreadJoin(), at which point it terminates.
22649 **
22650 ** Threads do not have to be real.  It could be that the work of the
22651 ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
22652 ** or sqlite3ThreadJoin() call.  This is, in fact, what happens in
22653 ** single threaded systems.  Nothing in SQLite requires multiple threads.
22654 ** This interface exists so that applications that want to take advantage
22655 ** of multiple cores can do so, while also allowing applications to stay
22656 ** single-threaded if desired.
22657 */
22658 #if SQLITE_OS_WIN
22659 #endif
22660 
22661 #if SQLITE_MAX_WORKER_THREADS>0
22662 
22663 /********************************* Unix Pthreads ****************************/
22664 #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
22665 
22666 #define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
22667 /* #include <pthread.h> */
22668 
22669 /* A running thread */
22670 struct SQLiteThread {
22671   pthread_t tid;                 /* Thread ID */
22672   int done;                      /* Set to true when thread finishes */
22673   void *pOut;                    /* Result returned by the thread */
22674   void *(*xTask)(void*);         /* The thread routine */
22675   void *pIn;                     /* Argument to the thread */
22676 };
22677 
22678 /* Create a new thread */
22679 SQLITE_PRIVATE int sqlite3ThreadCreate(
22680   SQLiteThread **ppThread,  /* OUT: Write the thread object here */
22681   void *(*xTask)(void*),    /* Routine to run in a separate thread */
22682   void *pIn                 /* Argument passed into xTask() */
22683 ){
22684   SQLiteThread *p;
22685   int rc;
22686 
22687   assert( ppThread!=0 );
22688   assert( xTask!=0 );
22689   /* This routine is never used in single-threaded mode */
22690   assert( sqlite3GlobalConfig.bCoreMutex!=0 );
22691 
22692   *ppThread = 0;
22693   p = sqlite3Malloc(sizeof(*p));
22694   if( p==0 ) return SQLITE_NOMEM;
22695   memset(p, 0, sizeof(*p));
22696   p->xTask = xTask;
22697   p->pIn = pIn;
22698   if( sqlite3FaultSim(200) ){
22699     rc = 1;
22700   }else{
22701     rc = pthread_create(&p->tid, 0, xTask, pIn);
22702   }
22703   if( rc ){
22704     p->done = 1;
22705     p->pOut = xTask(pIn);
22706   }
22707   *ppThread = p;
22708   return SQLITE_OK;
22709 }
22710 
22711 /* Get the results of the thread */
22712 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
22713   int rc;
22714 
22715   assert( ppOut!=0 );
22716   if( NEVER(p==0) ) return SQLITE_NOMEM;
22717   if( p->done ){
22718     *ppOut = p->pOut;
22719     rc = SQLITE_OK;
22720   }else{
22721     rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
22722   }
22723   sqlite3_free(p);
22724   return rc;
22725 }
22726 
22727 #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
22728 /******************************** End Unix Pthreads *************************/
22729 
22730 
22731 /********************************* Win32 Threads ****************************/
22732 #if SQLITE_OS_WIN_THREADS
22733 
22734 #define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
22735 #include <process.h>
22736 
22737 /* A running thread */
22738 struct SQLiteThread {
22739   void *tid;               /* The thread handle */
22740   unsigned id;             /* The thread identifier */
22741   void *(*xTask)(void*);   /* The routine to run as a thread */
22742   void *pIn;               /* Argument to xTask */
22743   void *pResult;           /* Result of xTask */
22744 };
22745 
22746 /* Thread procedure Win32 compatibility shim */
22747 static unsigned __stdcall sqlite3ThreadProc(
22748   void *pArg  /* IN: Pointer to the SQLiteThread structure */
22749 ){
22750   SQLiteThread *p = (SQLiteThread *)pArg;
22751 
22752   assert( p!=0 );
22753 #if 0
22754   /*
22755   ** This assert appears to trigger spuriously on certain
22756   ** versions of Windows, possibly due to _beginthreadex()
22757   ** and/or CreateThread() not fully setting their thread
22758   ** ID parameter before starting the thread.
22759   */
22760   assert( p->id==GetCurrentThreadId() );
22761 #endif
22762   assert( p->xTask!=0 );
22763   p->pResult = p->xTask(p->pIn);
22764 
22765   _endthreadex(0);
22766   return 0; /* NOT REACHED */
22767 }
22768 
22769 /* Create a new thread */
22770 SQLITE_PRIVATE int sqlite3ThreadCreate(
22771   SQLiteThread **ppThread,  /* OUT: Write the thread object here */
22772   void *(*xTask)(void*),    /* Routine to run in a separate thread */
22773   void *pIn                 /* Argument passed into xTask() */
22774 ){
22775   SQLiteThread *p;
22776 
22777   assert( ppThread!=0 );
22778   assert( xTask!=0 );
22779   *ppThread = 0;
22780   p = sqlite3Malloc(sizeof(*p));
22781   if( p==0 ) return SQLITE_NOMEM;
22782   if( sqlite3GlobalConfig.bCoreMutex==0 ){
22783     memset(p, 0, sizeof(*p));
22784   }else{
22785     p->xTask = xTask;
22786     p->pIn = pIn;
22787     p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
22788     if( p->tid==0 ){
22789       memset(p, 0, sizeof(*p));
22790     }
22791   }
22792   if( p->xTask==0 ){
22793     p->id = GetCurrentThreadId();
22794     p->pResult = xTask(pIn);
22795   }
22796   *ppThread = p;
22797   return SQLITE_OK;
22798 }
22799 
22800 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
22801 
22802 /* Get the results of the thread */
22803 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
22804   DWORD rc;
22805   BOOL bRc;
22806 
22807   assert( ppOut!=0 );
22808   if( NEVER(p==0) ) return SQLITE_NOMEM;
22809   if( p->xTask==0 ){
22810     assert( p->id==GetCurrentThreadId() );
22811     rc = WAIT_OBJECT_0;
22812     assert( p->tid==0 );
22813   }else{
22814     assert( p->id!=0 && p->id!=GetCurrentThreadId() );
22815     rc = sqlite3Win32Wait((HANDLE)p->tid);
22816     assert( rc!=WAIT_IO_COMPLETION );
22817     bRc = CloseHandle((HANDLE)p->tid);
22818     assert( bRc );
22819   }
22820   if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
22821   sqlite3_free(p);
22822   return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
22823 }
22824 
22825 #endif /* SQLITE_OS_WIN_THREADS */
22826 /******************************** End Win32 Threads *************************/
22827 
22828 
22829 /********************************* Single-Threaded **************************/
22830 #ifndef SQLITE_THREADS_IMPLEMENTED
22831 /*
22832 ** This implementation does not actually create a new thread.  It does the
22833 ** work of the thread in the main thread, when either the thread is created
22834 ** or when it is joined
22835 */
22836 
22837 /* A running thread */
22838 struct SQLiteThread {
22839   void *(*xTask)(void*);   /* The routine to run as a thread */
22840   void *pIn;               /* Argument to xTask */
22841   void *pResult;           /* Result of xTask */
22842 };
22843 
22844 /* Create a new thread */
22845 SQLITE_PRIVATE int sqlite3ThreadCreate(
22846   SQLiteThread **ppThread,  /* OUT: Write the thread object here */
22847   void *(*xTask)(void*),    /* Routine to run in a separate thread */
22848   void *pIn                 /* Argument passed into xTask() */
22849 ){
22850   SQLiteThread *p;
22851 
22852   assert( ppThread!=0 );
22853   assert( xTask!=0 );
22854   *ppThread = 0;
22855   p = sqlite3Malloc(sizeof(*p));
22856   if( p==0 ) return SQLITE_NOMEM;
22857   if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
22858     p->xTask = xTask;
22859     p->pIn = pIn;
22860   }else{
22861     p->xTask = 0;
22862     p->pResult = xTask(pIn);
22863   }
22864   *ppThread = p;
22865   return SQLITE_OK;
22866 }
22867 
22868 /* Get the results of the thread */
22869 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
22870 
22871   assert( ppOut!=0 );
22872   if( NEVER(p==0) ) return SQLITE_NOMEM;
22873   if( p->xTask ){
22874     *ppOut = p->xTask(p->pIn);
22875   }else{
22876     *ppOut = p->pResult;
22877   }
22878   sqlite3_free(p);
22879 
22880 #if defined(SQLITE_TEST)
22881   {
22882     void *pTstAlloc = sqlite3Malloc(10);
22883     if (!pTstAlloc) return SQLITE_NOMEM;
22884     sqlite3_free(pTstAlloc);
22885   }
22886 #endif
22887 
22888   return SQLITE_OK;
22889 }
22890 
22891 #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
22892 /****************************** End Single-Threaded *************************/
22893 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
22894 
22895 /************** End of threads.c *********************************************/
22896 /************** Begin file utf.c *********************************************/
22897 /*
22898 ** 2004 April 13
22899 **
22900 ** The author disclaims copyright to this source code.  In place of
22901 ** a legal notice, here is a blessing:
22902 **
22903 **    May you do good and not evil.
22904 **    May you find forgiveness for yourself and forgive others.
22905 **    May you share freely, never taking more than you give.
22906 **
22907 *************************************************************************
22908 ** This file contains routines used to translate between UTF-8,
22909 ** UTF-16, UTF-16BE, and UTF-16LE.
22910 **
22911 ** Notes on UTF-8:
22912 **
22913 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
22914 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
22915 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
22916 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
22917 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
22918 **
22919 **
22920 ** Notes on UTF-16:  (with wwww+1==uuuuu)
22921 **
22922 **      Word-0               Word-1          Value
22923 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
22924 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
22925 **
22926 **
22927 ** BOM or Byte Order Mark:
22928 **     0xff 0xfe   little-endian utf-16 follows
22929 **     0xfe 0xff   big-endian utf-16 follows
22930 **
22931 */
22932 /* #include <assert.h> */
22933 
22934 #ifndef SQLITE_AMALGAMATION
22935 /*
22936 ** The following constant value is used by the SQLITE_BIGENDIAN and
22937 ** SQLITE_LITTLEENDIAN macros.
22938 */
22939 SQLITE_PRIVATE const int sqlite3one = 1;
22940 #endif /* SQLITE_AMALGAMATION */
22941 
22942 /*
22943 ** This lookup table is used to help decode the first byte of
22944 ** a multi-byte UTF8 character.
22945 */
22946 static const unsigned char sqlite3Utf8Trans1[] = {
22947   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22948   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22949   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
22950   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
22951   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22952   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22953   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22954   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
22955 };
22956 
22957 
22958 #define WRITE_UTF8(zOut, c) {                          \
22959   if( c<0x00080 ){                                     \
22960     *zOut++ = (u8)(c&0xFF);                            \
22961   }                                                    \
22962   else if( c<0x00800 ){                                \
22963     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
22964     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22965   }                                                    \
22966   else if( c<0x10000 ){                                \
22967     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
22968     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
22969     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22970   }else{                                               \
22971     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
22972     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
22973     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
22974     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22975   }                                                    \
22976 }
22977 
22978 #define WRITE_UTF16LE(zOut, c) {                                    \
22979   if( c<=0xFFFF ){                                                  \
22980     *zOut++ = (u8)(c&0x00FF);                                       \
22981     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
22982   }else{                                                            \
22983     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
22984     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
22985     *zOut++ = (u8)(c&0x00FF);                                       \
22986     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
22987   }                                                                 \
22988 }
22989 
22990 #define WRITE_UTF16BE(zOut, c) {                                    \
22991   if( c<=0xFFFF ){                                                  \
22992     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
22993     *zOut++ = (u8)(c&0x00FF);                                       \
22994   }else{                                                            \
22995     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
22996     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
22997     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
22998     *zOut++ = (u8)(c&0x00FF);                                       \
22999   }                                                                 \
23000 }
23001 
23002 #define READ_UTF16LE(zIn, TERM, c){                                   \
23003   c = (*zIn++);                                                       \
23004   c += ((*zIn++)<<8);                                                 \
23005   if( c>=0xD800 && c<0xE000 && TERM ){                                \
23006     int c2 = (*zIn++);                                                \
23007     c2 += ((*zIn++)<<8);                                              \
23008     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
23009   }                                                                   \
23010 }
23011 
23012 #define READ_UTF16BE(zIn, TERM, c){                                   \
23013   c = ((*zIn++)<<8);                                                  \
23014   c += (*zIn++);                                                      \
23015   if( c>=0xD800 && c<0xE000 && TERM ){                                \
23016     int c2 = ((*zIn++)<<8);                                           \
23017     c2 += (*zIn++);                                                   \
23018     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
23019   }                                                                   \
23020 }
23021 
23022 /*
23023 ** Translate a single UTF-8 character.  Return the unicode value.
23024 **
23025 ** During translation, assume that the byte that zTerm points
23026 ** is a 0x00.
23027 **
23028 ** Write a pointer to the next unread byte back into *pzNext.
23029 **
23030 ** Notes On Invalid UTF-8:
23031 **
23032 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
23033 **     be encoded as a multi-byte character.  Any multi-byte character that
23034 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
23035 **
23036 **  *  This routine never allows a UTF16 surrogate value to be encoded.
23037 **     If a multi-byte character attempts to encode a value between
23038 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
23039 **
23040 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
23041 **     byte of a character are interpreted as single-byte characters
23042 **     and rendered as themselves even though they are technically
23043 **     invalid characters.
23044 **
23045 **  *  This routine accepts over-length UTF8 encodings
23046 **     for unicode values 0x80 and greater.  It does not change over-length
23047 **     encodings to 0xfffd as some systems recommend.
23048 */
23049 #define READ_UTF8(zIn, zTerm, c)                           \
23050   c = *(zIn++);                                            \
23051   if( c>=0xc0 ){                                           \
23052     c = sqlite3Utf8Trans1[c-0xc0];                         \
23053     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
23054       c = (c<<6) + (0x3f & *(zIn++));                      \
23055     }                                                      \
23056     if( c<0x80                                             \
23057         || (c&0xFFFFF800)==0xD800                          \
23058         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
23059   }
23060 SQLITE_PRIVATE u32 sqlite3Utf8Read(
23061   const unsigned char **pz    /* Pointer to string from which to read char */
23062 ){
23063   unsigned int c;
23064 
23065   /* Same as READ_UTF8() above but without the zTerm parameter.
23066   ** For this routine, we assume the UTF8 string is always zero-terminated.
23067   */
23068   c = *((*pz)++);
23069   if( c>=0xc0 ){
23070     c = sqlite3Utf8Trans1[c-0xc0];
23071     while( (*(*pz) & 0xc0)==0x80 ){
23072       c = (c<<6) + (0x3f & *((*pz)++));
23073     }
23074     if( c<0x80
23075         || (c&0xFFFFF800)==0xD800
23076         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
23077   }
23078   return c;
23079 }
23080 
23081 
23082 
23083 
23084 /*
23085 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
23086 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
23087 */
23088 /* #define TRANSLATE_TRACE 1 */
23089 
23090 #ifndef SQLITE_OMIT_UTF16
23091 /*
23092 ** This routine transforms the internal text encoding used by pMem to
23093 ** desiredEnc. It is an error if the string is already of the desired
23094 ** encoding, or if *pMem does not contain a string value.
23095 */
23096 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
23097   int len;                    /* Maximum length of output string in bytes */
23098   unsigned char *zOut;                  /* Output buffer */
23099   unsigned char *zIn;                   /* Input iterator */
23100   unsigned char *zTerm;                 /* End of input */
23101   unsigned char *z;                     /* Output iterator */
23102   unsigned int c;
23103 
23104   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
23105   assert( pMem->flags&MEM_Str );
23106   assert( pMem->enc!=desiredEnc );
23107   assert( pMem->enc!=0 );
23108   assert( pMem->n>=0 );
23109 
23110 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
23111   {
23112     char zBuf[100];
23113     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
23114     fprintf(stderr, "INPUT:  %s\n", zBuf);
23115   }
23116 #endif
23117 
23118   /* If the translation is between UTF-16 little and big endian, then
23119   ** all that is required is to swap the byte order. This case is handled
23120   ** differently from the others.
23121   */
23122   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
23123     u8 temp;
23124     int rc;
23125     rc = sqlite3VdbeMemMakeWriteable(pMem);
23126     if( rc!=SQLITE_OK ){
23127       assert( rc==SQLITE_NOMEM );
23128       return SQLITE_NOMEM;
23129     }
23130     zIn = (u8*)pMem->z;
23131     zTerm = &zIn[pMem->n&~1];
23132     while( zIn<zTerm ){
23133       temp = *zIn;
23134       *zIn = *(zIn+1);
23135       zIn++;
23136       *zIn++ = temp;
23137     }
23138     pMem->enc = desiredEnc;
23139     goto translate_out;
23140   }
23141 
23142   /* Set len to the maximum number of bytes required in the output buffer. */
23143   if( desiredEnc==SQLITE_UTF8 ){
23144     /* When converting from UTF-16, the maximum growth results from
23145     ** translating a 2-byte character to a 4-byte UTF-8 character.
23146     ** A single byte is required for the output string
23147     ** nul-terminator.
23148     */
23149     pMem->n &= ~1;
23150     len = pMem->n * 2 + 1;
23151   }else{
23152     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
23153     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
23154     ** character. Two bytes are required in the output buffer for the
23155     ** nul-terminator.
23156     */
23157     len = pMem->n * 2 + 2;
23158   }
23159 
23160   /* Set zIn to point at the start of the input buffer and zTerm to point 1
23161   ** byte past the end.
23162   **
23163   ** Variable zOut is set to point at the output buffer, space obtained
23164   ** from sqlite3_malloc().
23165   */
23166   zIn = (u8*)pMem->z;
23167   zTerm = &zIn[pMem->n];
23168   zOut = sqlite3DbMallocRaw(pMem->db, len);
23169   if( !zOut ){
23170     return SQLITE_NOMEM;
23171   }
23172   z = zOut;
23173 
23174   if( pMem->enc==SQLITE_UTF8 ){
23175     if( desiredEnc==SQLITE_UTF16LE ){
23176       /* UTF-8 -> UTF-16 Little-endian */
23177       while( zIn<zTerm ){
23178         READ_UTF8(zIn, zTerm, c);
23179         WRITE_UTF16LE(z, c);
23180       }
23181     }else{
23182       assert( desiredEnc==SQLITE_UTF16BE );
23183       /* UTF-8 -> UTF-16 Big-endian */
23184       while( zIn<zTerm ){
23185         READ_UTF8(zIn, zTerm, c);
23186         WRITE_UTF16BE(z, c);
23187       }
23188     }
23189     pMem->n = (int)(z - zOut);
23190     *z++ = 0;
23191   }else{
23192     assert( desiredEnc==SQLITE_UTF8 );
23193     if( pMem->enc==SQLITE_UTF16LE ){
23194       /* UTF-16 Little-endian -> UTF-8 */
23195       while( zIn<zTerm ){
23196         READ_UTF16LE(zIn, zIn<zTerm, c);
23197         WRITE_UTF8(z, c);
23198       }
23199     }else{
23200       /* UTF-16 Big-endian -> UTF-8 */
23201       while( zIn<zTerm ){
23202         READ_UTF16BE(zIn, zIn<zTerm, c);
23203         WRITE_UTF8(z, c);
23204       }
23205     }
23206     pMem->n = (int)(z - zOut);
23207   }
23208   *z = 0;
23209   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
23210 
23211   c = pMem->flags;
23212   sqlite3VdbeMemRelease(pMem);
23213   pMem->flags = MEM_Str|MEM_Term|(c&MEM_AffMask);
23214   pMem->enc = desiredEnc;
23215   pMem->z = (char*)zOut;
23216   pMem->zMalloc = pMem->z;
23217   pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
23218 
23219 translate_out:
23220 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
23221   {
23222     char zBuf[100];
23223     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
23224     fprintf(stderr, "OUTPUT: %s\n", zBuf);
23225   }
23226 #endif
23227   return SQLITE_OK;
23228 }
23229 
23230 /*
23231 ** This routine checks for a byte-order mark at the beginning of the
23232 ** UTF-16 string stored in *pMem. If one is present, it is removed and
23233 ** the encoding of the Mem adjusted. This routine does not do any
23234 ** byte-swapping, it just sets Mem.enc appropriately.
23235 **
23236 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
23237 ** changed by this function.
23238 */
23239 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
23240   int rc = SQLITE_OK;
23241   u8 bom = 0;
23242 
23243   assert( pMem->n>=0 );
23244   if( pMem->n>1 ){
23245     u8 b1 = *(u8 *)pMem->z;
23246     u8 b2 = *(((u8 *)pMem->z) + 1);
23247     if( b1==0xFE && b2==0xFF ){
23248       bom = SQLITE_UTF16BE;
23249     }
23250     if( b1==0xFF && b2==0xFE ){
23251       bom = SQLITE_UTF16LE;
23252     }
23253   }
23254 
23255   if( bom ){
23256     rc = sqlite3VdbeMemMakeWriteable(pMem);
23257     if( rc==SQLITE_OK ){
23258       pMem->n -= 2;
23259       memmove(pMem->z, &pMem->z[2], pMem->n);
23260       pMem->z[pMem->n] = '\0';
23261       pMem->z[pMem->n+1] = '\0';
23262       pMem->flags |= MEM_Term;
23263       pMem->enc = bom;
23264     }
23265   }
23266   return rc;
23267 }
23268 #endif /* SQLITE_OMIT_UTF16 */
23269 
23270 /*
23271 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
23272 ** return the number of unicode characters in pZ up to (but not including)
23273 ** the first 0x00 byte. If nByte is not less than zero, return the
23274 ** number of unicode characters in the first nByte of pZ (or up to
23275 ** the first 0x00, whichever comes first).
23276 */
23277 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
23278   int r = 0;
23279   const u8 *z = (const u8*)zIn;
23280   const u8 *zTerm;
23281   if( nByte>=0 ){
23282     zTerm = &z[nByte];
23283   }else{
23284     zTerm = (const u8*)(-1);
23285   }
23286   assert( z<=zTerm );
23287   while( *z!=0 && z<zTerm ){
23288     SQLITE_SKIP_UTF8(z);
23289     r++;
23290   }
23291   return r;
23292 }
23293 
23294 /* This test function is not currently used by the automated test-suite.
23295 ** Hence it is only available in debug builds.
23296 */
23297 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23298 /*
23299 ** Translate UTF-8 to UTF-8.
23300 **
23301 ** This has the effect of making sure that the string is well-formed
23302 ** UTF-8.  Miscoded characters are removed.
23303 **
23304 ** The translation is done in-place and aborted if the output
23305 ** overruns the input.
23306 */
23307 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
23308   unsigned char *zOut = zIn;
23309   unsigned char *zStart = zIn;
23310   u32 c;
23311 
23312   while( zIn[0] && zOut<=zIn ){
23313     c = sqlite3Utf8Read((const u8**)&zIn);
23314     if( c!=0xfffd ){
23315       WRITE_UTF8(zOut, c);
23316     }
23317   }
23318   *zOut = 0;
23319   return (int)(zOut - zStart);
23320 }
23321 #endif
23322 
23323 #ifndef SQLITE_OMIT_UTF16
23324 /*
23325 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
23326 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
23327 ** be freed by the calling function.
23328 **
23329 ** NULL is returned if there is an allocation error.
23330 */
23331 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
23332   Mem m;
23333   memset(&m, 0, sizeof(m));
23334   m.db = db;
23335   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
23336   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
23337   if( db->mallocFailed ){
23338     sqlite3VdbeMemRelease(&m);
23339     m.z = 0;
23340   }
23341   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
23342   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
23343   assert( m.z || db->mallocFailed );
23344   return m.z;
23345 }
23346 
23347 /*
23348 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
23349 ** Return the number of bytes in the first nChar unicode characters
23350 ** in pZ.  nChar must be non-negative.
23351 */
23352 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
23353   int c;
23354   unsigned char const *z = zIn;
23355   int n = 0;
23356 
23357   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
23358     while( n<nChar ){
23359       READ_UTF16BE(z, 1, c);
23360       n++;
23361     }
23362   }else{
23363     while( n<nChar ){
23364       READ_UTF16LE(z, 1, c);
23365       n++;
23366     }
23367   }
23368   return (int)(z-(unsigned char const *)zIn);
23369 }
23370 
23371 #if defined(SQLITE_TEST)
23372 /*
23373 ** This routine is called from the TCL test function "translate_selftest".
23374 ** It checks that the primitives for serializing and deserializing
23375 ** characters in each encoding are inverses of each other.
23376 */
23377 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
23378   unsigned int i, t;
23379   unsigned char zBuf[20];
23380   unsigned char *z;
23381   int n;
23382   unsigned int c;
23383 
23384   for(i=0; i<0x00110000; i++){
23385     z = zBuf;
23386     WRITE_UTF8(z, i);
23387     n = (int)(z-zBuf);
23388     assert( n>0 && n<=4 );
23389     z[0] = 0;
23390     z = zBuf;
23391     c = sqlite3Utf8Read((const u8**)&z);
23392     t = i;
23393     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
23394     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
23395     assert( c==t );
23396     assert( (z-zBuf)==n );
23397   }
23398   for(i=0; i<0x00110000; i++){
23399     if( i>=0xD800 && i<0xE000 ) continue;
23400     z = zBuf;
23401     WRITE_UTF16LE(z, i);
23402     n = (int)(z-zBuf);
23403     assert( n>0 && n<=4 );
23404     z[0] = 0;
23405     z = zBuf;
23406     READ_UTF16LE(z, 1, c);
23407     assert( c==i );
23408     assert( (z-zBuf)==n );
23409   }
23410   for(i=0; i<0x00110000; i++){
23411     if( i>=0xD800 && i<0xE000 ) continue;
23412     z = zBuf;
23413     WRITE_UTF16BE(z, i);
23414     n = (int)(z-zBuf);
23415     assert( n>0 && n<=4 );
23416     z[0] = 0;
23417     z = zBuf;
23418     READ_UTF16BE(z, 1, c);
23419     assert( c==i );
23420     assert( (z-zBuf)==n );
23421   }
23422 }
23423 #endif /* SQLITE_TEST */
23424 #endif /* SQLITE_OMIT_UTF16 */
23425 
23426 /************** End of utf.c *************************************************/
23427 /************** Begin file util.c ********************************************/
23428 /*
23429 ** 2001 September 15
23430 **
23431 ** The author disclaims copyright to this source code.  In place of
23432 ** a legal notice, here is a blessing:
23433 **
23434 **    May you do good and not evil.
23435 **    May you find forgiveness for yourself and forgive others.
23436 **    May you share freely, never taking more than you give.
23437 **
23438 *************************************************************************
23439 ** Utility functions used throughout sqlite.
23440 **
23441 ** This file contains functions for allocating memory, comparing
23442 ** strings, and stuff like that.
23443 **
23444 */
23445 /* #include <stdarg.h> */
23446 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
23447 # include <math.h>
23448 #endif
23449 
23450 /*
23451 ** Routine needed to support the testcase() macro.
23452 */
23453 #ifdef SQLITE_COVERAGE_TEST
23454 SQLITE_PRIVATE void sqlite3Coverage(int x){
23455   static unsigned dummy = 0;
23456   dummy += (unsigned)x;
23457 }
23458 #endif
23459 
23460 /*
23461 ** Give a callback to the test harness that can be used to simulate faults
23462 ** in places where it is difficult or expensive to do so purely by means
23463 ** of inputs.
23464 **
23465 ** The intent of the integer argument is to let the fault simulator know
23466 ** which of multiple sqlite3FaultSim() calls has been hit.
23467 **
23468 ** Return whatever integer value the test callback returns, or return
23469 ** SQLITE_OK if no test callback is installed.
23470 */
23471 #ifndef SQLITE_OMIT_BUILTIN_TEST
23472 SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
23473   int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
23474   return xCallback ? xCallback(iTest) : SQLITE_OK;
23475 }
23476 #endif
23477 
23478 #ifndef SQLITE_OMIT_FLOATING_POINT
23479 /*
23480 ** Return true if the floating point value is Not a Number (NaN).
23481 **
23482 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
23483 ** Otherwise, we have our own implementation that works on most systems.
23484 */
23485 SQLITE_PRIVATE int sqlite3IsNaN(double x){
23486   int rc;   /* The value return */
23487 #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
23488   /*
23489   ** Systems that support the isnan() library function should probably
23490   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
23491   ** found that many systems do not have a working isnan() function so
23492   ** this implementation is provided as an alternative.
23493   **
23494   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
23495   ** On the other hand, the use of -ffast-math comes with the following
23496   ** warning:
23497   **
23498   **      This option [-ffast-math] should never be turned on by any
23499   **      -O option since it can result in incorrect output for programs
23500   **      which depend on an exact implementation of IEEE or ISO
23501   **      rules/specifications for math functions.
23502   **
23503   ** Under MSVC, this NaN test may fail if compiled with a floating-
23504   ** point precision mode other than /fp:precise.  From the MSDN
23505   ** documentation:
23506   **
23507   **      The compiler [with /fp:precise] will properly handle comparisons
23508   **      involving NaN. For example, x != x evaluates to true if x is NaN
23509   **      ...
23510   */
23511 #ifdef __FAST_MATH__
23512 # error SQLite will not work correctly with the -ffast-math option of GCC.
23513 #endif
23514   volatile double y = x;
23515   volatile double z = y;
23516   rc = (y!=z);
23517 #else  /* if HAVE_ISNAN */
23518   rc = isnan(x);
23519 #endif /* HAVE_ISNAN */
23520   testcase( rc );
23521   return rc;
23522 }
23523 #endif /* SQLITE_OMIT_FLOATING_POINT */
23524 
23525 /*
23526 ** Compute a string length that is limited to what can be stored in
23527 ** lower 30 bits of a 32-bit signed integer.
23528 **
23529 ** The value returned will never be negative.  Nor will it ever be greater
23530 ** than the actual length of the string.  For very long strings (greater
23531 ** than 1GiB) the value returned might be less than the true string length.
23532 */
23533 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
23534   const char *z2 = z;
23535   if( z==0 ) return 0;
23536   while( *z2 ){ z2++; }
23537   return 0x3fffffff & (int)(z2 - z);
23538 }
23539 
23540 /*
23541 ** Set the current error code to err_code and clear any prior error message.
23542 */
23543 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
23544   assert( db!=0 );
23545   db->errCode = err_code;
23546   if( db->pErr ) sqlite3ValueSetNull(db->pErr);
23547 }
23548 
23549 /*
23550 ** Set the most recent error code and error string for the sqlite
23551 ** handle "db". The error code is set to "err_code".
23552 **
23553 ** If it is not NULL, string zFormat specifies the format of the
23554 ** error string in the style of the printf functions: The following
23555 ** format characters are allowed:
23556 **
23557 **      %s      Insert a string
23558 **      %z      A string that should be freed after use
23559 **      %d      Insert an integer
23560 **      %T      Insert a token
23561 **      %S      Insert the first element of a SrcList
23562 **
23563 ** zFormat and any string tokens that follow it are assumed to be
23564 ** encoded in UTF-8.
23565 **
23566 ** To clear the most recent error for sqlite handle "db", sqlite3Error
23567 ** should be called with err_code set to SQLITE_OK and zFormat set
23568 ** to NULL.
23569 */
23570 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
23571   assert( db!=0 );
23572   db->errCode = err_code;
23573   if( zFormat==0 ){
23574     sqlite3Error(db, err_code);
23575   }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
23576     char *z;
23577     va_list ap;
23578     va_start(ap, zFormat);
23579     z = sqlite3VMPrintf(db, zFormat, ap);
23580     va_end(ap);
23581     sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
23582   }
23583 }
23584 
23585 /*
23586 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
23587 ** The following formatting characters are allowed:
23588 **
23589 **      %s      Insert a string
23590 **      %z      A string that should be freed after use
23591 **      %d      Insert an integer
23592 **      %T      Insert a token
23593 **      %S      Insert the first element of a SrcList
23594 **
23595 ** This function should be used to report any error that occurs while
23596 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
23597 ** last thing the sqlite3_prepare() function does is copy the error
23598 ** stored by this function into the database handle using sqlite3Error().
23599 ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
23600 ** during statement execution (sqlite3_step() etc.).
23601 */
23602 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
23603   char *zMsg;
23604   va_list ap;
23605   sqlite3 *db = pParse->db;
23606   va_start(ap, zFormat);
23607   zMsg = sqlite3VMPrintf(db, zFormat, ap);
23608   va_end(ap);
23609   if( db->suppressErr ){
23610     sqlite3DbFree(db, zMsg);
23611   }else{
23612     pParse->nErr++;
23613     sqlite3DbFree(db, pParse->zErrMsg);
23614     pParse->zErrMsg = zMsg;
23615     pParse->rc = SQLITE_ERROR;
23616   }
23617 }
23618 
23619 /*
23620 ** Convert an SQL-style quoted string into a normal string by removing
23621 ** the quote characters.  The conversion is done in-place.  If the
23622 ** input does not begin with a quote character, then this routine
23623 ** is a no-op.
23624 **
23625 ** The input string must be zero-terminated.  A new zero-terminator
23626 ** is added to the dequoted string.
23627 **
23628 ** The return value is -1 if no dequoting occurs or the length of the
23629 ** dequoted string, exclusive of the zero terminator, if dequoting does
23630 ** occur.
23631 **
23632 ** 2002-Feb-14: This routine is extended to remove MS-Access style
23633 ** brackets from around identifiers.  For example:  "[a-b-c]" becomes
23634 ** "a-b-c".
23635 */
23636 SQLITE_PRIVATE int sqlite3Dequote(char *z){
23637   char quote;
23638   int i, j;
23639   if( z==0 ) return -1;
23640   quote = z[0];
23641   switch( quote ){
23642     case '\'':  break;
23643     case '"':   break;
23644     case '`':   break;                /* For MySQL compatibility */
23645     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
23646     default:    return -1;
23647   }
23648   for(i=1, j=0;; i++){
23649     assert( z[i] );
23650     if( z[i]==quote ){
23651       if( z[i+1]==quote ){
23652         z[j++] = quote;
23653         i++;
23654       }else{
23655         break;
23656       }
23657     }else{
23658       z[j++] = z[i];
23659     }
23660   }
23661   z[j] = 0;
23662   return j;
23663 }
23664 
23665 /* Convenient short-hand */
23666 #define UpperToLower sqlite3UpperToLower
23667 
23668 /*
23669 ** Some systems have stricmp().  Others have strcasecmp().  Because
23670 ** there is no consistency, we will define our own.
23671 **
23672 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
23673 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
23674 ** the contents of two buffers containing UTF-8 strings in a
23675 ** case-independent fashion, using the same definition of "case
23676 ** independence" that SQLite uses internally when comparing identifiers.
23677 */
23678 SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *zLeft, const char *zRight){
23679   register unsigned char *a, *b;
23680   if( zLeft==0 ){
23681     return zRight ? -1 : 0;
23682   }else if( zRight==0 ){
23683     return 1;
23684   }
23685   a = (unsigned char *)zLeft;
23686   b = (unsigned char *)zRight;
23687   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
23688   return UpperToLower[*a] - UpperToLower[*b];
23689 }
23690 SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
23691   register unsigned char *a, *b;
23692   if( zLeft==0 ){
23693     return zRight ? -1 : 0;
23694   }else if( zRight==0 ){
23695     return 1;
23696   }
23697   a = (unsigned char *)zLeft;
23698   b = (unsigned char *)zRight;
23699   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
23700   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
23701 }
23702 
23703 /*
23704 ** The string z[] is an text representation of a real number.
23705 ** Convert this string to a double and write it into *pResult.
23706 **
23707 ** The string z[] is length bytes in length (bytes, not characters) and
23708 ** uses the encoding enc.  The string is not necessarily zero-terminated.
23709 **
23710 ** Return TRUE if the result is a valid real number (or integer) and FALSE
23711 ** if the string is empty or contains extraneous text.  Valid numbers
23712 ** are in one of these formats:
23713 **
23714 **    [+-]digits[E[+-]digits]
23715 **    [+-]digits.[digits][E[+-]digits]
23716 **    [+-].digits[E[+-]digits]
23717 **
23718 ** Leading and trailing whitespace is ignored for the purpose of determining
23719 ** validity.
23720 **
23721 ** If some prefix of the input string is a valid number, this routine
23722 ** returns FALSE but it still converts the prefix and writes the result
23723 ** into *pResult.
23724 */
23725 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
23726 #ifndef SQLITE_OMIT_FLOATING_POINT
23727   int incr;
23728   const char *zEnd = z + length;
23729   /* sign * significand * (10 ^ (esign * exponent)) */
23730   int sign = 1;    /* sign of significand */
23731   i64 s = 0;       /* significand */
23732   int d = 0;       /* adjust exponent for shifting decimal point */
23733   int esign = 1;   /* sign of exponent */
23734   int e = 0;       /* exponent */
23735   int eValid = 1;  /* True exponent is either not used or is well-formed */
23736   double result;
23737   int nDigits = 0;
23738   int nonNum = 0;
23739 
23740   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
23741   *pResult = 0.0;   /* Default return value, in case of an error */
23742 
23743   if( enc==SQLITE_UTF8 ){
23744     incr = 1;
23745   }else{
23746     int i;
23747     incr = 2;
23748     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
23749     for(i=3-enc; i<length && z[i]==0; i+=2){}
23750     nonNum = i<length;
23751     zEnd = z+i+enc-3;
23752     z += (enc&1);
23753   }
23754 
23755   /* skip leading spaces */
23756   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
23757   if( z>=zEnd ) return 0;
23758 
23759   /* get sign of significand */
23760   if( *z=='-' ){
23761     sign = -1;
23762     z+=incr;
23763   }else if( *z=='+' ){
23764     z+=incr;
23765   }
23766 
23767   /* skip leading zeroes */
23768   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
23769 
23770   /* copy max significant digits to significand */
23771   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
23772     s = s*10 + (*z - '0');
23773     z+=incr, nDigits++;
23774   }
23775 
23776   /* skip non-significant significand digits
23777   ** (increase exponent by d to shift decimal left) */
23778   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
23779   if( z>=zEnd ) goto do_atof_calc;
23780 
23781   /* if decimal point is present */
23782   if( *z=='.' ){
23783     z+=incr;
23784     /* copy digits from after decimal to significand
23785     ** (decrease exponent by d to shift decimal right) */
23786     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
23787       s = s*10 + (*z - '0');
23788       z+=incr, nDigits++, d--;
23789     }
23790     /* skip non-significant digits */
23791     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
23792   }
23793   if( z>=zEnd ) goto do_atof_calc;
23794 
23795   /* if exponent is present */
23796   if( *z=='e' || *z=='E' ){
23797     z+=incr;
23798     eValid = 0;
23799     if( z>=zEnd ) goto do_atof_calc;
23800     /* get sign of exponent */
23801     if( *z=='-' ){
23802       esign = -1;
23803       z+=incr;
23804     }else if( *z=='+' ){
23805       z+=incr;
23806     }
23807     /* copy digits to exponent */
23808     while( z<zEnd && sqlite3Isdigit(*z) ){
23809       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
23810       z+=incr;
23811       eValid = 1;
23812     }
23813   }
23814 
23815   /* skip trailing spaces */
23816   if( nDigits && eValid ){
23817     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
23818   }
23819 
23820 do_atof_calc:
23821   /* adjust exponent by d, and update sign */
23822   e = (e*esign) + d;
23823   if( e<0 ) {
23824     esign = -1;
23825     e *= -1;
23826   } else {
23827     esign = 1;
23828   }
23829 
23830   /* if 0 significand */
23831   if( !s ) {
23832     /* In the IEEE 754 standard, zero is signed.
23833     ** Add the sign if we've seen at least one digit */
23834     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
23835   } else {
23836     /* attempt to reduce exponent */
23837     if( esign>0 ){
23838       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
23839     }else{
23840       while( !(s%10) && e>0 ) e--,s/=10;
23841     }
23842 
23843     /* adjust the sign of significand */
23844     s = sign<0 ? -s : s;
23845 
23846     /* if exponent, scale significand as appropriate
23847     ** and store in result. */
23848     if( e ){
23849       LONGDOUBLE_TYPE scale = 1.0;
23850       /* attempt to handle extremely small/large numbers better */
23851       if( e>307 && e<342 ){
23852         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
23853         if( esign<0 ){
23854           result = s / scale;
23855           result /= 1.0e+308;
23856         }else{
23857           result = s * scale;
23858           result *= 1.0e+308;
23859         }
23860       }else if( e>=342 ){
23861         if( esign<0 ){
23862           result = 0.0*s;
23863         }else{
23864           result = 1e308*1e308*s;  /* Infinity */
23865         }
23866       }else{
23867         /* 1.0e+22 is the largest power of 10 than can be
23868         ** represented exactly. */
23869         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
23870         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
23871         if( esign<0 ){
23872           result = s / scale;
23873         }else{
23874           result = s * scale;
23875         }
23876       }
23877     } else {
23878       result = (double)s;
23879     }
23880   }
23881 
23882   /* store the result */
23883   *pResult = result;
23884 
23885   /* return true if number and no extra non-whitespace chracters after */
23886   return z>=zEnd && nDigits>0 && eValid && nonNum==0;
23887 #else
23888   return !sqlite3Atoi64(z, pResult, length, enc);
23889 #endif /* SQLITE_OMIT_FLOATING_POINT */
23890 }
23891 
23892 /*
23893 ** Compare the 19-character string zNum against the text representation
23894 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
23895 ** if zNum is less than, equal to, or greater than the string.
23896 ** Note that zNum must contain exactly 19 characters.
23897 **
23898 ** Unlike memcmp() this routine is guaranteed to return the difference
23899 ** in the values of the last digit if the only difference is in the
23900 ** last digit.  So, for example,
23901 **
23902 **      compare2pow63("9223372036854775800", 1)
23903 **
23904 ** will return -8.
23905 */
23906 static int compare2pow63(const char *zNum, int incr){
23907   int c = 0;
23908   int i;
23909                     /* 012345678901234567 */
23910   const char *pow63 = "922337203685477580";
23911   for(i=0; c==0 && i<18; i++){
23912     c = (zNum[i*incr]-pow63[i])*10;
23913   }
23914   if( c==0 ){
23915     c = zNum[18*incr] - '8';
23916     testcase( c==(-1) );
23917     testcase( c==0 );
23918     testcase( c==(+1) );
23919   }
23920   return c;
23921 }
23922 
23923 /*
23924 ** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
23925 ** routine does *not* accept hexadecimal notation.
23926 **
23927 ** If the zNum value is representable as a 64-bit twos-complement
23928 ** integer, then write that value into *pNum and return 0.
23929 **
23930 ** If zNum is exactly 9223372036854775808, return 2.  This special
23931 ** case is broken out because while 9223372036854775808 cannot be a
23932 ** signed 64-bit integer, its negative -9223372036854775808 can be.
23933 **
23934 ** If zNum is too big for a 64-bit integer and is not
23935 ** 9223372036854775808  or if zNum contains any non-numeric text,
23936 ** then return 1.
23937 **
23938 ** length is the number of bytes in the string (bytes, not characters).
23939 ** The string is not necessarily zero-terminated.  The encoding is
23940 ** given by enc.
23941 */
23942 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
23943   int incr;
23944   u64 u = 0;
23945   int neg = 0; /* assume positive */
23946   int i;
23947   int c = 0;
23948   int nonNum = 0;
23949   const char *zStart;
23950   const char *zEnd = zNum + length;
23951   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
23952   if( enc==SQLITE_UTF8 ){
23953     incr = 1;
23954   }else{
23955     incr = 2;
23956     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
23957     for(i=3-enc; i<length && zNum[i]==0; i+=2){}
23958     nonNum = i<length;
23959     zEnd = zNum+i+enc-3;
23960     zNum += (enc&1);
23961   }
23962   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
23963   if( zNum<zEnd ){
23964     if( *zNum=='-' ){
23965       neg = 1;
23966       zNum+=incr;
23967     }else if( *zNum=='+' ){
23968       zNum+=incr;
23969     }
23970   }
23971   zStart = zNum;
23972   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
23973   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
23974     u = u*10 + c - '0';
23975   }
23976   if( u>LARGEST_INT64 ){
23977     *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
23978   }else if( neg ){
23979     *pNum = -(i64)u;
23980   }else{
23981     *pNum = (i64)u;
23982   }
23983   testcase( i==18 );
23984   testcase( i==19 );
23985   testcase( i==20 );
23986   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
23987     /* zNum is empty or contains non-numeric text or is longer
23988     ** than 19 digits (thus guaranteeing that it is too large) */
23989     return 1;
23990   }else if( i<19*incr ){
23991     /* Less than 19 digits, so we know that it fits in 64 bits */
23992     assert( u<=LARGEST_INT64 );
23993     return 0;
23994   }else{
23995     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
23996     c = compare2pow63(zNum, incr);
23997     if( c<0 ){
23998       /* zNum is less than 9223372036854775808 so it fits */
23999       assert( u<=LARGEST_INT64 );
24000       return 0;
24001     }else if( c>0 ){
24002       /* zNum is greater than 9223372036854775808 so it overflows */
24003       return 1;
24004     }else{
24005       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
24006       ** special case 2 overflow if positive */
24007       assert( u-1==LARGEST_INT64 );
24008       return neg ? 0 : 2;
24009     }
24010   }
24011 }
24012 
24013 /*
24014 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
24015 ** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
24016 ** whereas sqlite3Atoi64() does not.
24017 **
24018 ** Returns:
24019 **
24020 **     0    Successful transformation.  Fits in a 64-bit signed integer.
24021 **     1    Integer too large for a 64-bit signed integer or is malformed
24022 **     2    Special case of 9223372036854775808
24023 */
24024 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
24025 #ifndef SQLITE_OMIT_HEX_INTEGER
24026   if( z[0]=='0'
24027    && (z[1]=='x' || z[1]=='X')
24028    && sqlite3Isxdigit(z[2])
24029   ){
24030     u64 u = 0;
24031     int i, k;
24032     for(i=2; z[i]=='0'; i++){}
24033     for(k=i; sqlite3Isxdigit(z[k]); k++){
24034       u = u*16 + sqlite3HexToInt(z[k]);
24035     }
24036     memcpy(pOut, &u, 8);
24037     return (z[k]==0 && k-i<=16) ? 0 : 1;
24038   }else
24039 #endif /* SQLITE_OMIT_HEX_INTEGER */
24040   {
24041     return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
24042   }
24043 }
24044 
24045 /*
24046 ** If zNum represents an integer that will fit in 32-bits, then set
24047 ** *pValue to that integer and return true.  Otherwise return false.
24048 **
24049 ** This routine accepts both decimal and hexadecimal notation for integers.
24050 **
24051 ** Any non-numeric characters that following zNum are ignored.
24052 ** This is different from sqlite3Atoi64() which requires the
24053 ** input number to be zero-terminated.
24054 */
24055 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
24056   sqlite_int64 v = 0;
24057   int i, c;
24058   int neg = 0;
24059   if( zNum[0]=='-' ){
24060     neg = 1;
24061     zNum++;
24062   }else if( zNum[0]=='+' ){
24063     zNum++;
24064   }
24065 #ifndef SQLITE_OMIT_HEX_INTEGER
24066   else if( zNum[0]=='0'
24067         && (zNum[1]=='x' || zNum[1]=='X')
24068         && sqlite3Isxdigit(zNum[2])
24069   ){
24070     u32 u = 0;
24071     zNum += 2;
24072     while( zNum[0]=='0' ) zNum++;
24073     for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
24074       u = u*16 + sqlite3HexToInt(zNum[i]);
24075     }
24076     if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
24077       memcpy(pValue, &u, 4);
24078       return 1;
24079     }else{
24080       return 0;
24081     }
24082   }
24083 #endif
24084   while( zNum[0]=='0' ) zNum++;
24085   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
24086     v = v*10 + c;
24087   }
24088 
24089   /* The longest decimal representation of a 32 bit integer is 10 digits:
24090   **
24091   **             1234567890
24092   **     2^31 -> 2147483648
24093   */
24094   testcase( i==10 );
24095   if( i>10 ){
24096     return 0;
24097   }
24098   testcase( v-neg==2147483647 );
24099   if( v-neg>2147483647 ){
24100     return 0;
24101   }
24102   if( neg ){
24103     v = -v;
24104   }
24105   *pValue = (int)v;
24106   return 1;
24107 }
24108 
24109 /*
24110 ** Return a 32-bit integer value extracted from a string.  If the
24111 ** string is not an integer, just return 0.
24112 */
24113 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
24114   int x = 0;
24115   if( z ) sqlite3GetInt32(z, &x);
24116   return x;
24117 }
24118 
24119 /*
24120 ** The variable-length integer encoding is as follows:
24121 **
24122 ** KEY:
24123 **         A = 0xxxxxxx    7 bits of data and one flag bit
24124 **         B = 1xxxxxxx    7 bits of data and one flag bit
24125 **         C = xxxxxxxx    8 bits of data
24126 **
24127 **  7 bits - A
24128 ** 14 bits - BA
24129 ** 21 bits - BBA
24130 ** 28 bits - BBBA
24131 ** 35 bits - BBBBA
24132 ** 42 bits - BBBBBA
24133 ** 49 bits - BBBBBBA
24134 ** 56 bits - BBBBBBBA
24135 ** 64 bits - BBBBBBBBC
24136 */
24137 
24138 /*
24139 ** Write a 64-bit variable-length integer to memory starting at p[0].
24140 ** The length of data write will be between 1 and 9 bytes.  The number
24141 ** of bytes written is returned.
24142 **
24143 ** A variable-length integer consists of the lower 7 bits of each byte
24144 ** for all bytes that have the 8th bit set and one byte with the 8th
24145 ** bit clear.  Except, if we get to the 9th byte, it stores the full
24146 ** 8 bits and is the last byte.
24147 */
24148 static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
24149   int i, j, n;
24150   u8 buf[10];
24151   if( v & (((u64)0xff000000)<<32) ){
24152     p[8] = (u8)v;
24153     v >>= 8;
24154     for(i=7; i>=0; i--){
24155       p[i] = (u8)((v & 0x7f) | 0x80);
24156       v >>= 7;
24157     }
24158     return 9;
24159   }
24160   n = 0;
24161   do{
24162     buf[n++] = (u8)((v & 0x7f) | 0x80);
24163     v >>= 7;
24164   }while( v!=0 );
24165   buf[0] &= 0x7f;
24166   assert( n<=9 );
24167   for(i=0, j=n-1; j>=0; j--, i++){
24168     p[i] = buf[j];
24169   }
24170   return n;
24171 }
24172 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
24173   if( v<=0x7f ){
24174     p[0] = v&0x7f;
24175     return 1;
24176   }
24177   if( v<=0x3fff ){
24178     p[0] = ((v>>7)&0x7f)|0x80;
24179     p[1] = v&0x7f;
24180     return 2;
24181   }
24182   return putVarint64(p,v);
24183 }
24184 
24185 /*
24186 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
24187 ** are defined here rather than simply putting the constant expressions
24188 ** inline in order to work around bugs in the RVT compiler.
24189 **
24190 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
24191 **
24192 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
24193 */
24194 #define SLOT_2_0     0x001fc07f
24195 #define SLOT_4_2_0   0xf01fc07f
24196 
24197 
24198 /*
24199 ** Read a 64-bit variable-length integer from memory starting at p[0].
24200 ** Return the number of bytes read.  The value is stored in *v.
24201 */
24202 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
24203   u32 a,b,s;
24204 
24205   a = *p;
24206   /* a: p0 (unmasked) */
24207   if (!(a&0x80))
24208   {
24209     *v = a;
24210     return 1;
24211   }
24212 
24213   p++;
24214   b = *p;
24215   /* b: p1 (unmasked) */
24216   if (!(b&0x80))
24217   {
24218     a &= 0x7f;
24219     a = a<<7;
24220     a |= b;
24221     *v = a;
24222     return 2;
24223   }
24224 
24225   /* Verify that constants are precomputed correctly */
24226   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
24227   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
24228 
24229   p++;
24230   a = a<<14;
24231   a |= *p;
24232   /* a: p0<<14 | p2 (unmasked) */
24233   if (!(a&0x80))
24234   {
24235     a &= SLOT_2_0;
24236     b &= 0x7f;
24237     b = b<<7;
24238     a |= b;
24239     *v = a;
24240     return 3;
24241   }
24242 
24243   /* CSE1 from below */
24244   a &= SLOT_2_0;
24245   p++;
24246   b = b<<14;
24247   b |= *p;
24248   /* b: p1<<14 | p3 (unmasked) */
24249   if (!(b&0x80))
24250   {
24251     b &= SLOT_2_0;
24252     /* moved CSE1 up */
24253     /* a &= (0x7f<<14)|(0x7f); */
24254     a = a<<7;
24255     a |= b;
24256     *v = a;
24257     return 4;
24258   }
24259 
24260   /* a: p0<<14 | p2 (masked) */
24261   /* b: p1<<14 | p3 (unmasked) */
24262   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
24263   /* moved CSE1 up */
24264   /* a &= (0x7f<<14)|(0x7f); */
24265   b &= SLOT_2_0;
24266   s = a;
24267   /* s: p0<<14 | p2 (masked) */
24268 
24269   p++;
24270   a = a<<14;
24271   a |= *p;
24272   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
24273   if (!(a&0x80))
24274   {
24275     /* we can skip these cause they were (effectively) done above in calc'ing s */
24276     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
24277     /* b &= (0x7f<<14)|(0x7f); */
24278     b = b<<7;
24279     a |= b;
24280     s = s>>18;
24281     *v = ((u64)s)<<32 | a;
24282     return 5;
24283   }
24284 
24285   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
24286   s = s<<7;
24287   s |= b;
24288   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
24289 
24290   p++;
24291   b = b<<14;
24292   b |= *p;
24293   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
24294   if (!(b&0x80))
24295   {
24296     /* we can skip this cause it was (effectively) done above in calc'ing s */
24297     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
24298     a &= SLOT_2_0;
24299     a = a<<7;
24300     a |= b;
24301     s = s>>18;
24302     *v = ((u64)s)<<32 | a;
24303     return 6;
24304   }
24305 
24306   p++;
24307   a = a<<14;
24308   a |= *p;
24309   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
24310   if (!(a&0x80))
24311   {
24312     a &= SLOT_4_2_0;
24313     b &= SLOT_2_0;
24314     b = b<<7;
24315     a |= b;
24316     s = s>>11;
24317     *v = ((u64)s)<<32 | a;
24318     return 7;
24319   }
24320 
24321   /* CSE2 from below */
24322   a &= SLOT_2_0;
24323   p++;
24324   b = b<<14;
24325   b |= *p;
24326   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
24327   if (!(b&0x80))
24328   {
24329     b &= SLOT_4_2_0;
24330     /* moved CSE2 up */
24331     /* a &= (0x7f<<14)|(0x7f); */
24332     a = a<<7;
24333     a |= b;
24334     s = s>>4;
24335     *v = ((u64)s)<<32 | a;
24336     return 8;
24337   }
24338 
24339   p++;
24340   a = a<<15;
24341   a |= *p;
24342   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
24343 
24344   /* moved CSE2 up */
24345   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
24346   b &= SLOT_2_0;
24347   b = b<<8;
24348   a |= b;
24349 
24350   s = s<<4;
24351   b = p[-4];
24352   b &= 0x7f;
24353   b = b>>3;
24354   s |= b;
24355 
24356   *v = ((u64)s)<<32 | a;
24357 
24358   return 9;
24359 }
24360 
24361 /*
24362 ** Read a 32-bit variable-length integer from memory starting at p[0].
24363 ** Return the number of bytes read.  The value is stored in *v.
24364 **
24365 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
24366 ** integer, then set *v to 0xffffffff.
24367 **
24368 ** A MACRO version, getVarint32, is provided which inlines the
24369 ** single-byte case.  All code should use the MACRO version as
24370 ** this function assumes the single-byte case has already been handled.
24371 */
24372 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
24373   u32 a,b;
24374 
24375   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
24376   ** by the getVarin32() macro */
24377   a = *p;
24378   /* a: p0 (unmasked) */
24379 #ifndef getVarint32
24380   if (!(a&0x80))
24381   {
24382     /* Values between 0 and 127 */
24383     *v = a;
24384     return 1;
24385   }
24386 #endif
24387 
24388   /* The 2-byte case */
24389   p++;
24390   b = *p;
24391   /* b: p1 (unmasked) */
24392   if (!(b&0x80))
24393   {
24394     /* Values between 128 and 16383 */
24395     a &= 0x7f;
24396     a = a<<7;
24397     *v = a | b;
24398     return 2;
24399   }
24400 
24401   /* The 3-byte case */
24402   p++;
24403   a = a<<14;
24404   a |= *p;
24405   /* a: p0<<14 | p2 (unmasked) */
24406   if (!(a&0x80))
24407   {
24408     /* Values between 16384 and 2097151 */
24409     a &= (0x7f<<14)|(0x7f);
24410     b &= 0x7f;
24411     b = b<<7;
24412     *v = a | b;
24413     return 3;
24414   }
24415 
24416   /* A 32-bit varint is used to store size information in btrees.
24417   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
24418   ** A 3-byte varint is sufficient, for example, to record the size
24419   ** of a 1048569-byte BLOB or string.
24420   **
24421   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
24422   ** rare larger cases can be handled by the slower 64-bit varint
24423   ** routine.
24424   */
24425 #if 1
24426   {
24427     u64 v64;
24428     u8 n;
24429 
24430     p -= 2;
24431     n = sqlite3GetVarint(p, &v64);
24432     assert( n>3 && n<=9 );
24433     if( (v64 & SQLITE_MAX_U32)!=v64 ){
24434       *v = 0xffffffff;
24435     }else{
24436       *v = (u32)v64;
24437     }
24438     return n;
24439   }
24440 
24441 #else
24442   /* For following code (kept for historical record only) shows an
24443   ** unrolling for the 3- and 4-byte varint cases.  This code is
24444   ** slightly faster, but it is also larger and much harder to test.
24445   */
24446   p++;
24447   b = b<<14;
24448   b |= *p;
24449   /* b: p1<<14 | p3 (unmasked) */
24450   if (!(b&0x80))
24451   {
24452     /* Values between 2097152 and 268435455 */
24453     b &= (0x7f<<14)|(0x7f);
24454     a &= (0x7f<<14)|(0x7f);
24455     a = a<<7;
24456     *v = a | b;
24457     return 4;
24458   }
24459 
24460   p++;
24461   a = a<<14;
24462   a |= *p;
24463   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
24464   if (!(a&0x80))
24465   {
24466     /* Values  between 268435456 and 34359738367 */
24467     a &= SLOT_4_2_0;
24468     b &= SLOT_4_2_0;
24469     b = b<<7;
24470     *v = a | b;
24471     return 5;
24472   }
24473 
24474   /* We can only reach this point when reading a corrupt database
24475   ** file.  In that case we are not in any hurry.  Use the (relatively
24476   ** slow) general-purpose sqlite3GetVarint() routine to extract the
24477   ** value. */
24478   {
24479     u64 v64;
24480     u8 n;
24481 
24482     p -= 4;
24483     n = sqlite3GetVarint(p, &v64);
24484     assert( n>5 && n<=9 );
24485     *v = (u32)v64;
24486     return n;
24487   }
24488 #endif
24489 }
24490 
24491 /*
24492 ** Return the number of bytes that will be needed to store the given
24493 ** 64-bit integer.
24494 */
24495 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
24496   int i = 0;
24497   do{
24498     i++;
24499     v >>= 7;
24500   }while( v!=0 && ALWAYS(i<9) );
24501   return i;
24502 }
24503 
24504 
24505 /*
24506 ** Read or write a four-byte big-endian integer value.
24507 */
24508 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
24509   testcase( p[0]&0x80 );
24510   return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
24511 }
24512 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
24513   p[0] = (u8)(v>>24);
24514   p[1] = (u8)(v>>16);
24515   p[2] = (u8)(v>>8);
24516   p[3] = (u8)v;
24517 }
24518 
24519 
24520 
24521 /*
24522 ** Translate a single byte of Hex into an integer.
24523 ** This routine only works if h really is a valid hexadecimal
24524 ** character:  0..9a..fA..F
24525 */
24526 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
24527   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
24528 #ifdef SQLITE_ASCII
24529   h += 9*(1&(h>>6));
24530 #endif
24531 #ifdef SQLITE_EBCDIC
24532   h += 9*(1&~(h>>4));
24533 #endif
24534   return (u8)(h & 0xf);
24535 }
24536 
24537 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
24538 /*
24539 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
24540 ** value.  Return a pointer to its binary value.  Space to hold the
24541 ** binary value has been obtained from malloc and must be freed by
24542 ** the calling routine.
24543 */
24544 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
24545   char *zBlob;
24546   int i;
24547 
24548   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
24549   n--;
24550   if( zBlob ){
24551     for(i=0; i<n; i+=2){
24552       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
24553     }
24554     zBlob[i/2] = 0;
24555   }
24556   return zBlob;
24557 }
24558 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
24559 
24560 /*
24561 ** Log an error that is an API call on a connection pointer that should
24562 ** not have been used.  The "type" of connection pointer is given as the
24563 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
24564 */
24565 static void logBadConnection(const char *zType){
24566   sqlite3_log(SQLITE_MISUSE,
24567      "API call with %s database connection pointer",
24568      zType
24569   );
24570 }
24571 
24572 /*
24573 ** Check to make sure we have a valid db pointer.  This test is not
24574 ** foolproof but it does provide some measure of protection against
24575 ** misuse of the interface such as passing in db pointers that are
24576 ** NULL or which have been previously closed.  If this routine returns
24577 ** 1 it means that the db pointer is valid and 0 if it should not be
24578 ** dereferenced for any reason.  The calling function should invoke
24579 ** SQLITE_MISUSE immediately.
24580 **
24581 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
24582 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
24583 ** open properly and is not fit for general use but which can be
24584 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
24585 */
24586 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
24587   u32 magic;
24588   if( db==0 ){
24589     logBadConnection("NULL");
24590     return 0;
24591   }
24592   magic = db->magic;
24593   if( magic!=SQLITE_MAGIC_OPEN ){
24594     if( sqlite3SafetyCheckSickOrOk(db) ){
24595       testcase( sqlite3GlobalConfig.xLog!=0 );
24596       logBadConnection("unopened");
24597     }
24598     return 0;
24599   }else{
24600     return 1;
24601   }
24602 }
24603 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
24604   u32 magic;
24605   magic = db->magic;
24606   if( magic!=SQLITE_MAGIC_SICK &&
24607       magic!=SQLITE_MAGIC_OPEN &&
24608       magic!=SQLITE_MAGIC_BUSY ){
24609     testcase( sqlite3GlobalConfig.xLog!=0 );
24610     logBadConnection("invalid");
24611     return 0;
24612   }else{
24613     return 1;
24614   }
24615 }
24616 
24617 /*
24618 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
24619 ** the other 64-bit signed integer at *pA and store the result in *pA.
24620 ** Return 0 on success.  Or if the operation would have resulted in an
24621 ** overflow, leave *pA unchanged and return 1.
24622 */
24623 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
24624   i64 iA = *pA;
24625   testcase( iA==0 ); testcase( iA==1 );
24626   testcase( iB==-1 ); testcase( iB==0 );
24627   if( iB>=0 ){
24628     testcase( iA>0 && LARGEST_INT64 - iA == iB );
24629     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
24630     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
24631   }else{
24632     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
24633     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
24634     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
24635   }
24636   *pA += iB;
24637   return 0;
24638 }
24639 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
24640   testcase( iB==SMALLEST_INT64+1 );
24641   if( iB==SMALLEST_INT64 ){
24642     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
24643     if( (*pA)>=0 ) return 1;
24644     *pA -= iB;
24645     return 0;
24646   }else{
24647     return sqlite3AddInt64(pA, -iB);
24648   }
24649 }
24650 #define TWOPOWER32 (((i64)1)<<32)
24651 #define TWOPOWER31 (((i64)1)<<31)
24652 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
24653   i64 iA = *pA;
24654   i64 iA1, iA0, iB1, iB0, r;
24655 
24656   iA1 = iA/TWOPOWER32;
24657   iA0 = iA % TWOPOWER32;
24658   iB1 = iB/TWOPOWER32;
24659   iB0 = iB % TWOPOWER32;
24660   if( iA1==0 ){
24661     if( iB1==0 ){
24662       *pA *= iB;
24663       return 0;
24664     }
24665     r = iA0*iB1;
24666   }else if( iB1==0 ){
24667     r = iA1*iB0;
24668   }else{
24669     /* If both iA1 and iB1 are non-zero, overflow will result */
24670     return 1;
24671   }
24672   testcase( r==(-TWOPOWER31)-1 );
24673   testcase( r==(-TWOPOWER31) );
24674   testcase( r==TWOPOWER31 );
24675   testcase( r==TWOPOWER31-1 );
24676   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
24677   r *= TWOPOWER32;
24678   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
24679   *pA = r;
24680   return 0;
24681 }
24682 
24683 /*
24684 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or
24685 ** if the integer has a value of -2147483648, return +2147483647
24686 */
24687 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
24688   if( x>=0 ) return x;
24689   if( x==(int)0x80000000 ) return 0x7fffffff;
24690   return -x;
24691 }
24692 
24693 #ifdef SQLITE_ENABLE_8_3_NAMES
24694 /*
24695 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
24696 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
24697 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
24698 ** three characters, then shorten the suffix on z[] to be the last three
24699 ** characters of the original suffix.
24700 **
24701 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
24702 ** do the suffix shortening regardless of URI parameter.
24703 **
24704 ** Examples:
24705 **
24706 **     test.db-journal    =>   test.nal
24707 **     test.db-wal        =>   test.wal
24708 **     test.db-shm        =>   test.shm
24709 **     test.db-mj7f3319fa =>   test.9fa
24710 */
24711 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
24712 #if SQLITE_ENABLE_8_3_NAMES<2
24713   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
24714 #endif
24715   {
24716     int i, sz;
24717     sz = sqlite3Strlen30(z);
24718     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
24719     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
24720   }
24721 }
24722 #endif
24723 
24724 /*
24725 ** Find (an approximate) sum of two LogEst values.  This computation is
24726 ** not a simple "+" operator because LogEst is stored as a logarithmic
24727 ** value.
24728 **
24729 */
24730 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
24731   static const unsigned char x[] = {
24732      10, 10,                         /* 0,1 */
24733       9, 9,                          /* 2,3 */
24734       8, 8,                          /* 4,5 */
24735       7, 7, 7,                       /* 6,7,8 */
24736       6, 6, 6,                       /* 9,10,11 */
24737       5, 5, 5,                       /* 12-14 */
24738       4, 4, 4, 4,                    /* 15-18 */
24739       3, 3, 3, 3, 3, 3,              /* 19-24 */
24740       2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
24741   };
24742   if( a>=b ){
24743     if( a>b+49 ) return a;
24744     if( a>b+31 ) return a+1;
24745     return a+x[a-b];
24746   }else{
24747     if( b>a+49 ) return b;
24748     if( b>a+31 ) return b+1;
24749     return b+x[b-a];
24750   }
24751 }
24752 
24753 /*
24754 ** Convert an integer into a LogEst.  In other words, compute an
24755 ** approximation for 10*log2(x).
24756 */
24757 SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
24758   static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
24759   LogEst y = 40;
24760   if( x<8 ){
24761     if( x<2 ) return 0;
24762     while( x<8 ){  y -= 10; x <<= 1; }
24763   }else{
24764     while( x>255 ){ y += 40; x >>= 4; }
24765     while( x>15 ){  y += 10; x >>= 1; }
24766   }
24767   return a[x&7] + y - 10;
24768 }
24769 
24770 #ifndef SQLITE_OMIT_VIRTUALTABLE
24771 /*
24772 ** Convert a double into a LogEst
24773 ** In other words, compute an approximation for 10*log2(x).
24774 */
24775 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
24776   u64 a;
24777   LogEst e;
24778   assert( sizeof(x)==8 && sizeof(a)==8 );
24779   if( x<=1 ) return 0;
24780   if( x<=2000000000 ) return sqlite3LogEst((u64)x);
24781   memcpy(&a, &x, 8);
24782   e = (a>>52) - 1022;
24783   return e*10;
24784 }
24785 #endif /* SQLITE_OMIT_VIRTUALTABLE */
24786 
24787 /*
24788 ** Convert a LogEst into an integer.
24789 */
24790 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
24791   u64 n;
24792   if( x<10 ) return 1;
24793   n = x%10;
24794   x /= 10;
24795   if( n>=5 ) n -= 2;
24796   else if( n>=1 ) n -= 1;
24797   if( x>=3 ){
24798     return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
24799   }
24800   return (n+8)>>(3-x);
24801 }
24802 
24803 /************** End of util.c ************************************************/
24804 /************** Begin file hash.c ********************************************/
24805 /*
24806 ** 2001 September 22
24807 **
24808 ** The author disclaims copyright to this source code.  In place of
24809 ** a legal notice, here is a blessing:
24810 **
24811 **    May you do good and not evil.
24812 **    May you find forgiveness for yourself and forgive others.
24813 **    May you share freely, never taking more than you give.
24814 **
24815 *************************************************************************
24816 ** This is the implementation of generic hash-tables
24817 ** used in SQLite.
24818 */
24819 /* #include <assert.h> */
24820 
24821 /* Turn bulk memory into a hash table object by initializing the
24822 ** fields of the Hash structure.
24823 **
24824 ** "pNew" is a pointer to the hash table that is to be initialized.
24825 */
24826 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
24827   assert( pNew!=0 );
24828   pNew->first = 0;
24829   pNew->count = 0;
24830   pNew->htsize = 0;
24831   pNew->ht = 0;
24832 }
24833 
24834 /* Remove all entries from a hash table.  Reclaim all memory.
24835 ** Call this routine to delete a hash table or to reset a hash table
24836 ** to the empty state.
24837 */
24838 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
24839   HashElem *elem;         /* For looping over all elements of the table */
24840 
24841   assert( pH!=0 );
24842   elem = pH->first;
24843   pH->first = 0;
24844   sqlite3_free(pH->ht);
24845   pH->ht = 0;
24846   pH->htsize = 0;
24847   while( elem ){
24848     HashElem *next_elem = elem->next;
24849     sqlite3_free(elem);
24850     elem = next_elem;
24851   }
24852   pH->count = 0;
24853 }
24854 
24855 /*
24856 ** The hashing function.
24857 */
24858 static unsigned int strHash(const char *z){
24859   unsigned int h = 0;
24860   unsigned char c;
24861   while( (c = (unsigned char)*z++)!=0 ){
24862     h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
24863   }
24864   return h;
24865 }
24866 
24867 
24868 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
24869 ** insert pNew into the pEntry hash bucket.
24870 */
24871 static void insertElement(
24872   Hash *pH,              /* The complete hash table */
24873   struct _ht *pEntry,    /* The entry into which pNew is inserted */
24874   HashElem *pNew         /* The element to be inserted */
24875 ){
24876   HashElem *pHead;       /* First element already in pEntry */
24877   if( pEntry ){
24878     pHead = pEntry->count ? pEntry->chain : 0;
24879     pEntry->count++;
24880     pEntry->chain = pNew;
24881   }else{
24882     pHead = 0;
24883   }
24884   if( pHead ){
24885     pNew->next = pHead;
24886     pNew->prev = pHead->prev;
24887     if( pHead->prev ){ pHead->prev->next = pNew; }
24888     else             { pH->first = pNew; }
24889     pHead->prev = pNew;
24890   }else{
24891     pNew->next = pH->first;
24892     if( pH->first ){ pH->first->prev = pNew; }
24893     pNew->prev = 0;
24894     pH->first = pNew;
24895   }
24896 }
24897 
24898 
24899 /* Resize the hash table so that it cantains "new_size" buckets.
24900 **
24901 ** The hash table might fail to resize if sqlite3_malloc() fails or
24902 ** if the new size is the same as the prior size.
24903 ** Return TRUE if the resize occurs and false if not.
24904 */
24905 static int rehash(Hash *pH, unsigned int new_size){
24906   struct _ht *new_ht;            /* The new hash table */
24907   HashElem *elem, *next_elem;    /* For looping over existing elements */
24908 
24909 #if SQLITE_MALLOC_SOFT_LIMIT>0
24910   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
24911     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
24912   }
24913   if( new_size==pH->htsize ) return 0;
24914 #endif
24915 
24916   /* The inability to allocates space for a larger hash table is
24917   ** a performance hit but it is not a fatal error.  So mark the
24918   ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
24919   ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
24920   ** only zeroes the requested number of bytes whereas this module will
24921   ** use the actual amount of space allocated for the hash table (which
24922   ** may be larger than the requested amount).
24923   */
24924   sqlite3BeginBenignMalloc();
24925   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
24926   sqlite3EndBenignMalloc();
24927 
24928   if( new_ht==0 ) return 0;
24929   sqlite3_free(pH->ht);
24930   pH->ht = new_ht;
24931   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
24932   memset(new_ht, 0, new_size*sizeof(struct _ht));
24933   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
24934     unsigned int h = strHash(elem->pKey) % new_size;
24935     next_elem = elem->next;
24936     insertElement(pH, &new_ht[h], elem);
24937   }
24938   return 1;
24939 }
24940 
24941 /* This function (for internal use only) locates an element in an
24942 ** hash table that matches the given key.  The hash for this key is
24943 ** also computed and returned in the *pH parameter.
24944 */
24945 static HashElem *findElementWithHash(
24946   const Hash *pH,     /* The pH to be searched */
24947   const char *pKey,   /* The key we are searching for */
24948   unsigned int *pHash /* Write the hash value here */
24949 ){
24950   HashElem *elem;                /* Used to loop thru the element list */
24951   int count;                     /* Number of elements left to test */
24952   unsigned int h;                /* The computed hash */
24953 
24954   if( pH->ht ){
24955     struct _ht *pEntry;
24956     h = strHash(pKey) % pH->htsize;
24957     pEntry = &pH->ht[h];
24958     elem = pEntry->chain;
24959     count = pEntry->count;
24960   }else{
24961     h = 0;
24962     elem = pH->first;
24963     count = pH->count;
24964   }
24965   *pHash = h;
24966   while( count-- ){
24967     assert( elem!=0 );
24968     if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
24969       return elem;
24970     }
24971     elem = elem->next;
24972   }
24973   return 0;
24974 }
24975 
24976 /* Remove a single entry from the hash table given a pointer to that
24977 ** element and a hash on the element's key.
24978 */
24979 static void removeElementGivenHash(
24980   Hash *pH,         /* The pH containing "elem" */
24981   HashElem* elem,   /* The element to be removed from the pH */
24982   unsigned int h    /* Hash value for the element */
24983 ){
24984   struct _ht *pEntry;
24985   if( elem->prev ){
24986     elem->prev->next = elem->next;
24987   }else{
24988     pH->first = elem->next;
24989   }
24990   if( elem->next ){
24991     elem->next->prev = elem->prev;
24992   }
24993   if( pH->ht ){
24994     pEntry = &pH->ht[h];
24995     if( pEntry->chain==elem ){
24996       pEntry->chain = elem->next;
24997     }
24998     pEntry->count--;
24999     assert( pEntry->count>=0 );
25000   }
25001   sqlite3_free( elem );
25002   pH->count--;
25003   if( pH->count==0 ){
25004     assert( pH->first==0 );
25005     assert( pH->count==0 );
25006     sqlite3HashClear(pH);
25007   }
25008 }
25009 
25010 /* Attempt to locate an element of the hash table pH with a key
25011 ** that matches pKey.  Return the data for this element if it is
25012 ** found, or NULL if there is no match.
25013 */
25014 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
25015   HashElem *elem;    /* The element that matches key */
25016   unsigned int h;    /* A hash on key */
25017 
25018   assert( pH!=0 );
25019   assert( pKey!=0 );
25020   elem = findElementWithHash(pH, pKey, &h);
25021   return elem ? elem->data : 0;
25022 }
25023 
25024 /* Insert an element into the hash table pH.  The key is pKey
25025 ** and the data is "data".
25026 **
25027 ** If no element exists with a matching key, then a new
25028 ** element is created and NULL is returned.
25029 **
25030 ** If another element already exists with the same key, then the
25031 ** new data replaces the old data and the old data is returned.
25032 ** The key is not copied in this instance.  If a malloc fails, then
25033 ** the new data is returned and the hash table is unchanged.
25034 **
25035 ** If the "data" parameter to this function is NULL, then the
25036 ** element corresponding to "key" is removed from the hash table.
25037 */
25038 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
25039   unsigned int h;       /* the hash of the key modulo hash table size */
25040   HashElem *elem;       /* Used to loop thru the element list */
25041   HashElem *new_elem;   /* New element added to the pH */
25042 
25043   assert( pH!=0 );
25044   assert( pKey!=0 );
25045   elem = findElementWithHash(pH,pKey,&h);
25046   if( elem ){
25047     void *old_data = elem->data;
25048     if( data==0 ){
25049       removeElementGivenHash(pH,elem,h);
25050     }else{
25051       elem->data = data;
25052       elem->pKey = pKey;
25053     }
25054     return old_data;
25055   }
25056   if( data==0 ) return 0;
25057   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
25058   if( new_elem==0 ) return data;
25059   new_elem->pKey = pKey;
25060   new_elem->data = data;
25061   pH->count++;
25062   if( pH->count>=10 && pH->count > 2*pH->htsize ){
25063     if( rehash(pH, pH->count*2) ){
25064       assert( pH->htsize>0 );
25065       h = strHash(pKey) % pH->htsize;
25066     }
25067   }
25068   insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
25069   return 0;
25070 }
25071 
25072 /************** End of hash.c ************************************************/
25073 /************** Begin file opcodes.c *****************************************/
25074 /* Automatically generated.  Do not edit */
25075 /* See the mkopcodec.awk script for details. */
25076 #if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
25077 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
25078 # define OpHelp(X) "\0" X
25079 #else
25080 # define OpHelp(X)
25081 #endif
25082 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
25083  static const char *const azName[] = { "?",
25084      /*   1 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
25085      /*   2 */ "Savepoint"        OpHelp(""),
25086      /*   3 */ "AutoCommit"       OpHelp(""),
25087      /*   4 */ "Transaction"      OpHelp(""),
25088      /*   5 */ "SorterNext"       OpHelp(""),
25089      /*   6 */ "PrevIfOpen"       OpHelp(""),
25090      /*   7 */ "NextIfOpen"       OpHelp(""),
25091      /*   8 */ "Prev"             OpHelp(""),
25092      /*   9 */ "Next"             OpHelp(""),
25093      /*  10 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
25094      /*  11 */ "Checkpoint"       OpHelp(""),
25095      /*  12 */ "JournalMode"      OpHelp(""),
25096      /*  13 */ "Vacuum"           OpHelp(""),
25097      /*  14 */ "VFilter"          OpHelp("iplan=r[P3] zplan='P4'"),
25098      /*  15 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
25099      /*  16 */ "Goto"             OpHelp(""),
25100      /*  17 */ "Gosub"            OpHelp(""),
25101      /*  18 */ "Return"           OpHelp(""),
25102      /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
25103      /*  20 */ "InitCoroutine"    OpHelp(""),
25104      /*  21 */ "EndCoroutine"     OpHelp(""),
25105      /*  22 */ "Yield"            OpHelp(""),
25106      /*  23 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
25107      /*  24 */ "Halt"             OpHelp(""),
25108      /*  25 */ "Integer"          OpHelp("r[P2]=P1"),
25109      /*  26 */ "Int64"            OpHelp("r[P2]=P4"),
25110      /*  27 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
25111      /*  28 */ "Null"             OpHelp("r[P2..P3]=NULL"),
25112      /*  29 */ "SoftNull"         OpHelp("r[P1]=NULL"),
25113      /*  30 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
25114      /*  31 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
25115      /*  32 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
25116      /*  33 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
25117      /*  34 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
25118      /*  35 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
25119      /*  36 */ "CollSeq"          OpHelp(""),
25120      /*  37 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
25121      /*  38 */ "MustBeInt"        OpHelp(""),
25122      /*  39 */ "RealAffinity"     OpHelp(""),
25123      /*  40 */ "Cast"             OpHelp("affinity(r[P1])"),
25124      /*  41 */ "Permutation"      OpHelp(""),
25125      /*  42 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
25126      /*  43 */ "Jump"             OpHelp(""),
25127      /*  44 */ "Once"             OpHelp(""),
25128      /*  45 */ "If"               OpHelp(""),
25129      /*  46 */ "IfNot"            OpHelp(""),
25130      /*  47 */ "Column"           OpHelp("r[P3]=PX"),
25131      /*  48 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
25132      /*  49 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
25133      /*  50 */ "Count"            OpHelp("r[P2]=count()"),
25134      /*  51 */ "ReadCookie"       OpHelp(""),
25135      /*  52 */ "SetCookie"        OpHelp(""),
25136      /*  53 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
25137      /*  54 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
25138      /*  55 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
25139      /*  56 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
25140      /*  57 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
25141      /*  58 */ "SorterOpen"       OpHelp(""),
25142      /*  59 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
25143      /*  60 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
25144      /*  61 */ "Close"            OpHelp(""),
25145      /*  62 */ "SeekLT"           OpHelp("key=r[P3@P4]"),
25146      /*  63 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
25147      /*  64 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
25148      /*  65 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
25149      /*  66 */ "Seek"             OpHelp("intkey=r[P2]"),
25150      /*  67 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
25151      /*  68 */ "NotFound"         OpHelp("key=r[P3@P4]"),
25152      /*  69 */ "Found"            OpHelp("key=r[P3@P4]"),
25153      /*  70 */ "NotExists"        OpHelp("intkey=r[P3]"),
25154      /*  71 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
25155      /*  72 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
25156      /*  73 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
25157      /*  74 */ "NewRowid"         OpHelp("r[P2]=rowid"),
25158      /*  75 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
25159      /*  76 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
25160      /*  77 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
25161      /*  78 */ "Ne"               OpHelp("if r[P1]!=r[P3] goto P2"),
25162      /*  79 */ "Eq"               OpHelp("if r[P1]==r[P3] goto P2"),
25163      /*  80 */ "Gt"               OpHelp("if r[P1]>r[P3] goto P2"),
25164      /*  81 */ "Le"               OpHelp("if r[P1]<=r[P3] goto P2"),
25165      /*  82 */ "Lt"               OpHelp("if r[P1]<r[P3] goto P2"),
25166      /*  83 */ "Ge"               OpHelp("if r[P1]>=r[P3] goto P2"),
25167      /*  84 */ "InsertInt"        OpHelp("intkey=P3 data=r[P2]"),
25168      /*  85 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
25169      /*  86 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
25170      /*  87 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
25171      /*  88 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
25172      /*  89 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
25173      /*  90 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
25174      /*  91 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
25175      /*  92 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
25176      /*  93 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
25177      /*  94 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
25178      /*  95 */ "Delete"           OpHelp(""),
25179      /*  96 */ "BitNot"           OpHelp("r[P1]= ~r[P1]"),
25180      /*  97 */ "String8"          OpHelp("r[P2]='P4'"),
25181      /*  98 */ "ResetCount"       OpHelp(""),
25182      /*  99 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
25183      /* 100 */ "SorterData"       OpHelp("r[P2]=data"),
25184      /* 101 */ "RowKey"           OpHelp("r[P2]=key"),
25185      /* 102 */ "RowData"          OpHelp("r[P2]=data"),
25186      /* 103 */ "Rowid"            OpHelp("r[P2]=rowid"),
25187      /* 104 */ "NullRow"          OpHelp(""),
25188      /* 105 */ "Last"             OpHelp(""),
25189      /* 106 */ "SorterSort"       OpHelp(""),
25190      /* 107 */ "Sort"             OpHelp(""),
25191      /* 108 */ "Rewind"           OpHelp(""),
25192      /* 109 */ "SorterInsert"     OpHelp(""),
25193      /* 110 */ "IdxInsert"        OpHelp("key=r[P2]"),
25194      /* 111 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
25195      /* 112 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
25196      /* 113 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
25197      /* 114 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
25198      /* 115 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
25199      /* 116 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
25200      /* 117 */ "Destroy"          OpHelp(""),
25201      /* 118 */ "Clear"            OpHelp(""),
25202      /* 119 */ "ResetSorter"      OpHelp(""),
25203      /* 120 */ "CreateIndex"      OpHelp("r[P2]=root iDb=P1"),
25204      /* 121 */ "CreateTable"      OpHelp("r[P2]=root iDb=P1"),
25205      /* 122 */ "ParseSchema"      OpHelp(""),
25206      /* 123 */ "LoadAnalysis"     OpHelp(""),
25207      /* 124 */ "DropTable"        OpHelp(""),
25208      /* 125 */ "DropIndex"        OpHelp(""),
25209      /* 126 */ "DropTrigger"      OpHelp(""),
25210      /* 127 */ "IntegrityCk"      OpHelp(""),
25211      /* 128 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
25212      /* 129 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
25213      /* 130 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
25214      /* 131 */ "Program"          OpHelp(""),
25215      /* 132 */ "Param"            OpHelp(""),
25216      /* 133 */ "Real"             OpHelp("r[P2]=P4"),
25217      /* 134 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
25218      /* 135 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
25219      /* 136 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
25220      /* 137 */ "IfPos"            OpHelp("if r[P1]>0 goto P2"),
25221      /* 138 */ "IfNeg"            OpHelp("r[P1]+=P3, if r[P1]<0 goto P2"),
25222      /* 139 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]+=P3, goto P2"),
25223      /* 140 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
25224      /* 141 */ "JumpZeroIncr"     OpHelp("if (r[P1]++)==0 ) goto P2"),
25225      /* 142 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
25226      /* 143 */ "IncrVacuum"       OpHelp(""),
25227      /* 144 */ "Expire"           OpHelp(""),
25228      /* 145 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
25229      /* 146 */ "VBegin"           OpHelp(""),
25230      /* 147 */ "VCreate"          OpHelp(""),
25231      /* 148 */ "VDestroy"         OpHelp(""),
25232      /* 149 */ "VOpen"            OpHelp(""),
25233      /* 150 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
25234      /* 151 */ "VNext"            OpHelp(""),
25235      /* 152 */ "VRename"          OpHelp(""),
25236      /* 153 */ "Pagecount"        OpHelp(""),
25237      /* 154 */ "MaxPgcnt"         OpHelp(""),
25238      /* 155 */ "Init"             OpHelp("Start at P2"),
25239      /* 156 */ "Noop"             OpHelp(""),
25240      /* 157 */ "Explain"          OpHelp(""),
25241   };
25242   return azName[i];
25243 }
25244 #endif
25245 
25246 /************** End of opcodes.c *********************************************/
25247 /************** Begin file os_unix.c *****************************************/
25248 /*
25249 ** 2004 May 22
25250 **
25251 ** The author disclaims copyright to this source code.  In place of
25252 ** a legal notice, here is a blessing:
25253 **
25254 **    May you do good and not evil.
25255 **    May you find forgiveness for yourself and forgive others.
25256 **    May you share freely, never taking more than you give.
25257 **
25258 ******************************************************************************
25259 **
25260 ** This file contains the VFS implementation for unix-like operating systems
25261 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
25262 **
25263 ** There are actually several different VFS implementations in this file.
25264 ** The differences are in the way that file locking is done.  The default
25265 ** implementation uses Posix Advisory Locks.  Alternative implementations
25266 ** use flock(), dot-files, various proprietary locking schemas, or simply
25267 ** skip locking all together.
25268 **
25269 ** This source file is organized into divisions where the logic for various
25270 ** subfunctions is contained within the appropriate division.  PLEASE
25271 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
25272 ** in the correct division and should be clearly labeled.
25273 **
25274 ** The layout of divisions is as follows:
25275 **
25276 **   *  General-purpose declarations and utility functions.
25277 **   *  Unique file ID logic used by VxWorks.
25278 **   *  Various locking primitive implementations (all except proxy locking):
25279 **      + for Posix Advisory Locks
25280 **      + for no-op locks
25281 **      + for dot-file locks
25282 **      + for flock() locking
25283 **      + for named semaphore locks (VxWorks only)
25284 **      + for AFP filesystem locks (MacOSX only)
25285 **   *  sqlite3_file methods not associated with locking.
25286 **   *  Definitions of sqlite3_io_methods objects for all locking
25287 **      methods plus "finder" functions for each locking method.
25288 **   *  sqlite3_vfs method implementations.
25289 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
25290 **   *  Definitions of sqlite3_vfs objects for all locking methods
25291 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
25292 */
25293 #if SQLITE_OS_UNIX              /* This file is used on unix only */
25294 
25295 /*
25296 ** There are various methods for file locking used for concurrency
25297 ** control:
25298 **
25299 **   1. POSIX locking (the default),
25300 **   2. No locking,
25301 **   3. Dot-file locking,
25302 **   4. flock() locking,
25303 **   5. AFP locking (OSX only),
25304 **   6. Named POSIX semaphores (VXWorks only),
25305 **   7. proxy locking. (OSX only)
25306 **
25307 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
25308 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
25309 ** selection of the appropriate locking style based on the filesystem
25310 ** where the database is located.
25311 */
25312 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
25313 #  if defined(__APPLE__)
25314 #    define SQLITE_ENABLE_LOCKING_STYLE 1
25315 #  else
25316 #    define SQLITE_ENABLE_LOCKING_STYLE 0
25317 #  endif
25318 #endif
25319 
25320 /*
25321 ** standard include files.
25322 */
25323 #include <sys/types.h>
25324 #include <sys/stat.h>
25325 #include <fcntl.h>
25326 #include <unistd.h>
25327 /* #include <time.h> */
25328 #include <sys/time.h>
25329 #include <errno.h>
25330 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
25331 # include <sys/mman.h>
25332 #endif
25333 
25334 #if SQLITE_ENABLE_LOCKING_STYLE
25335 # include <sys/ioctl.h>
25336 # include <sys/file.h>
25337 # include <sys/param.h>
25338 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
25339 
25340 #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
25341                            (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
25342 #  if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
25343        && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
25344 #    define HAVE_GETHOSTUUID 1
25345 #  else
25346 #    warning "gethostuuid() is disabled."
25347 #  endif
25348 #endif
25349 
25350 
25351 #if OS_VXWORKS
25352 /* # include <sys/ioctl.h> */
25353 # include <semaphore.h>
25354 # include <limits.h>
25355 #endif /* OS_VXWORKS */
25356 
25357 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
25358 # include <sys/mount.h>
25359 #endif
25360 
25361 #ifdef HAVE_UTIME
25362 # include <utime.h>
25363 #endif
25364 
25365 /*
25366 ** Allowed values of unixFile.fsFlags
25367 */
25368 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
25369 
25370 /*
25371 ** If we are to be thread-safe, include the pthreads header and define
25372 ** the SQLITE_UNIX_THREADS macro.
25373 */
25374 #if SQLITE_THREADSAFE
25375 /* # include <pthread.h> */
25376 # define SQLITE_UNIX_THREADS 1
25377 #endif
25378 
25379 /*
25380 ** Default permissions when creating a new file
25381 */
25382 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
25383 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
25384 #endif
25385 
25386 /*
25387 ** Default permissions when creating auto proxy dir
25388 */
25389 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
25390 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
25391 #endif
25392 
25393 /*
25394 ** Maximum supported path-length.
25395 */
25396 #define MAX_PATHNAME 512
25397 
25398 /* Always cast the getpid() return type for compatibility with
25399 ** kernel modules in VxWorks. */
25400 #define osGetpid(X) (pid_t)getpid()
25401 
25402 /*
25403 ** Only set the lastErrno if the error code is a real error and not
25404 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
25405 */
25406 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
25407 
25408 /* Forward references */
25409 typedef struct unixShm unixShm;               /* Connection shared memory */
25410 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
25411 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
25412 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
25413 
25414 /*
25415 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
25416 ** cannot be closed immediately. In these cases, instances of the following
25417 ** structure are used to store the file descriptor while waiting for an
25418 ** opportunity to either close or reuse it.
25419 */
25420 struct UnixUnusedFd {
25421   int fd;                   /* File descriptor to close */
25422   int flags;                /* Flags this file descriptor was opened with */
25423   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
25424 };
25425 
25426 /*
25427 ** The unixFile structure is subclass of sqlite3_file specific to the unix
25428 ** VFS implementations.
25429 */
25430 typedef struct unixFile unixFile;
25431 struct unixFile {
25432   sqlite3_io_methods const *pMethod;  /* Always the first entry */
25433   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
25434   unixInodeInfo *pInode;              /* Info about locks on this inode */
25435   int h;                              /* The file descriptor */
25436   unsigned char eFileLock;            /* The type of lock held on this fd */
25437   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
25438   int lastErrno;                      /* The unix errno from last I/O error */
25439   void *lockingContext;               /* Locking style specific state */
25440   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
25441   const char *zPath;                  /* Name of the file */
25442   unixShm *pShm;                      /* Shared memory segment information */
25443   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
25444 #if SQLITE_MAX_MMAP_SIZE>0
25445   int nFetchOut;                      /* Number of outstanding xFetch refs */
25446   sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
25447   sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
25448   sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
25449   void *pMapRegion;                   /* Memory mapped region */
25450 #endif
25451 #ifdef __QNXNTO__
25452   int sectorSize;                     /* Device sector size */
25453   int deviceCharacteristics;          /* Precomputed device characteristics */
25454 #endif
25455 #if SQLITE_ENABLE_LOCKING_STYLE
25456   int openFlags;                      /* The flags specified at open() */
25457 #endif
25458 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
25459   unsigned fsFlags;                   /* cached details from statfs() */
25460 #endif
25461 #if OS_VXWORKS
25462   struct vxworksFileId *pId;          /* Unique file ID */
25463 #endif
25464 #ifdef SQLITE_DEBUG
25465   /* The next group of variables are used to track whether or not the
25466   ** transaction counter in bytes 24-27 of database files are updated
25467   ** whenever any part of the database changes.  An assertion fault will
25468   ** occur if a file is updated without also updating the transaction
25469   ** counter.  This test is made to avoid new problems similar to the
25470   ** one described by ticket #3584.
25471   */
25472   unsigned char transCntrChng;   /* True if the transaction counter changed */
25473   unsigned char dbUpdate;        /* True if any part of database file changed */
25474   unsigned char inNormalWrite;   /* True if in a normal write operation */
25475 
25476 #endif
25477 
25478 #ifdef SQLITE_TEST
25479   /* In test mode, increase the size of this structure a bit so that
25480   ** it is larger than the struct CrashFile defined in test6.c.
25481   */
25482   char aPadding[32];
25483 #endif
25484 };
25485 
25486 /* This variable holds the process id (pid) from when the xRandomness()
25487 ** method was called.  If xOpen() is called from a different process id,
25488 ** indicating that a fork() has occurred, the PRNG will be reset.
25489 */
25490 static pid_t randomnessPid = 0;
25491 
25492 /*
25493 ** Allowed values for the unixFile.ctrlFlags bitmask:
25494 */
25495 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
25496 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
25497 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
25498 #ifndef SQLITE_DISABLE_DIRSYNC
25499 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
25500 #else
25501 # define UNIXFILE_DIRSYNC    0x00
25502 #endif
25503 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
25504 #define UNIXFILE_DELETE      0x20     /* Delete on close */
25505 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
25506 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
25507 #define UNIXFILE_WARNED    0x0100     /* verifyDbFile() warnings issued */
25508 #define UNIXFILE_BLOCK     0x0200     /* Next SHM lock might block */
25509 
25510 /*
25511 ** Include code that is common to all os_*.c files
25512 */
25513 /************** Include os_common.h in the middle of os_unix.c ***************/
25514 /************** Begin file os_common.h ***************************************/
25515 /*
25516 ** 2004 May 22
25517 **
25518 ** The author disclaims copyright to this source code.  In place of
25519 ** a legal notice, here is a blessing:
25520 **
25521 **    May you do good and not evil.
25522 **    May you find forgiveness for yourself and forgive others.
25523 **    May you share freely, never taking more than you give.
25524 **
25525 ******************************************************************************
25526 **
25527 ** This file contains macros and a little bit of code that is common to
25528 ** all of the platform-specific files (os_*.c) and is #included into those
25529 ** files.
25530 **
25531 ** This file should be #included by the os_*.c files only.  It is not a
25532 ** general purpose header file.
25533 */
25534 #ifndef _OS_COMMON_H_
25535 #define _OS_COMMON_H_
25536 
25537 /*
25538 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
25539 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
25540 ** switch.  The following code should catch this problem at compile-time.
25541 */
25542 #ifdef MEMORY_DEBUG
25543 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
25544 #endif
25545 
25546 /*
25547 ** Macros for performance tracing.  Normally turned off.  Only works
25548 ** on i486 hardware.
25549 */
25550 #ifdef SQLITE_PERFORMANCE_TRACE
25551 
25552 /*
25553 ** hwtime.h contains inline assembler code for implementing
25554 ** high-performance timing routines.
25555 */
25556 /************** Include hwtime.h in the middle of os_common.h ****************/
25557 /************** Begin file hwtime.h ******************************************/
25558 /*
25559 ** 2008 May 27
25560 **
25561 ** The author disclaims copyright to this source code.  In place of
25562 ** a legal notice, here is a blessing:
25563 **
25564 **    May you do good and not evil.
25565 **    May you find forgiveness for yourself and forgive others.
25566 **    May you share freely, never taking more than you give.
25567 **
25568 ******************************************************************************
25569 **
25570 ** This file contains inline asm code for retrieving "high-performance"
25571 ** counters for x86 class CPUs.
25572 */
25573 #ifndef _HWTIME_H_
25574 #define _HWTIME_H_
25575 
25576 /*
25577 ** The following routine only works on pentium-class (or newer) processors.
25578 ** It uses the RDTSC opcode to read the cycle count value out of the
25579 ** processor and returns that value.  This can be used for high-res
25580 ** profiling.
25581 */
25582 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
25583       (defined(i386) || defined(__i386__) || defined(_M_IX86))
25584 
25585   #if defined(__GNUC__)
25586 
25587   __inline__ sqlite_uint64 sqlite3Hwtime(void){
25588      unsigned int lo, hi;
25589      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
25590      return (sqlite_uint64)hi << 32 | lo;
25591   }
25592 
25593   #elif defined(_MSC_VER)
25594 
25595   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
25596      __asm {
25597         rdtsc
25598         ret       ; return value at EDX:EAX
25599      }
25600   }
25601 
25602   #endif
25603 
25604 #elif (defined(__GNUC__) && defined(__x86_64__))
25605 
25606   __inline__ sqlite_uint64 sqlite3Hwtime(void){
25607       unsigned long val;
25608       __asm__ __volatile__ ("rdtsc" : "=A" (val));
25609       return val;
25610   }
25611 
25612 #elif (defined(__GNUC__) && defined(__ppc__))
25613 
25614   __inline__ sqlite_uint64 sqlite3Hwtime(void){
25615       unsigned long long retval;
25616       unsigned long junk;
25617       __asm__ __volatile__ ("\n\
25618           1:      mftbu   %1\n\
25619                   mftb    %L0\n\
25620                   mftbu   %0\n\
25621                   cmpw    %0,%1\n\
25622                   bne     1b"
25623                   : "=r" (retval), "=r" (junk));
25624       return retval;
25625   }
25626 
25627 #else
25628 
25629   #error Need implementation of sqlite3Hwtime() for your platform.
25630 
25631   /*
25632   ** To compile without implementing sqlite3Hwtime() for your platform,
25633   ** you can remove the above #error and use the following
25634   ** stub function.  You will lose timing support for many
25635   ** of the debugging and testing utilities, but it should at
25636   ** least compile and run.
25637   */
25638 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
25639 
25640 #endif
25641 
25642 #endif /* !defined(_HWTIME_H_) */
25643 
25644 /************** End of hwtime.h **********************************************/
25645 /************** Continuing where we left off in os_common.h ******************/
25646 
25647 static sqlite_uint64 g_start;
25648 static sqlite_uint64 g_elapsed;
25649 #define TIMER_START       g_start=sqlite3Hwtime()
25650 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
25651 #define TIMER_ELAPSED     g_elapsed
25652 #else
25653 #define TIMER_START
25654 #define TIMER_END
25655 #define TIMER_ELAPSED     ((sqlite_uint64)0)
25656 #endif
25657 
25658 /*
25659 ** If we compile with the SQLITE_TEST macro set, then the following block
25660 ** of code will give us the ability to simulate a disk I/O error.  This
25661 ** is used for testing the I/O recovery logic.
25662 */
25663 #ifdef SQLITE_TEST
25664 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
25665 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
25666 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
25667 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
25668 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
25669 SQLITE_API int sqlite3_diskfull_pending = 0;
25670 SQLITE_API int sqlite3_diskfull = 0;
25671 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
25672 #define SimulateIOError(CODE)  \
25673   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
25674        || sqlite3_io_error_pending-- == 1 )  \
25675               { local_ioerr(); CODE; }
25676 static void local_ioerr(){
25677   IOTRACE(("IOERR\n"));
25678   sqlite3_io_error_hit++;
25679   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
25680 }
25681 #define SimulateDiskfullError(CODE) \
25682    if( sqlite3_diskfull_pending ){ \
25683      if( sqlite3_diskfull_pending == 1 ){ \
25684        local_ioerr(); \
25685        sqlite3_diskfull = 1; \
25686        sqlite3_io_error_hit = 1; \
25687        CODE; \
25688      }else{ \
25689        sqlite3_diskfull_pending--; \
25690      } \
25691    }
25692 #else
25693 #define SimulateIOErrorBenign(X)
25694 #define SimulateIOError(A)
25695 #define SimulateDiskfullError(A)
25696 #endif
25697 
25698 /*
25699 ** When testing, keep a count of the number of open files.
25700 */
25701 #ifdef SQLITE_TEST
25702 SQLITE_API int sqlite3_open_file_count = 0;
25703 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
25704 #else
25705 #define OpenCounter(X)
25706 #endif
25707 
25708 #endif /* !defined(_OS_COMMON_H_) */
25709 
25710 /************** End of os_common.h *******************************************/
25711 /************** Continuing where we left off in os_unix.c ********************/
25712 
25713 /*
25714 ** Define various macros that are missing from some systems.
25715 */
25716 #ifndef O_LARGEFILE
25717 # define O_LARGEFILE 0
25718 #endif
25719 #ifdef SQLITE_DISABLE_LFS
25720 # undef O_LARGEFILE
25721 # define O_LARGEFILE 0
25722 #endif
25723 #ifndef O_NOFOLLOW
25724 # define O_NOFOLLOW 0
25725 #endif
25726 #ifndef O_BINARY
25727 # define O_BINARY 0
25728 #endif
25729 
25730 /*
25731 ** The threadid macro resolves to the thread-id or to 0.  Used for
25732 ** testing and debugging only.
25733 */
25734 #if SQLITE_THREADSAFE
25735 #define threadid pthread_self()
25736 #else
25737 #define threadid 0
25738 #endif
25739 
25740 /*
25741 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
25742 */
25743 #if !defined(HAVE_MREMAP)
25744 # if defined(__linux__) && defined(_GNU_SOURCE)
25745 #  define HAVE_MREMAP 1
25746 # else
25747 #  define HAVE_MREMAP 0
25748 # endif
25749 #endif
25750 
25751 /*
25752 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
25753 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
25754 */
25755 #ifdef __ANDROID__
25756 # define lseek lseek64
25757 #endif
25758 
25759 /*
25760 ** Different Unix systems declare open() in different ways.  Same use
25761 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
25762 ** The difference is important when using a pointer to the function.
25763 **
25764 ** The safest way to deal with the problem is to always use this wrapper
25765 ** which always has the same well-defined interface.
25766 */
25767 static int posixOpen(const char *zFile, int flags, int mode){
25768   return open(zFile, flags, mode);
25769 }
25770 
25771 /*
25772 ** On some systems, calls to fchown() will trigger a message in a security
25773 ** log if they come from non-root processes.  So avoid calling fchown() if
25774 ** we are not running as root.
25775 */
25776 static int posixFchown(int fd, uid_t uid, gid_t gid){
25777 #if OS_VXWORKS
25778   return 0;
25779 #else
25780   return geteuid() ? 0 : fchown(fd,uid,gid);
25781 #endif
25782 }
25783 
25784 /* Forward reference */
25785 static int openDirectory(const char*, int*);
25786 static int unixGetpagesize(void);
25787 
25788 /*
25789 ** Many system calls are accessed through pointer-to-functions so that
25790 ** they may be overridden at runtime to facilitate fault injection during
25791 ** testing and sandboxing.  The following array holds the names and pointers
25792 ** to all overrideable system calls.
25793 */
25794 static struct unix_syscall {
25795   const char *zName;            /* Name of the system call */
25796   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
25797   sqlite3_syscall_ptr pDefault; /* Default value */
25798 } aSyscall[] = {
25799   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
25800 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
25801 
25802   { "close",        (sqlite3_syscall_ptr)close,      0  },
25803 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
25804 
25805   { "access",       (sqlite3_syscall_ptr)access,     0  },
25806 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
25807 
25808   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
25809 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
25810 
25811   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
25812 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
25813 
25814 /*
25815 ** The DJGPP compiler environment looks mostly like Unix, but it
25816 ** lacks the fcntl() system call.  So redefine fcntl() to be something
25817 ** that always succeeds.  This means that locking does not occur under
25818 ** DJGPP.  But it is DOS - what did you expect?
25819 */
25820 #ifdef __DJGPP__
25821   { "fstat",        0,                 0  },
25822 #define osFstat(a,b,c)    0
25823 #else
25824   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
25825 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
25826 #endif
25827 
25828   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
25829 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
25830 
25831   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
25832 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
25833 
25834   { "read",         (sqlite3_syscall_ptr)read,       0  },
25835 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
25836 
25837 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
25838   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
25839 #else
25840   { "pread",        (sqlite3_syscall_ptr)0,          0  },
25841 #endif
25842 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
25843 
25844 #if defined(USE_PREAD64)
25845   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
25846 #else
25847   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
25848 #endif
25849 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
25850 
25851   { "write",        (sqlite3_syscall_ptr)write,      0  },
25852 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
25853 
25854 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
25855   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
25856 #else
25857   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
25858 #endif
25859 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
25860                     aSyscall[12].pCurrent)
25861 
25862 #if defined(USE_PREAD64)
25863   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
25864 #else
25865   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
25866 #endif
25867 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
25868                     aSyscall[13].pCurrent)
25869 
25870   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
25871 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
25872 
25873 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
25874   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
25875 #else
25876   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
25877 #endif
25878 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
25879 
25880   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
25881 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
25882 
25883   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
25884 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
25885 
25886   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
25887 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
25888 
25889   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
25890 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
25891 
25892   { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
25893 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
25894 
25895 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
25896   { "mmap",       (sqlite3_syscall_ptr)mmap,     0 },
25897 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
25898 
25899   { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
25900 #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
25901 
25902 #if HAVE_MREMAP
25903   { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
25904 #else
25905   { "mremap",       (sqlite3_syscall_ptr)0,               0 },
25906 #endif
25907 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
25908   { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
25909 #define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
25910 
25911 #endif
25912 
25913 }; /* End of the overrideable system calls */
25914 
25915 /*
25916 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
25917 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
25918 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
25919 ** system call named zName.
25920 */
25921 static int unixSetSystemCall(
25922   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
25923   const char *zName,            /* Name of system call to override */
25924   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
25925 ){
25926   unsigned int i;
25927   int rc = SQLITE_NOTFOUND;
25928 
25929   UNUSED_PARAMETER(pNotUsed);
25930   if( zName==0 ){
25931     /* If no zName is given, restore all system calls to their default
25932     ** settings and return NULL
25933     */
25934     rc = SQLITE_OK;
25935     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25936       if( aSyscall[i].pDefault ){
25937         aSyscall[i].pCurrent = aSyscall[i].pDefault;
25938       }
25939     }
25940   }else{
25941     /* If zName is specified, operate on only the one system call
25942     ** specified.
25943     */
25944     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25945       if( strcmp(zName, aSyscall[i].zName)==0 ){
25946         if( aSyscall[i].pDefault==0 ){
25947           aSyscall[i].pDefault = aSyscall[i].pCurrent;
25948         }
25949         rc = SQLITE_OK;
25950         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
25951         aSyscall[i].pCurrent = pNewFunc;
25952         break;
25953       }
25954     }
25955   }
25956   return rc;
25957 }
25958 
25959 /*
25960 ** Return the value of a system call.  Return NULL if zName is not a
25961 ** recognized system call name.  NULL is also returned if the system call
25962 ** is currently undefined.
25963 */
25964 static sqlite3_syscall_ptr unixGetSystemCall(
25965   sqlite3_vfs *pNotUsed,
25966   const char *zName
25967 ){
25968   unsigned int i;
25969 
25970   UNUSED_PARAMETER(pNotUsed);
25971   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25972     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
25973   }
25974   return 0;
25975 }
25976 
25977 /*
25978 ** Return the name of the first system call after zName.  If zName==NULL
25979 ** then return the name of the first system call.  Return NULL if zName
25980 ** is the last system call or if zName is not the name of a valid
25981 ** system call.
25982 */
25983 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
25984   int i = -1;
25985 
25986   UNUSED_PARAMETER(p);
25987   if( zName ){
25988     for(i=0; i<ArraySize(aSyscall)-1; i++){
25989       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
25990     }
25991   }
25992   for(i++; i<ArraySize(aSyscall); i++){
25993     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
25994   }
25995   return 0;
25996 }
25997 
25998 /*
25999 ** Do not accept any file descriptor less than this value, in order to avoid
26000 ** opening database file using file descriptors that are commonly used for
26001 ** standard input, output, and error.
26002 */
26003 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
26004 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
26005 #endif
26006 
26007 /*
26008 ** Invoke open().  Do so multiple times, until it either succeeds or
26009 ** fails for some reason other than EINTR.
26010 **
26011 ** If the file creation mode "m" is 0 then set it to the default for
26012 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
26013 ** 0644) as modified by the system umask.  If m is not 0, then
26014 ** make the file creation mode be exactly m ignoring the umask.
26015 **
26016 ** The m parameter will be non-zero only when creating -wal, -journal,
26017 ** and -shm files.  We want those files to have *exactly* the same
26018 ** permissions as their original database, unadulterated by the umask.
26019 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
26020 ** transaction crashes and leaves behind hot journals, then any
26021 ** process that is able to write to the database will also be able to
26022 ** recover the hot journals.
26023 */
26024 static int robust_open(const char *z, int f, mode_t m){
26025   int fd;
26026   mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
26027   while(1){
26028 #if defined(O_CLOEXEC)
26029     fd = osOpen(z,f|O_CLOEXEC,m2);
26030 #else
26031     fd = osOpen(z,f,m2);
26032 #endif
26033     if( fd<0 ){
26034       if( errno==EINTR ) continue;
26035       break;
26036     }
26037     if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
26038     osClose(fd);
26039     sqlite3_log(SQLITE_WARNING,
26040                 "attempt to open \"%s\" as file descriptor %d", z, fd);
26041     fd = -1;
26042     if( osOpen("/dev/null", f, m)<0 ) break;
26043   }
26044   if( fd>=0 ){
26045     if( m!=0 ){
26046       struct stat statbuf;
26047       if( osFstat(fd, &statbuf)==0
26048        && statbuf.st_size==0
26049        && (statbuf.st_mode&0777)!=m
26050       ){
26051         osFchmod(fd, m);
26052       }
26053     }
26054 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
26055     osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
26056 #endif
26057   }
26058   return fd;
26059 }
26060 
26061 /*
26062 ** Helper functions to obtain and relinquish the global mutex. The
26063 ** global mutex is used to protect the unixInodeInfo and
26064 ** vxworksFileId objects used by this file, all of which may be
26065 ** shared by multiple threads.
26066 **
26067 ** Function unixMutexHeld() is used to assert() that the global mutex
26068 ** is held when required. This function is only used as part of assert()
26069 ** statements. e.g.
26070 **
26071 **   unixEnterMutex()
26072 **     assert( unixMutexHeld() );
26073 **   unixEnterLeave()
26074 */
26075 static void unixEnterMutex(void){
26076   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
26077 }
26078 static void unixLeaveMutex(void){
26079   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
26080 }
26081 #ifdef SQLITE_DEBUG
26082 static int unixMutexHeld(void) {
26083   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
26084 }
26085 #endif
26086 
26087 
26088 #ifdef SQLITE_HAVE_OS_TRACE
26089 /*
26090 ** Helper function for printing out trace information from debugging
26091 ** binaries. This returns the string representation of the supplied
26092 ** integer lock-type.
26093 */
26094 static const char *azFileLock(int eFileLock){
26095   switch( eFileLock ){
26096     case NO_LOCK: return "NONE";
26097     case SHARED_LOCK: return "SHARED";
26098     case RESERVED_LOCK: return "RESERVED";
26099     case PENDING_LOCK: return "PENDING";
26100     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
26101   }
26102   return "ERROR";
26103 }
26104 #endif
26105 
26106 #ifdef SQLITE_LOCK_TRACE
26107 /*
26108 ** Print out information about all locking operations.
26109 **
26110 ** This routine is used for troubleshooting locks on multithreaded
26111 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
26112 ** command-line option on the compiler.  This code is normally
26113 ** turned off.
26114 */
26115 static int lockTrace(int fd, int op, struct flock *p){
26116   char *zOpName, *zType;
26117   int s;
26118   int savedErrno;
26119   if( op==F_GETLK ){
26120     zOpName = "GETLK";
26121   }else if( op==F_SETLK ){
26122     zOpName = "SETLK";
26123   }else{
26124     s = osFcntl(fd, op, p);
26125     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
26126     return s;
26127   }
26128   if( p->l_type==F_RDLCK ){
26129     zType = "RDLCK";
26130   }else if( p->l_type==F_WRLCK ){
26131     zType = "WRLCK";
26132   }else if( p->l_type==F_UNLCK ){
26133     zType = "UNLCK";
26134   }else{
26135     assert( 0 );
26136   }
26137   assert( p->l_whence==SEEK_SET );
26138   s = osFcntl(fd, op, p);
26139   savedErrno = errno;
26140   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
26141      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
26142      (int)p->l_pid, s);
26143   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
26144     struct flock l2;
26145     l2 = *p;
26146     osFcntl(fd, F_GETLK, &l2);
26147     if( l2.l_type==F_RDLCK ){
26148       zType = "RDLCK";
26149     }else if( l2.l_type==F_WRLCK ){
26150       zType = "WRLCK";
26151     }else if( l2.l_type==F_UNLCK ){
26152       zType = "UNLCK";
26153     }else{
26154       assert( 0 );
26155     }
26156     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
26157        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
26158   }
26159   errno = savedErrno;
26160   return s;
26161 }
26162 #undef osFcntl
26163 #define osFcntl lockTrace
26164 #endif /* SQLITE_LOCK_TRACE */
26165 
26166 /*
26167 ** Retry ftruncate() calls that fail due to EINTR
26168 **
26169 ** All calls to ftruncate() within this file should be made through
26170 ** this wrapper.  On the Android platform, bypassing the logic below
26171 ** could lead to a corrupt database.
26172 */
26173 static int robust_ftruncate(int h, sqlite3_int64 sz){
26174   int rc;
26175 #ifdef __ANDROID__
26176   /* On Android, ftruncate() always uses 32-bit offsets, even if
26177   ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
26178   ** truncate a file to any size larger than 2GiB. Silently ignore any
26179   ** such attempts.  */
26180   if( sz>(sqlite3_int64)0x7FFFFFFF ){
26181     rc = SQLITE_OK;
26182   }else
26183 #endif
26184   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
26185   return rc;
26186 }
26187 
26188 /*
26189 ** This routine translates a standard POSIX errno code into something
26190 ** useful to the clients of the sqlite3 functions.  Specifically, it is
26191 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
26192 ** and a variety of "please close the file descriptor NOW" errors into
26193 ** SQLITE_IOERR
26194 **
26195 ** Errors during initialization of locks, or file system support for locks,
26196 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
26197 */
26198 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
26199   switch (posixError) {
26200 #if 0
26201   /* At one point this code was not commented out. In theory, this branch
26202   ** should never be hit, as this function should only be called after
26203   ** a locking-related function (i.e. fcntl()) has returned non-zero with
26204   ** the value of errno as the first argument. Since a system call has failed,
26205   ** errno should be non-zero.
26206   **
26207   ** Despite this, if errno really is zero, we still don't want to return
26208   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
26209   ** propagated back to the caller. Commenting this branch out means errno==0
26210   ** will be handled by the "default:" case below.
26211   */
26212   case 0:
26213     return SQLITE_OK;
26214 #endif
26215 
26216   case EAGAIN:
26217   case ETIMEDOUT:
26218   case EBUSY:
26219   case EINTR:
26220   case ENOLCK:
26221     /* random NFS retry error, unless during file system support
26222      * introspection, in which it actually means what it says */
26223     return SQLITE_BUSY;
26224 
26225   case EACCES:
26226     /* EACCES is like EAGAIN during locking operations, but not any other time*/
26227     if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
26228         (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
26229         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
26230         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
26231       return SQLITE_BUSY;
26232     }
26233     /* else fall through */
26234   case EPERM:
26235     return SQLITE_PERM;
26236 
26237 #if EOPNOTSUPP!=ENOTSUP
26238   case EOPNOTSUPP:
26239     /* something went terribly awry, unless during file system support
26240      * introspection, in which it actually means what it says */
26241 #endif
26242 #ifdef ENOTSUP
26243   case ENOTSUP:
26244     /* invalid fd, unless during file system support introspection, in which
26245      * it actually means what it says */
26246 #endif
26247   case EIO:
26248   case EBADF:
26249   case EINVAL:
26250   case ENOTCONN:
26251   case ENODEV:
26252   case ENXIO:
26253   case ENOENT:
26254 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
26255   case ESTALE:
26256 #endif
26257   case ENOSYS:
26258     /* these should force the client to close the file and reconnect */
26259 
26260   default:
26261     return sqliteIOErr;
26262   }
26263 }
26264 
26265 
26266 /******************************************************************************
26267 ****************** Begin Unique File ID Utility Used By VxWorks ***************
26268 **
26269 ** On most versions of unix, we can get a unique ID for a file by concatenating
26270 ** the device number and the inode number.  But this does not work on VxWorks.
26271 ** On VxWorks, a unique file id must be based on the canonical filename.
26272 **
26273 ** A pointer to an instance of the following structure can be used as a
26274 ** unique file ID in VxWorks.  Each instance of this structure contains
26275 ** a copy of the canonical filename.  There is also a reference count.
26276 ** The structure is reclaimed when the number of pointers to it drops to
26277 ** zero.
26278 **
26279 ** There are never very many files open at one time and lookups are not
26280 ** a performance-critical path, so it is sufficient to put these
26281 ** structures on a linked list.
26282 */
26283 struct vxworksFileId {
26284   struct vxworksFileId *pNext;  /* Next in a list of them all */
26285   int nRef;                     /* Number of references to this one */
26286   int nName;                    /* Length of the zCanonicalName[] string */
26287   char *zCanonicalName;         /* Canonical filename */
26288 };
26289 
26290 #if OS_VXWORKS
26291 /*
26292 ** All unique filenames are held on a linked list headed by this
26293 ** variable:
26294 */
26295 static struct vxworksFileId *vxworksFileList = 0;
26296 
26297 /*
26298 ** Simplify a filename into its canonical form
26299 ** by making the following changes:
26300 **
26301 **  * removing any trailing and duplicate /
26302 **  * convert /./ into just /
26303 **  * convert /A/../ where A is any simple name into just /
26304 **
26305 ** Changes are made in-place.  Return the new name length.
26306 **
26307 ** The original filename is in z[0..n-1].  Return the number of
26308 ** characters in the simplified name.
26309 */
26310 static int vxworksSimplifyName(char *z, int n){
26311   int i, j;
26312   while( n>1 && z[n-1]=='/' ){ n--; }
26313   for(i=j=0; i<n; i++){
26314     if( z[i]=='/' ){
26315       if( z[i+1]=='/' ) continue;
26316       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
26317         i += 1;
26318         continue;
26319       }
26320       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
26321         while( j>0 && z[j-1]!='/' ){ j--; }
26322         if( j>0 ){ j--; }
26323         i += 2;
26324         continue;
26325       }
26326     }
26327     z[j++] = z[i];
26328   }
26329   z[j] = 0;
26330   return j;
26331 }
26332 
26333 /*
26334 ** Find a unique file ID for the given absolute pathname.  Return
26335 ** a pointer to the vxworksFileId object.  This pointer is the unique
26336 ** file ID.
26337 **
26338 ** The nRef field of the vxworksFileId object is incremented before
26339 ** the object is returned.  A new vxworksFileId object is created
26340 ** and added to the global list if necessary.
26341 **
26342 ** If a memory allocation error occurs, return NULL.
26343 */
26344 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
26345   struct vxworksFileId *pNew;         /* search key and new file ID */
26346   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
26347   int n;                              /* Length of zAbsoluteName string */
26348 
26349   assert( zAbsoluteName[0]=='/' );
26350   n = (int)strlen(zAbsoluteName);
26351   pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
26352   if( pNew==0 ) return 0;
26353   pNew->zCanonicalName = (char*)&pNew[1];
26354   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
26355   n = vxworksSimplifyName(pNew->zCanonicalName, n);
26356 
26357   /* Search for an existing entry that matching the canonical name.
26358   ** If found, increment the reference count and return a pointer to
26359   ** the existing file ID.
26360   */
26361   unixEnterMutex();
26362   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
26363     if( pCandidate->nName==n
26364      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
26365     ){
26366        sqlite3_free(pNew);
26367        pCandidate->nRef++;
26368        unixLeaveMutex();
26369        return pCandidate;
26370     }
26371   }
26372 
26373   /* No match was found.  We will make a new file ID */
26374   pNew->nRef = 1;
26375   pNew->nName = n;
26376   pNew->pNext = vxworksFileList;
26377   vxworksFileList = pNew;
26378   unixLeaveMutex();
26379   return pNew;
26380 }
26381 
26382 /*
26383 ** Decrement the reference count on a vxworksFileId object.  Free
26384 ** the object when the reference count reaches zero.
26385 */
26386 static void vxworksReleaseFileId(struct vxworksFileId *pId){
26387   unixEnterMutex();
26388   assert( pId->nRef>0 );
26389   pId->nRef--;
26390   if( pId->nRef==0 ){
26391     struct vxworksFileId **pp;
26392     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
26393     assert( *pp==pId );
26394     *pp = pId->pNext;
26395     sqlite3_free(pId);
26396   }
26397   unixLeaveMutex();
26398 }
26399 #endif /* OS_VXWORKS */
26400 /*************** End of Unique File ID Utility Used By VxWorks ****************
26401 ******************************************************************************/
26402 
26403 
26404 /******************************************************************************
26405 *************************** Posix Advisory Locking ****************************
26406 **
26407 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
26408 ** section 6.5.2.2 lines 483 through 490 specify that when a process
26409 ** sets or clears a lock, that operation overrides any prior locks set
26410 ** by the same process.  It does not explicitly say so, but this implies
26411 ** that it overrides locks set by the same process using a different
26412 ** file descriptor.  Consider this test case:
26413 **
26414 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
26415 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
26416 **
26417 ** Suppose ./file1 and ./file2 are really the same file (because
26418 ** one is a hard or symbolic link to the other) then if you set
26419 ** an exclusive lock on fd1, then try to get an exclusive lock
26420 ** on fd2, it works.  I would have expected the second lock to
26421 ** fail since there was already a lock on the file due to fd1.
26422 ** But not so.  Since both locks came from the same process, the
26423 ** second overrides the first, even though they were on different
26424 ** file descriptors opened on different file names.
26425 **
26426 ** This means that we cannot use POSIX locks to synchronize file access
26427 ** among competing threads of the same process.  POSIX locks will work fine
26428 ** to synchronize access for threads in separate processes, but not
26429 ** threads within the same process.
26430 **
26431 ** To work around the problem, SQLite has to manage file locks internally
26432 ** on its own.  Whenever a new database is opened, we have to find the
26433 ** specific inode of the database file (the inode is determined by the
26434 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
26435 ** and check for locks already existing on that inode.  When locks are
26436 ** created or removed, we have to look at our own internal record of the
26437 ** locks to see if another thread has previously set a lock on that same
26438 ** inode.
26439 **
26440 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
26441 ** For VxWorks, we have to use the alternative unique ID system based on
26442 ** canonical filename and implemented in the previous division.)
26443 **
26444 ** The sqlite3_file structure for POSIX is no longer just an integer file
26445 ** descriptor.  It is now a structure that holds the integer file
26446 ** descriptor and a pointer to a structure that describes the internal
26447 ** locks on the corresponding inode.  There is one locking structure
26448 ** per inode, so if the same inode is opened twice, both unixFile structures
26449 ** point to the same locking structure.  The locking structure keeps
26450 ** a reference count (so we will know when to delete it) and a "cnt"
26451 ** field that tells us its internal lock status.  cnt==0 means the
26452 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
26453 ** cnt>0 means there are cnt shared locks on the file.
26454 **
26455 ** Any attempt to lock or unlock a file first checks the locking
26456 ** structure.  The fcntl() system call is only invoked to set a
26457 ** POSIX lock if the internal lock structure transitions between
26458 ** a locked and an unlocked state.
26459 **
26460 ** But wait:  there are yet more problems with POSIX advisory locks.
26461 **
26462 ** If you close a file descriptor that points to a file that has locks,
26463 ** all locks on that file that are owned by the current process are
26464 ** released.  To work around this problem, each unixInodeInfo object
26465 ** maintains a count of the number of pending locks on tha inode.
26466 ** When an attempt is made to close an unixFile, if there are
26467 ** other unixFile open on the same inode that are holding locks, the call
26468 ** to close() the file descriptor is deferred until all of the locks clear.
26469 ** The unixInodeInfo structure keeps a list of file descriptors that need to
26470 ** be closed and that list is walked (and cleared) when the last lock
26471 ** clears.
26472 **
26473 ** Yet another problem:  LinuxThreads do not play well with posix locks.
26474 **
26475 ** Many older versions of linux use the LinuxThreads library which is
26476 ** not posix compliant.  Under LinuxThreads, a lock created by thread
26477 ** A cannot be modified or overridden by a different thread B.
26478 ** Only thread A can modify the lock.  Locking behavior is correct
26479 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
26480 ** on linux - with NPTL a lock created by thread A can override locks
26481 ** in thread B.  But there is no way to know at compile-time which
26482 ** threading library is being used.  So there is no way to know at
26483 ** compile-time whether or not thread A can override locks on thread B.
26484 ** One has to do a run-time check to discover the behavior of the
26485 ** current process.
26486 **
26487 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
26488 ** was dropped beginning with version 3.7.0.  SQLite will still work with
26489 ** LinuxThreads provided that (1) there is no more than one connection
26490 ** per database file in the same process and (2) database connections
26491 ** do not move across threads.
26492 */
26493 
26494 /*
26495 ** An instance of the following structure serves as the key used
26496 ** to locate a particular unixInodeInfo object.
26497 */
26498 struct unixFileId {
26499   dev_t dev;                  /* Device number */
26500 #if OS_VXWORKS
26501   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
26502 #else
26503   ino_t ino;                  /* Inode number */
26504 #endif
26505 };
26506 
26507 /*
26508 ** An instance of the following structure is allocated for each open
26509 ** inode.  Or, on LinuxThreads, there is one of these structures for
26510 ** each inode opened by each thread.
26511 **
26512 ** A single inode can have multiple file descriptors, so each unixFile
26513 ** structure contains a pointer to an instance of this object and this
26514 ** object keeps a count of the number of unixFile pointing to it.
26515 */
26516 struct unixInodeInfo {
26517   struct unixFileId fileId;       /* The lookup key */
26518   int nShared;                    /* Number of SHARED locks held */
26519   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
26520   unsigned char bProcessLock;     /* An exclusive process lock is held */
26521   int nRef;                       /* Number of pointers to this structure */
26522   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
26523   int nLock;                      /* Number of outstanding file locks */
26524   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
26525   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
26526   unixInodeInfo *pPrev;           /*    .... doubly linked */
26527 #if SQLITE_ENABLE_LOCKING_STYLE
26528   unsigned long long sharedByte;  /* for AFP simulated shared lock */
26529 #endif
26530 #if OS_VXWORKS
26531   sem_t *pSem;                    /* Named POSIX semaphore */
26532   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
26533 #endif
26534 };
26535 
26536 /*
26537 ** A lists of all unixInodeInfo objects.
26538 */
26539 static unixInodeInfo *inodeList = 0;
26540 
26541 /*
26542 **
26543 ** This function - unixLogError_x(), is only ever called via the macro
26544 ** unixLogError().
26545 **
26546 ** It is invoked after an error occurs in an OS function and errno has been
26547 ** set. It logs a message using sqlite3_log() containing the current value of
26548 ** errno and, if possible, the human-readable equivalent from strerror() or
26549 ** strerror_r().
26550 **
26551 ** The first argument passed to the macro should be the error code that
26552 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
26553 ** The two subsequent arguments should be the name of the OS function that
26554 ** failed (e.g. "unlink", "open") and the associated file-system path,
26555 ** if any.
26556 */
26557 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
26558 static int unixLogErrorAtLine(
26559   int errcode,                    /* SQLite error code */
26560   const char *zFunc,              /* Name of OS function that failed */
26561   const char *zPath,              /* File path associated with error */
26562   int iLine                       /* Source line number where error occurred */
26563 ){
26564   char *zErr;                     /* Message from strerror() or equivalent */
26565   int iErrno = errno;             /* Saved syscall error number */
26566 
26567   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
26568   ** the strerror() function to obtain the human-readable error message
26569   ** equivalent to errno. Otherwise, use strerror_r().
26570   */
26571 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
26572   char aErr[80];
26573   memset(aErr, 0, sizeof(aErr));
26574   zErr = aErr;
26575 
26576   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
26577   ** assume that the system provides the GNU version of strerror_r() that
26578   ** returns a pointer to a buffer containing the error message. That pointer
26579   ** may point to aErr[], or it may point to some static storage somewhere.
26580   ** Otherwise, assume that the system provides the POSIX version of
26581   ** strerror_r(), which always writes an error message into aErr[].
26582   **
26583   ** If the code incorrectly assumes that it is the POSIX version that is
26584   ** available, the error message will often be an empty string. Not a
26585   ** huge problem. Incorrectly concluding that the GNU version is available
26586   ** could lead to a segfault though.
26587   */
26588 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
26589   zErr =
26590 # endif
26591   strerror_r(iErrno, aErr, sizeof(aErr)-1);
26592 
26593 #elif SQLITE_THREADSAFE
26594   /* This is a threadsafe build, but strerror_r() is not available. */
26595   zErr = "";
26596 #else
26597   /* Non-threadsafe build, use strerror(). */
26598   zErr = strerror(iErrno);
26599 #endif
26600 
26601   if( zPath==0 ) zPath = "";
26602   sqlite3_log(errcode,
26603       "os_unix.c:%d: (%d) %s(%s) - %s",
26604       iLine, iErrno, zFunc, zPath, zErr
26605   );
26606 
26607   return errcode;
26608 }
26609 
26610 /*
26611 ** Close a file descriptor.
26612 **
26613 ** We assume that close() almost always works, since it is only in a
26614 ** very sick application or on a very sick platform that it might fail.
26615 ** If it does fail, simply leak the file descriptor, but do log the
26616 ** error.
26617 **
26618 ** Note that it is not safe to retry close() after EINTR since the
26619 ** file descriptor might have already been reused by another thread.
26620 ** So we don't even try to recover from an EINTR.  Just log the error
26621 ** and move on.
26622 */
26623 static void robust_close(unixFile *pFile, int h, int lineno){
26624   if( osClose(h) ){
26625     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
26626                        pFile ? pFile->zPath : 0, lineno);
26627   }
26628 }
26629 
26630 /*
26631 ** Set the pFile->lastErrno.  Do this in a subroutine as that provides
26632 ** a convenient place to set a breakpoint.
26633 */
26634 static void storeLastErrno(unixFile *pFile, int error){
26635   pFile->lastErrno = error;
26636 }
26637 
26638 /*
26639 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
26640 */
26641 static void closePendingFds(unixFile *pFile){
26642   unixInodeInfo *pInode = pFile->pInode;
26643   UnixUnusedFd *p;
26644   UnixUnusedFd *pNext;
26645   for(p=pInode->pUnused; p; p=pNext){
26646     pNext = p->pNext;
26647     robust_close(pFile, p->fd, __LINE__);
26648     sqlite3_free(p);
26649   }
26650   pInode->pUnused = 0;
26651 }
26652 
26653 /*
26654 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
26655 **
26656 ** The mutex entered using the unixEnterMutex() function must be held
26657 ** when this function is called.
26658 */
26659 static void releaseInodeInfo(unixFile *pFile){
26660   unixInodeInfo *pInode = pFile->pInode;
26661   assert( unixMutexHeld() );
26662   if( ALWAYS(pInode) ){
26663     pInode->nRef--;
26664     if( pInode->nRef==0 ){
26665       assert( pInode->pShmNode==0 );
26666       closePendingFds(pFile);
26667       if( pInode->pPrev ){
26668         assert( pInode->pPrev->pNext==pInode );
26669         pInode->pPrev->pNext = pInode->pNext;
26670       }else{
26671         assert( inodeList==pInode );
26672         inodeList = pInode->pNext;
26673       }
26674       if( pInode->pNext ){
26675         assert( pInode->pNext->pPrev==pInode );
26676         pInode->pNext->pPrev = pInode->pPrev;
26677       }
26678       sqlite3_free(pInode);
26679     }
26680   }
26681 }
26682 
26683 /*
26684 ** Given a file descriptor, locate the unixInodeInfo object that
26685 ** describes that file descriptor.  Create a new one if necessary.  The
26686 ** return value might be uninitialized if an error occurs.
26687 **
26688 ** The mutex entered using the unixEnterMutex() function must be held
26689 ** when this function is called.
26690 **
26691 ** Return an appropriate error code.
26692 */
26693 static int findInodeInfo(
26694   unixFile *pFile,               /* Unix file with file desc used in the key */
26695   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
26696 ){
26697   int rc;                        /* System call return code */
26698   int fd;                        /* The file descriptor for pFile */
26699   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
26700   struct stat statbuf;           /* Low-level file information */
26701   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
26702 
26703   assert( unixMutexHeld() );
26704 
26705   /* Get low-level information about the file that we can used to
26706   ** create a unique name for the file.
26707   */
26708   fd = pFile->h;
26709   rc = osFstat(fd, &statbuf);
26710   if( rc!=0 ){
26711     storeLastErrno(pFile, errno);
26712 #ifdef EOVERFLOW
26713     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
26714 #endif
26715     return SQLITE_IOERR;
26716   }
26717 
26718 #ifdef __APPLE__
26719   /* On OS X on an msdos filesystem, the inode number is reported
26720   ** incorrectly for zero-size files.  See ticket #3260.  To work
26721   ** around this problem (we consider it a bug in OS X, not SQLite)
26722   ** we always increase the file size to 1 by writing a single byte
26723   ** prior to accessing the inode number.  The one byte written is
26724   ** an ASCII 'S' character which also happens to be the first byte
26725   ** in the header of every SQLite database.  In this way, if there
26726   ** is a race condition such that another thread has already populated
26727   ** the first page of the database, no damage is done.
26728   */
26729   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
26730     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
26731     if( rc!=1 ){
26732       storeLastErrno(pFile, errno);
26733       return SQLITE_IOERR;
26734     }
26735     rc = osFstat(fd, &statbuf);
26736     if( rc!=0 ){
26737       storeLastErrno(pFile, errno);
26738       return SQLITE_IOERR;
26739     }
26740   }
26741 #endif
26742 
26743   memset(&fileId, 0, sizeof(fileId));
26744   fileId.dev = statbuf.st_dev;
26745 #if OS_VXWORKS
26746   fileId.pId = pFile->pId;
26747 #else
26748   fileId.ino = statbuf.st_ino;
26749 #endif
26750   pInode = inodeList;
26751   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
26752     pInode = pInode->pNext;
26753   }
26754   if( pInode==0 ){
26755     pInode = sqlite3_malloc64( sizeof(*pInode) );
26756     if( pInode==0 ){
26757       return SQLITE_NOMEM;
26758     }
26759     memset(pInode, 0, sizeof(*pInode));
26760     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
26761     pInode->nRef = 1;
26762     pInode->pNext = inodeList;
26763     pInode->pPrev = 0;
26764     if( inodeList ) inodeList->pPrev = pInode;
26765     inodeList = pInode;
26766   }else{
26767     pInode->nRef++;
26768   }
26769   *ppInode = pInode;
26770   return SQLITE_OK;
26771 }
26772 
26773 /*
26774 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
26775 */
26776 static int fileHasMoved(unixFile *pFile){
26777 #if OS_VXWORKS
26778   return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
26779 #else
26780   struct stat buf;
26781   return pFile->pInode!=0 &&
26782       (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
26783 #endif
26784 }
26785 
26786 
26787 /*
26788 ** Check a unixFile that is a database.  Verify the following:
26789 **
26790 ** (1) There is exactly one hard link on the file
26791 ** (2) The file is not a symbolic link
26792 ** (3) The file has not been renamed or unlinked
26793 **
26794 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
26795 */
26796 static void verifyDbFile(unixFile *pFile){
26797   struct stat buf;
26798   int rc;
26799   if( pFile->ctrlFlags & UNIXFILE_WARNED ){
26800     /* One or more of the following warnings have already been issued.  Do not
26801     ** repeat them so as not to clutter the error log */
26802     return;
26803   }
26804   rc = osFstat(pFile->h, &buf);
26805   if( rc!=0 ){
26806     sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
26807     pFile->ctrlFlags |= UNIXFILE_WARNED;
26808     return;
26809   }
26810   if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
26811     sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
26812     pFile->ctrlFlags |= UNIXFILE_WARNED;
26813     return;
26814   }
26815   if( buf.st_nlink>1 ){
26816     sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
26817     pFile->ctrlFlags |= UNIXFILE_WARNED;
26818     return;
26819   }
26820   if( fileHasMoved(pFile) ){
26821     sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
26822     pFile->ctrlFlags |= UNIXFILE_WARNED;
26823     return;
26824   }
26825 }
26826 
26827 
26828 /*
26829 ** This routine checks if there is a RESERVED lock held on the specified
26830 ** file by this or any other process. If such a lock is held, set *pResOut
26831 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26832 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26833 */
26834 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
26835   int rc = SQLITE_OK;
26836   int reserved = 0;
26837   unixFile *pFile = (unixFile*)id;
26838 
26839   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26840 
26841   assert( pFile );
26842   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26843 
26844   /* Check if a thread in this process holds such a lock */
26845   if( pFile->pInode->eFileLock>SHARED_LOCK ){
26846     reserved = 1;
26847   }
26848 
26849   /* Otherwise see if some other process holds it.
26850   */
26851 #ifndef __DJGPP__
26852   if( !reserved && !pFile->pInode->bProcessLock ){
26853     struct flock lock;
26854     lock.l_whence = SEEK_SET;
26855     lock.l_start = RESERVED_BYTE;
26856     lock.l_len = 1;
26857     lock.l_type = F_WRLCK;
26858     if( osFcntl(pFile->h, F_GETLK, &lock) ){
26859       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
26860       storeLastErrno(pFile, errno);
26861     } else if( lock.l_type!=F_UNLCK ){
26862       reserved = 1;
26863     }
26864   }
26865 #endif
26866 
26867   unixLeaveMutex();
26868   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
26869 
26870   *pResOut = reserved;
26871   return rc;
26872 }
26873 
26874 /*
26875 ** Attempt to set a system-lock on the file pFile.  The lock is
26876 ** described by pLock.
26877 **
26878 ** If the pFile was opened read/write from unix-excl, then the only lock
26879 ** ever obtained is an exclusive lock, and it is obtained exactly once
26880 ** the first time any lock is attempted.  All subsequent system locking
26881 ** operations become no-ops.  Locking operations still happen internally,
26882 ** in order to coordinate access between separate database connections
26883 ** within this process, but all of that is handled in memory and the
26884 ** operating system does not participate.
26885 **
26886 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
26887 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
26888 ** and is read-only.
26889 **
26890 ** Zero is returned if the call completes successfully, or -1 if a call
26891 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
26892 */
26893 static int unixFileLock(unixFile *pFile, struct flock *pLock){
26894   int rc;
26895   unixInodeInfo *pInode = pFile->pInode;
26896   assert( unixMutexHeld() );
26897   assert( pInode!=0 );
26898   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
26899    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
26900   ){
26901     if( pInode->bProcessLock==0 ){
26902       struct flock lock;
26903       assert( pInode->nLock==0 );
26904       lock.l_whence = SEEK_SET;
26905       lock.l_start = SHARED_FIRST;
26906       lock.l_len = SHARED_SIZE;
26907       lock.l_type = F_WRLCK;
26908       rc = osFcntl(pFile->h, F_SETLK, &lock);
26909       if( rc<0 ) return rc;
26910       pInode->bProcessLock = 1;
26911       pInode->nLock++;
26912     }else{
26913       rc = 0;
26914     }
26915   }else{
26916     rc = osFcntl(pFile->h, F_SETLK, pLock);
26917   }
26918   return rc;
26919 }
26920 
26921 /*
26922 ** Lock the file with the lock specified by parameter eFileLock - one
26923 ** of the following:
26924 **
26925 **     (1) SHARED_LOCK
26926 **     (2) RESERVED_LOCK
26927 **     (3) PENDING_LOCK
26928 **     (4) EXCLUSIVE_LOCK
26929 **
26930 ** Sometimes when requesting one lock state, additional lock states
26931 ** are inserted in between.  The locking might fail on one of the later
26932 ** transitions leaving the lock state different from what it started but
26933 ** still short of its goal.  The following chart shows the allowed
26934 ** transitions and the inserted intermediate states:
26935 **
26936 **    UNLOCKED -> SHARED
26937 **    SHARED -> RESERVED
26938 **    SHARED -> (PENDING) -> EXCLUSIVE
26939 **    RESERVED -> (PENDING) -> EXCLUSIVE
26940 **    PENDING -> EXCLUSIVE
26941 **
26942 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26943 ** routine to lower a locking level.
26944 */
26945 static int unixLock(sqlite3_file *id, int eFileLock){
26946   /* The following describes the implementation of the various locks and
26947   ** lock transitions in terms of the POSIX advisory shared and exclusive
26948   ** lock primitives (called read-locks and write-locks below, to avoid
26949   ** confusion with SQLite lock names). The algorithms are complicated
26950   ** slightly in order to be compatible with windows systems simultaneously
26951   ** accessing the same database file, in case that is ever required.
26952   **
26953   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
26954   ** byte', each single bytes at well known offsets, and the 'shared byte
26955   ** range', a range of 510 bytes at a well known offset.
26956   **
26957   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
26958   ** byte'.  If this is successful, a random byte from the 'shared byte
26959   ** range' is read-locked and the lock on the 'pending byte' released.
26960   **
26961   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
26962   ** A RESERVED lock is implemented by grabbing a write-lock on the
26963   ** 'reserved byte'.
26964   **
26965   ** A process may only obtain a PENDING lock after it has obtained a
26966   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
26967   ** on the 'pending byte'. This ensures that no new SHARED locks can be
26968   ** obtained, but existing SHARED locks are allowed to persist. A process
26969   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
26970   ** This property is used by the algorithm for rolling back a journal file
26971   ** after a crash.
26972   **
26973   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
26974   ** implemented by obtaining a write-lock on the entire 'shared byte
26975   ** range'. Since all other locks require a read-lock on one of the bytes
26976   ** within this range, this ensures that no other locks are held on the
26977   ** database.
26978   **
26979   ** The reason a single byte cannot be used instead of the 'shared byte
26980   ** range' is that some versions of windows do not support read-locks. By
26981   ** locking a random byte from a range, concurrent SHARED locks may exist
26982   ** even if the locking primitive used is always a write-lock.
26983   */
26984   int rc = SQLITE_OK;
26985   unixFile *pFile = (unixFile*)id;
26986   unixInodeInfo *pInode;
26987   struct flock lock;
26988   int tErrno = 0;
26989 
26990   assert( pFile );
26991   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
26992       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26993       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
26994       osGetpid(0)));
26995 
26996   /* If there is already a lock of this type or more restrictive on the
26997   ** unixFile, do nothing. Don't use the end_lock: exit path, as
26998   ** unixEnterMutex() hasn't been called yet.
26999   */
27000   if( pFile->eFileLock>=eFileLock ){
27001     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
27002             azFileLock(eFileLock)));
27003     return SQLITE_OK;
27004   }
27005 
27006   /* Make sure the locking sequence is correct.
27007   **  (1) We never move from unlocked to anything higher than shared lock.
27008   **  (2) SQLite never explicitly requests a pendig lock.
27009   **  (3) A shared lock is always held when a reserve lock is requested.
27010   */
27011   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
27012   assert( eFileLock!=PENDING_LOCK );
27013   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
27014 
27015   /* This mutex is needed because pFile->pInode is shared across threads
27016   */
27017   unixEnterMutex();
27018   pInode = pFile->pInode;
27019 
27020   /* If some thread using this PID has a lock via a different unixFile*
27021   ** handle that precludes the requested lock, return BUSY.
27022   */
27023   if( (pFile->eFileLock!=pInode->eFileLock &&
27024           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
27025   ){
27026     rc = SQLITE_BUSY;
27027     goto end_lock;
27028   }
27029 
27030   /* If a SHARED lock is requested, and some thread using this PID already
27031   ** has a SHARED or RESERVED lock, then increment reference counts and
27032   ** return SQLITE_OK.
27033   */
27034   if( eFileLock==SHARED_LOCK &&
27035       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
27036     assert( eFileLock==SHARED_LOCK );
27037     assert( pFile->eFileLock==0 );
27038     assert( pInode->nShared>0 );
27039     pFile->eFileLock = SHARED_LOCK;
27040     pInode->nShared++;
27041     pInode->nLock++;
27042     goto end_lock;
27043   }
27044 
27045 
27046   /* A PENDING lock is needed before acquiring a SHARED lock and before
27047   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
27048   ** be released.
27049   */
27050   lock.l_len = 1L;
27051   lock.l_whence = SEEK_SET;
27052   if( eFileLock==SHARED_LOCK
27053       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
27054   ){
27055     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
27056     lock.l_start = PENDING_BYTE;
27057     if( unixFileLock(pFile, &lock) ){
27058       tErrno = errno;
27059       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27060       if( rc!=SQLITE_BUSY ){
27061         storeLastErrno(pFile, tErrno);
27062       }
27063       goto end_lock;
27064     }
27065   }
27066 
27067 
27068   /* If control gets to this point, then actually go ahead and make
27069   ** operating system calls for the specified lock.
27070   */
27071   if( eFileLock==SHARED_LOCK ){
27072     assert( pInode->nShared==0 );
27073     assert( pInode->eFileLock==0 );
27074     assert( rc==SQLITE_OK );
27075 
27076     /* Now get the read-lock */
27077     lock.l_start = SHARED_FIRST;
27078     lock.l_len = SHARED_SIZE;
27079     if( unixFileLock(pFile, &lock) ){
27080       tErrno = errno;
27081       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27082     }
27083 
27084     /* Drop the temporary PENDING lock */
27085     lock.l_start = PENDING_BYTE;
27086     lock.l_len = 1L;
27087     lock.l_type = F_UNLCK;
27088     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
27089       /* This could happen with a network mount */
27090       tErrno = errno;
27091       rc = SQLITE_IOERR_UNLOCK;
27092     }
27093 
27094     if( rc ){
27095       if( rc!=SQLITE_BUSY ){
27096         storeLastErrno(pFile, tErrno);
27097       }
27098       goto end_lock;
27099     }else{
27100       pFile->eFileLock = SHARED_LOCK;
27101       pInode->nLock++;
27102       pInode->nShared = 1;
27103     }
27104   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
27105     /* We are trying for an exclusive lock but another thread in this
27106     ** same process is still holding a shared lock. */
27107     rc = SQLITE_BUSY;
27108   }else{
27109     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
27110     ** assumed that there is a SHARED or greater lock on the file
27111     ** already.
27112     */
27113     assert( 0!=pFile->eFileLock );
27114     lock.l_type = F_WRLCK;
27115 
27116     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
27117     if( eFileLock==RESERVED_LOCK ){
27118       lock.l_start = RESERVED_BYTE;
27119       lock.l_len = 1L;
27120     }else{
27121       lock.l_start = SHARED_FIRST;
27122       lock.l_len = SHARED_SIZE;
27123     }
27124 
27125     if( unixFileLock(pFile, &lock) ){
27126       tErrno = errno;
27127       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27128       if( rc!=SQLITE_BUSY ){
27129         storeLastErrno(pFile, tErrno);
27130       }
27131     }
27132   }
27133 
27134 
27135 #ifdef SQLITE_DEBUG
27136   /* Set up the transaction-counter change checking flags when
27137   ** transitioning from a SHARED to a RESERVED lock.  The change
27138   ** from SHARED to RESERVED marks the beginning of a normal
27139   ** write operation (not a hot journal rollback).
27140   */
27141   if( rc==SQLITE_OK
27142    && pFile->eFileLock<=SHARED_LOCK
27143    && eFileLock==RESERVED_LOCK
27144   ){
27145     pFile->transCntrChng = 0;
27146     pFile->dbUpdate = 0;
27147     pFile->inNormalWrite = 1;
27148   }
27149 #endif
27150 
27151 
27152   if( rc==SQLITE_OK ){
27153     pFile->eFileLock = eFileLock;
27154     pInode->eFileLock = eFileLock;
27155   }else if( eFileLock==EXCLUSIVE_LOCK ){
27156     pFile->eFileLock = PENDING_LOCK;
27157     pInode->eFileLock = PENDING_LOCK;
27158   }
27159 
27160 end_lock:
27161   unixLeaveMutex();
27162   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
27163       rc==SQLITE_OK ? "ok" : "failed"));
27164   return rc;
27165 }
27166 
27167 /*
27168 ** Add the file descriptor used by file handle pFile to the corresponding
27169 ** pUnused list.
27170 */
27171 static void setPendingFd(unixFile *pFile){
27172   unixInodeInfo *pInode = pFile->pInode;
27173   UnixUnusedFd *p = pFile->pUnused;
27174   p->pNext = pInode->pUnused;
27175   pInode->pUnused = p;
27176   pFile->h = -1;
27177   pFile->pUnused = 0;
27178 }
27179 
27180 /*
27181 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27182 ** must be either NO_LOCK or SHARED_LOCK.
27183 **
27184 ** If the locking level of the file descriptor is already at or below
27185 ** the requested locking level, this routine is a no-op.
27186 **
27187 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
27188 ** the byte range is divided into 2 parts and the first part is unlocked then
27189 ** set to a read lock, then the other part is simply unlocked.  This works
27190 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
27191 ** remove the write lock on a region when a read lock is set.
27192 */
27193 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
27194   unixFile *pFile = (unixFile*)id;
27195   unixInodeInfo *pInode;
27196   struct flock lock;
27197   int rc = SQLITE_OK;
27198 
27199   assert( pFile );
27200   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
27201       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
27202       osGetpid(0)));
27203 
27204   assert( eFileLock<=SHARED_LOCK );
27205   if( pFile->eFileLock<=eFileLock ){
27206     return SQLITE_OK;
27207   }
27208   unixEnterMutex();
27209   pInode = pFile->pInode;
27210   assert( pInode->nShared!=0 );
27211   if( pFile->eFileLock>SHARED_LOCK ){
27212     assert( pInode->eFileLock==pFile->eFileLock );
27213 
27214 #ifdef SQLITE_DEBUG
27215     /* When reducing a lock such that other processes can start
27216     ** reading the database file again, make sure that the
27217     ** transaction counter was updated if any part of the database
27218     ** file changed.  If the transaction counter is not updated,
27219     ** other connections to the same file might not realize that
27220     ** the file has changed and hence might not know to flush their
27221     ** cache.  The use of a stale cache can lead to database corruption.
27222     */
27223     pFile->inNormalWrite = 0;
27224 #endif
27225 
27226     /* downgrading to a shared lock on NFS involves clearing the write lock
27227     ** before establishing the readlock - to avoid a race condition we downgrade
27228     ** the lock in 2 blocks, so that part of the range will be covered by a
27229     ** write lock until the rest is covered by a read lock:
27230     **  1:   [WWWWW]
27231     **  2:   [....W]
27232     **  3:   [RRRRW]
27233     **  4:   [RRRR.]
27234     */
27235     if( eFileLock==SHARED_LOCK ){
27236 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
27237       (void)handleNFSUnlock;
27238       assert( handleNFSUnlock==0 );
27239 #endif
27240 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27241       if( handleNFSUnlock ){
27242         int tErrno;               /* Error code from system call errors */
27243         off_t divSize = SHARED_SIZE - 1;
27244 
27245         lock.l_type = F_UNLCK;
27246         lock.l_whence = SEEK_SET;
27247         lock.l_start = SHARED_FIRST;
27248         lock.l_len = divSize;
27249         if( unixFileLock(pFile, &lock)==(-1) ){
27250           tErrno = errno;
27251           rc = SQLITE_IOERR_UNLOCK;
27252           if( IS_LOCK_ERROR(rc) ){
27253             storeLastErrno(pFile, tErrno);
27254           }
27255           goto end_unlock;
27256         }
27257         lock.l_type = F_RDLCK;
27258         lock.l_whence = SEEK_SET;
27259         lock.l_start = SHARED_FIRST;
27260         lock.l_len = divSize;
27261         if( unixFileLock(pFile, &lock)==(-1) ){
27262           tErrno = errno;
27263           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
27264           if( IS_LOCK_ERROR(rc) ){
27265             storeLastErrno(pFile, tErrno);
27266           }
27267           goto end_unlock;
27268         }
27269         lock.l_type = F_UNLCK;
27270         lock.l_whence = SEEK_SET;
27271         lock.l_start = SHARED_FIRST+divSize;
27272         lock.l_len = SHARED_SIZE-divSize;
27273         if( unixFileLock(pFile, &lock)==(-1) ){
27274           tErrno = errno;
27275           rc = SQLITE_IOERR_UNLOCK;
27276           if( IS_LOCK_ERROR(rc) ){
27277             storeLastErrno(pFile, tErrno);
27278           }
27279           goto end_unlock;
27280         }
27281       }else
27282 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27283       {
27284         lock.l_type = F_RDLCK;
27285         lock.l_whence = SEEK_SET;
27286         lock.l_start = SHARED_FIRST;
27287         lock.l_len = SHARED_SIZE;
27288         if( unixFileLock(pFile, &lock) ){
27289           /* In theory, the call to unixFileLock() cannot fail because another
27290           ** process is holding an incompatible lock. If it does, this
27291           ** indicates that the other process is not following the locking
27292           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
27293           ** SQLITE_BUSY would confuse the upper layer (in practice it causes
27294           ** an assert to fail). */
27295           rc = SQLITE_IOERR_RDLOCK;
27296           storeLastErrno(pFile, errno);
27297           goto end_unlock;
27298         }
27299       }
27300     }
27301     lock.l_type = F_UNLCK;
27302     lock.l_whence = SEEK_SET;
27303     lock.l_start = PENDING_BYTE;
27304     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
27305     if( unixFileLock(pFile, &lock)==0 ){
27306       pInode->eFileLock = SHARED_LOCK;
27307     }else{
27308       rc = SQLITE_IOERR_UNLOCK;
27309       storeLastErrno(pFile, errno);
27310       goto end_unlock;
27311     }
27312   }
27313   if( eFileLock==NO_LOCK ){
27314     /* Decrement the shared lock counter.  Release the lock using an
27315     ** OS call only when all threads in this same process have released
27316     ** the lock.
27317     */
27318     pInode->nShared--;
27319     if( pInode->nShared==0 ){
27320       lock.l_type = F_UNLCK;
27321       lock.l_whence = SEEK_SET;
27322       lock.l_start = lock.l_len = 0L;
27323       if( unixFileLock(pFile, &lock)==0 ){
27324         pInode->eFileLock = NO_LOCK;
27325       }else{
27326         rc = SQLITE_IOERR_UNLOCK;
27327         storeLastErrno(pFile, errno);
27328         pInode->eFileLock = NO_LOCK;
27329         pFile->eFileLock = NO_LOCK;
27330       }
27331     }
27332 
27333     /* Decrement the count of locks against this same file.  When the
27334     ** count reaches zero, close any other file descriptors whose close
27335     ** was deferred because of outstanding locks.
27336     */
27337     pInode->nLock--;
27338     assert( pInode->nLock>=0 );
27339     if( pInode->nLock==0 ){
27340       closePendingFds(pFile);
27341     }
27342   }
27343 
27344 end_unlock:
27345   unixLeaveMutex();
27346   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
27347   return rc;
27348 }
27349 
27350 /*
27351 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27352 ** must be either NO_LOCK or SHARED_LOCK.
27353 **
27354 ** If the locking level of the file descriptor is already at or below
27355 ** the requested locking level, this routine is a no-op.
27356 */
27357 static int unixUnlock(sqlite3_file *id, int eFileLock){
27358 #if SQLITE_MAX_MMAP_SIZE>0
27359   assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
27360 #endif
27361   return posixUnlock(id, eFileLock, 0);
27362 }
27363 
27364 #if SQLITE_MAX_MMAP_SIZE>0
27365 static int unixMapfile(unixFile *pFd, i64 nByte);
27366 static void unixUnmapfile(unixFile *pFd);
27367 #endif
27368 
27369 /*
27370 ** This function performs the parts of the "close file" operation
27371 ** common to all locking schemes. It closes the directory and file
27372 ** handles, if they are valid, and sets all fields of the unixFile
27373 ** structure to 0.
27374 **
27375 ** It is *not* necessary to hold the mutex when this routine is called,
27376 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
27377 ** vxworksReleaseFileId() routine.
27378 */
27379 static int closeUnixFile(sqlite3_file *id){
27380   unixFile *pFile = (unixFile*)id;
27381 #if SQLITE_MAX_MMAP_SIZE>0
27382   unixUnmapfile(pFile);
27383 #endif
27384   if( pFile->h>=0 ){
27385     robust_close(pFile, pFile->h, __LINE__);
27386     pFile->h = -1;
27387   }
27388 #if OS_VXWORKS
27389   if( pFile->pId ){
27390     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
27391       osUnlink(pFile->pId->zCanonicalName);
27392     }
27393     vxworksReleaseFileId(pFile->pId);
27394     pFile->pId = 0;
27395   }
27396 #endif
27397 #ifdef SQLITE_UNLINK_AFTER_CLOSE
27398   if( pFile->ctrlFlags & UNIXFILE_DELETE ){
27399     osUnlink(pFile->zPath);
27400     sqlite3_free(*(char**)&pFile->zPath);
27401     pFile->zPath = 0;
27402   }
27403 #endif
27404   OSTRACE(("CLOSE   %-3d\n", pFile->h));
27405   OpenCounter(-1);
27406   sqlite3_free(pFile->pUnused);
27407   memset(pFile, 0, sizeof(unixFile));
27408   return SQLITE_OK;
27409 }
27410 
27411 /*
27412 ** Close a file.
27413 */
27414 static int unixClose(sqlite3_file *id){
27415   int rc = SQLITE_OK;
27416   unixFile *pFile = (unixFile *)id;
27417   verifyDbFile(pFile);
27418   unixUnlock(id, NO_LOCK);
27419   unixEnterMutex();
27420 
27421   /* unixFile.pInode is always valid here. Otherwise, a different close
27422   ** routine (e.g. nolockClose()) would be called instead.
27423   */
27424   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
27425   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
27426     /* If there are outstanding locks, do not actually close the file just
27427     ** yet because that would clear those locks.  Instead, add the file
27428     ** descriptor to pInode->pUnused list.  It will be automatically closed
27429     ** when the last lock is cleared.
27430     */
27431     setPendingFd(pFile);
27432   }
27433   releaseInodeInfo(pFile);
27434   rc = closeUnixFile(id);
27435   unixLeaveMutex();
27436   return rc;
27437 }
27438 
27439 /************** End of the posix advisory lock implementation *****************
27440 ******************************************************************************/
27441 
27442 /******************************************************************************
27443 ****************************** No-op Locking **********************************
27444 **
27445 ** Of the various locking implementations available, this is by far the
27446 ** simplest:  locking is ignored.  No attempt is made to lock the database
27447 ** file for reading or writing.
27448 **
27449 ** This locking mode is appropriate for use on read-only databases
27450 ** (ex: databases that are burned into CD-ROM, for example.)  It can
27451 ** also be used if the application employs some external mechanism to
27452 ** prevent simultaneous access of the same database by two or more
27453 ** database connections.  But there is a serious risk of database
27454 ** corruption if this locking mode is used in situations where multiple
27455 ** database connections are accessing the same database file at the same
27456 ** time and one or more of those connections are writing.
27457 */
27458 
27459 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
27460   UNUSED_PARAMETER(NotUsed);
27461   *pResOut = 0;
27462   return SQLITE_OK;
27463 }
27464 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
27465   UNUSED_PARAMETER2(NotUsed, NotUsed2);
27466   return SQLITE_OK;
27467 }
27468 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
27469   UNUSED_PARAMETER2(NotUsed, NotUsed2);
27470   return SQLITE_OK;
27471 }
27472 
27473 /*
27474 ** Close the file.
27475 */
27476 static int nolockClose(sqlite3_file *id) {
27477   return closeUnixFile(id);
27478 }
27479 
27480 /******************* End of the no-op lock implementation *********************
27481 ******************************************************************************/
27482 
27483 /******************************************************************************
27484 ************************* Begin dot-file Locking ******************************
27485 **
27486 ** The dotfile locking implementation uses the existence of separate lock
27487 ** files (really a directory) to control access to the database.  This works
27488 ** on just about every filesystem imaginable.  But there are serious downsides:
27489 **
27490 **    (1)  There is zero concurrency.  A single reader blocks all other
27491 **         connections from reading or writing the database.
27492 **
27493 **    (2)  An application crash or power loss can leave stale lock files
27494 **         sitting around that need to be cleared manually.
27495 **
27496 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
27497 ** other locking strategy is available.
27498 **
27499 ** Dotfile locking works by creating a subdirectory in the same directory as
27500 ** the database and with the same name but with a ".lock" extension added.
27501 ** The existence of a lock directory implies an EXCLUSIVE lock.  All other
27502 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
27503 */
27504 
27505 /*
27506 ** The file suffix added to the data base filename in order to create the
27507 ** lock directory.
27508 */
27509 #define DOTLOCK_SUFFIX ".lock"
27510 
27511 /*
27512 ** This routine checks if there is a RESERVED lock held on the specified
27513 ** file by this or any other process. If such a lock is held, set *pResOut
27514 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27515 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27516 **
27517 ** In dotfile locking, either a lock exists or it does not.  So in this
27518 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
27519 ** is held on the file and false if the file is unlocked.
27520 */
27521 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
27522   int rc = SQLITE_OK;
27523   int reserved = 0;
27524   unixFile *pFile = (unixFile*)id;
27525 
27526   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27527 
27528   assert( pFile );
27529 
27530   /* Check if a thread in this process holds such a lock */
27531   if( pFile->eFileLock>SHARED_LOCK ){
27532     /* Either this connection or some other connection in the same process
27533     ** holds a lock on the file.  No need to check further. */
27534     reserved = 1;
27535   }else{
27536     /* The lock is held if and only if the lockfile exists */
27537     const char *zLockFile = (const char*)pFile->lockingContext;
27538     reserved = osAccess(zLockFile, 0)==0;
27539   }
27540   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
27541   *pResOut = reserved;
27542   return rc;
27543 }
27544 
27545 /*
27546 ** Lock the file with the lock specified by parameter eFileLock - one
27547 ** of the following:
27548 **
27549 **     (1) SHARED_LOCK
27550 **     (2) RESERVED_LOCK
27551 **     (3) PENDING_LOCK
27552 **     (4) EXCLUSIVE_LOCK
27553 **
27554 ** Sometimes when requesting one lock state, additional lock states
27555 ** are inserted in between.  The locking might fail on one of the later
27556 ** transitions leaving the lock state different from what it started but
27557 ** still short of its goal.  The following chart shows the allowed
27558 ** transitions and the inserted intermediate states:
27559 **
27560 **    UNLOCKED -> SHARED
27561 **    SHARED -> RESERVED
27562 **    SHARED -> (PENDING) -> EXCLUSIVE
27563 **    RESERVED -> (PENDING) -> EXCLUSIVE
27564 **    PENDING -> EXCLUSIVE
27565 **
27566 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27567 ** routine to lower a locking level.
27568 **
27569 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
27570 ** But we track the other locking levels internally.
27571 */
27572 static int dotlockLock(sqlite3_file *id, int eFileLock) {
27573   unixFile *pFile = (unixFile*)id;
27574   char *zLockFile = (char *)pFile->lockingContext;
27575   int rc = SQLITE_OK;
27576 
27577 
27578   /* If we have any lock, then the lock file already exists.  All we have
27579   ** to do is adjust our internal record of the lock level.
27580   */
27581   if( pFile->eFileLock > NO_LOCK ){
27582     pFile->eFileLock = eFileLock;
27583     /* Always update the timestamp on the old file */
27584 #ifdef HAVE_UTIME
27585     utime(zLockFile, NULL);
27586 #else
27587     utimes(zLockFile, NULL);
27588 #endif
27589     return SQLITE_OK;
27590   }
27591 
27592   /* grab an exclusive lock */
27593   rc = osMkdir(zLockFile, 0777);
27594   if( rc<0 ){
27595     /* failed to open/create the lock directory */
27596     int tErrno = errno;
27597     if( EEXIST == tErrno ){
27598       rc = SQLITE_BUSY;
27599     } else {
27600       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27601       if( IS_LOCK_ERROR(rc) ){
27602         storeLastErrno(pFile, tErrno);
27603       }
27604     }
27605     return rc;
27606   }
27607 
27608   /* got it, set the type and return ok */
27609   pFile->eFileLock = eFileLock;
27610   return rc;
27611 }
27612 
27613 /*
27614 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27615 ** must be either NO_LOCK or SHARED_LOCK.
27616 **
27617 ** If the locking level of the file descriptor is already at or below
27618 ** the requested locking level, this routine is a no-op.
27619 **
27620 ** When the locking level reaches NO_LOCK, delete the lock file.
27621 */
27622 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
27623   unixFile *pFile = (unixFile*)id;
27624   char *zLockFile = (char *)pFile->lockingContext;
27625   int rc;
27626 
27627   assert( pFile );
27628   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
27629            pFile->eFileLock, osGetpid(0)));
27630   assert( eFileLock<=SHARED_LOCK );
27631 
27632   /* no-op if possible */
27633   if( pFile->eFileLock==eFileLock ){
27634     return SQLITE_OK;
27635   }
27636 
27637   /* To downgrade to shared, simply update our internal notion of the
27638   ** lock state.  No need to mess with the file on disk.
27639   */
27640   if( eFileLock==SHARED_LOCK ){
27641     pFile->eFileLock = SHARED_LOCK;
27642     return SQLITE_OK;
27643   }
27644 
27645   /* To fully unlock the database, delete the lock file */
27646   assert( eFileLock==NO_LOCK );
27647   rc = osRmdir(zLockFile);
27648   if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
27649   if( rc<0 ){
27650     int tErrno = errno;
27651     rc = 0;
27652     if( ENOENT != tErrno ){
27653       rc = SQLITE_IOERR_UNLOCK;
27654     }
27655     if( IS_LOCK_ERROR(rc) ){
27656       storeLastErrno(pFile, tErrno);
27657     }
27658     return rc;
27659   }
27660   pFile->eFileLock = NO_LOCK;
27661   return SQLITE_OK;
27662 }
27663 
27664 /*
27665 ** Close a file.  Make sure the lock has been released before closing.
27666 */
27667 static int dotlockClose(sqlite3_file *id) {
27668   int rc = SQLITE_OK;
27669   if( id ){
27670     unixFile *pFile = (unixFile*)id;
27671     dotlockUnlock(id, NO_LOCK);
27672     sqlite3_free(pFile->lockingContext);
27673     rc = closeUnixFile(id);
27674   }
27675   return rc;
27676 }
27677 /****************** End of the dot-file lock implementation *******************
27678 ******************************************************************************/
27679 
27680 /******************************************************************************
27681 ************************** Begin flock Locking ********************************
27682 **
27683 ** Use the flock() system call to do file locking.
27684 **
27685 ** flock() locking is like dot-file locking in that the various
27686 ** fine-grain locking levels supported by SQLite are collapsed into
27687 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
27688 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
27689 ** still works when you do this, but concurrency is reduced since
27690 ** only a single process can be reading the database at a time.
27691 **
27692 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
27693 */
27694 #if SQLITE_ENABLE_LOCKING_STYLE
27695 
27696 /*
27697 ** Retry flock() calls that fail with EINTR
27698 */
27699 #ifdef EINTR
27700 static int robust_flock(int fd, int op){
27701   int rc;
27702   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
27703   return rc;
27704 }
27705 #else
27706 # define robust_flock(a,b) flock(a,b)
27707 #endif
27708 
27709 
27710 /*
27711 ** This routine checks if there is a RESERVED lock held on the specified
27712 ** file by this or any other process. If such a lock is held, set *pResOut
27713 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27714 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27715 */
27716 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
27717   int rc = SQLITE_OK;
27718   int reserved = 0;
27719   unixFile *pFile = (unixFile*)id;
27720 
27721   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27722 
27723   assert( pFile );
27724 
27725   /* Check if a thread in this process holds such a lock */
27726   if( pFile->eFileLock>SHARED_LOCK ){
27727     reserved = 1;
27728   }
27729 
27730   /* Otherwise see if some other process holds it. */
27731   if( !reserved ){
27732     /* attempt to get the lock */
27733     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
27734     if( !lrc ){
27735       /* got the lock, unlock it */
27736       lrc = robust_flock(pFile->h, LOCK_UN);
27737       if ( lrc ) {
27738         int tErrno = errno;
27739         /* unlock failed with an error */
27740         lrc = SQLITE_IOERR_UNLOCK;
27741         if( IS_LOCK_ERROR(lrc) ){
27742           storeLastErrno(pFile, tErrno);
27743           rc = lrc;
27744         }
27745       }
27746     } else {
27747       int tErrno = errno;
27748       reserved = 1;
27749       /* someone else might have it reserved */
27750       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27751       if( IS_LOCK_ERROR(lrc) ){
27752         storeLastErrno(pFile, tErrno);
27753         rc = lrc;
27754       }
27755     }
27756   }
27757   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
27758 
27759 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27760   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27761     rc = SQLITE_OK;
27762     reserved=1;
27763   }
27764 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27765   *pResOut = reserved;
27766   return rc;
27767 }
27768 
27769 /*
27770 ** Lock the file with the lock specified by parameter eFileLock - one
27771 ** of the following:
27772 **
27773 **     (1) SHARED_LOCK
27774 **     (2) RESERVED_LOCK
27775 **     (3) PENDING_LOCK
27776 **     (4) EXCLUSIVE_LOCK
27777 **
27778 ** Sometimes when requesting one lock state, additional lock states
27779 ** are inserted in between.  The locking might fail on one of the later
27780 ** transitions leaving the lock state different from what it started but
27781 ** still short of its goal.  The following chart shows the allowed
27782 ** transitions and the inserted intermediate states:
27783 **
27784 **    UNLOCKED -> SHARED
27785 **    SHARED -> RESERVED
27786 **    SHARED -> (PENDING) -> EXCLUSIVE
27787 **    RESERVED -> (PENDING) -> EXCLUSIVE
27788 **    PENDING -> EXCLUSIVE
27789 **
27790 ** flock() only really support EXCLUSIVE locks.  We track intermediate
27791 ** lock states in the sqlite3_file structure, but all locks SHARED or
27792 ** above are really EXCLUSIVE locks and exclude all other processes from
27793 ** access the file.
27794 **
27795 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27796 ** routine to lower a locking level.
27797 */
27798 static int flockLock(sqlite3_file *id, int eFileLock) {
27799   int rc = SQLITE_OK;
27800   unixFile *pFile = (unixFile*)id;
27801 
27802   assert( pFile );
27803 
27804   /* if we already have a lock, it is exclusive.
27805   ** Just adjust level and punt on outta here. */
27806   if (pFile->eFileLock > NO_LOCK) {
27807     pFile->eFileLock = eFileLock;
27808     return SQLITE_OK;
27809   }
27810 
27811   /* grab an exclusive lock */
27812 
27813   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
27814     int tErrno = errno;
27815     /* didn't get, must be busy */
27816     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27817     if( IS_LOCK_ERROR(rc) ){
27818       storeLastErrno(pFile, tErrno);
27819     }
27820   } else {
27821     /* got it, set the type and return ok */
27822     pFile->eFileLock = eFileLock;
27823   }
27824   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
27825            rc==SQLITE_OK ? "ok" : "failed"));
27826 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27827   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27828     rc = SQLITE_BUSY;
27829   }
27830 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27831   return rc;
27832 }
27833 
27834 
27835 /*
27836 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27837 ** must be either NO_LOCK or SHARED_LOCK.
27838 **
27839 ** If the locking level of the file descriptor is already at or below
27840 ** the requested locking level, this routine is a no-op.
27841 */
27842 static int flockUnlock(sqlite3_file *id, int eFileLock) {
27843   unixFile *pFile = (unixFile*)id;
27844 
27845   assert( pFile );
27846   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
27847            pFile->eFileLock, osGetpid(0)));
27848   assert( eFileLock<=SHARED_LOCK );
27849 
27850   /* no-op if possible */
27851   if( pFile->eFileLock==eFileLock ){
27852     return SQLITE_OK;
27853   }
27854 
27855   /* shared can just be set because we always have an exclusive */
27856   if (eFileLock==SHARED_LOCK) {
27857     pFile->eFileLock = eFileLock;
27858     return SQLITE_OK;
27859   }
27860 
27861   /* no, really, unlock. */
27862   if( robust_flock(pFile->h, LOCK_UN) ){
27863 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27864     return SQLITE_OK;
27865 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27866     return SQLITE_IOERR_UNLOCK;
27867   }else{
27868     pFile->eFileLock = NO_LOCK;
27869     return SQLITE_OK;
27870   }
27871 }
27872 
27873 /*
27874 ** Close a file.
27875 */
27876 static int flockClose(sqlite3_file *id) {
27877   int rc = SQLITE_OK;
27878   if( id ){
27879     flockUnlock(id, NO_LOCK);
27880     rc = closeUnixFile(id);
27881   }
27882   return rc;
27883 }
27884 
27885 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
27886 
27887 /******************* End of the flock lock implementation *********************
27888 ******************************************************************************/
27889 
27890 /******************************************************************************
27891 ************************ Begin Named Semaphore Locking ************************
27892 **
27893 ** Named semaphore locking is only supported on VxWorks.
27894 **
27895 ** Semaphore locking is like dot-lock and flock in that it really only
27896 ** supports EXCLUSIVE locking.  Only a single process can read or write
27897 ** the database file at a time.  This reduces potential concurrency, but
27898 ** makes the lock implementation much easier.
27899 */
27900 #if OS_VXWORKS
27901 
27902 /*
27903 ** This routine checks if there is a RESERVED lock held on the specified
27904 ** file by this or any other process. If such a lock is held, set *pResOut
27905 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27906 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27907 */
27908 static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
27909   int rc = SQLITE_OK;
27910   int reserved = 0;
27911   unixFile *pFile = (unixFile*)id;
27912 
27913   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27914 
27915   assert( pFile );
27916 
27917   /* Check if a thread in this process holds such a lock */
27918   if( pFile->eFileLock>SHARED_LOCK ){
27919     reserved = 1;
27920   }
27921 
27922   /* Otherwise see if some other process holds it. */
27923   if( !reserved ){
27924     sem_t *pSem = pFile->pInode->pSem;
27925 
27926     if( sem_trywait(pSem)==-1 ){
27927       int tErrno = errno;
27928       if( EAGAIN != tErrno ){
27929         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
27930         storeLastErrno(pFile, tErrno);
27931       } else {
27932         /* someone else has the lock when we are in NO_LOCK */
27933         reserved = (pFile->eFileLock < SHARED_LOCK);
27934       }
27935     }else{
27936       /* we could have it if we want it */
27937       sem_post(pSem);
27938     }
27939   }
27940   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
27941 
27942   *pResOut = reserved;
27943   return rc;
27944 }
27945 
27946 /*
27947 ** Lock the file with the lock specified by parameter eFileLock - one
27948 ** of the following:
27949 **
27950 **     (1) SHARED_LOCK
27951 **     (2) RESERVED_LOCK
27952 **     (3) PENDING_LOCK
27953 **     (4) EXCLUSIVE_LOCK
27954 **
27955 ** Sometimes when requesting one lock state, additional lock states
27956 ** are inserted in between.  The locking might fail on one of the later
27957 ** transitions leaving the lock state different from what it started but
27958 ** still short of its goal.  The following chart shows the allowed
27959 ** transitions and the inserted intermediate states:
27960 **
27961 **    UNLOCKED -> SHARED
27962 **    SHARED -> RESERVED
27963 **    SHARED -> (PENDING) -> EXCLUSIVE
27964 **    RESERVED -> (PENDING) -> EXCLUSIVE
27965 **    PENDING -> EXCLUSIVE
27966 **
27967 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
27968 ** lock states in the sqlite3_file structure, but all locks SHARED or
27969 ** above are really EXCLUSIVE locks and exclude all other processes from
27970 ** access the file.
27971 **
27972 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27973 ** routine to lower a locking level.
27974 */
27975 static int semXLock(sqlite3_file *id, int eFileLock) {
27976   unixFile *pFile = (unixFile*)id;
27977   sem_t *pSem = pFile->pInode->pSem;
27978   int rc = SQLITE_OK;
27979 
27980   /* if we already have a lock, it is exclusive.
27981   ** Just adjust level and punt on outta here. */
27982   if (pFile->eFileLock > NO_LOCK) {
27983     pFile->eFileLock = eFileLock;
27984     rc = SQLITE_OK;
27985     goto sem_end_lock;
27986   }
27987 
27988   /* lock semaphore now but bail out when already locked. */
27989   if( sem_trywait(pSem)==-1 ){
27990     rc = SQLITE_BUSY;
27991     goto sem_end_lock;
27992   }
27993 
27994   /* got it, set the type and return ok */
27995   pFile->eFileLock = eFileLock;
27996 
27997  sem_end_lock:
27998   return rc;
27999 }
28000 
28001 /*
28002 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28003 ** must be either NO_LOCK or SHARED_LOCK.
28004 **
28005 ** If the locking level of the file descriptor is already at or below
28006 ** the requested locking level, this routine is a no-op.
28007 */
28008 static int semXUnlock(sqlite3_file *id, int eFileLock) {
28009   unixFile *pFile = (unixFile*)id;
28010   sem_t *pSem = pFile->pInode->pSem;
28011 
28012   assert( pFile );
28013   assert( pSem );
28014   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
28015            pFile->eFileLock, osGetpid(0)));
28016   assert( eFileLock<=SHARED_LOCK );
28017 
28018   /* no-op if possible */
28019   if( pFile->eFileLock==eFileLock ){
28020     return SQLITE_OK;
28021   }
28022 
28023   /* shared can just be set because we always have an exclusive */
28024   if (eFileLock==SHARED_LOCK) {
28025     pFile->eFileLock = eFileLock;
28026     return SQLITE_OK;
28027   }
28028 
28029   /* no, really unlock. */
28030   if ( sem_post(pSem)==-1 ) {
28031     int rc, tErrno = errno;
28032     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
28033     if( IS_LOCK_ERROR(rc) ){
28034       storeLastErrno(pFile, tErrno);
28035     }
28036     return rc;
28037   }
28038   pFile->eFileLock = NO_LOCK;
28039   return SQLITE_OK;
28040 }
28041 
28042 /*
28043  ** Close a file.
28044  */
28045 static int semXClose(sqlite3_file *id) {
28046   if( id ){
28047     unixFile *pFile = (unixFile*)id;
28048     semXUnlock(id, NO_LOCK);
28049     assert( pFile );
28050     unixEnterMutex();
28051     releaseInodeInfo(pFile);
28052     unixLeaveMutex();
28053     closeUnixFile(id);
28054   }
28055   return SQLITE_OK;
28056 }
28057 
28058 #endif /* OS_VXWORKS */
28059 /*
28060 ** Named semaphore locking is only available on VxWorks.
28061 **
28062 *************** End of the named semaphore lock implementation ****************
28063 ******************************************************************************/
28064 
28065 
28066 /******************************************************************************
28067 *************************** Begin AFP Locking *********************************
28068 **
28069 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
28070 ** on Apple Macintosh computers - both OS9 and OSX.
28071 **
28072 ** Third-party implementations of AFP are available.  But this code here
28073 ** only works on OSX.
28074 */
28075 
28076 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28077 /*
28078 ** The afpLockingContext structure contains all afp lock specific state
28079 */
28080 typedef struct afpLockingContext afpLockingContext;
28081 struct afpLockingContext {
28082   int reserved;
28083   const char *dbPath;             /* Name of the open file */
28084 };
28085 
28086 struct ByteRangeLockPB2
28087 {
28088   unsigned long long offset;        /* offset to first byte to lock */
28089   unsigned long long length;        /* nbr of bytes to lock */
28090   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
28091   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
28092   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
28093   int fd;                           /* file desc to assoc this lock with */
28094 };
28095 
28096 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
28097 
28098 /*
28099 ** This is a utility for setting or clearing a bit-range lock on an
28100 ** AFP filesystem.
28101 **
28102 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
28103 */
28104 static int afpSetLock(
28105   const char *path,              /* Name of the file to be locked or unlocked */
28106   unixFile *pFile,               /* Open file descriptor on path */
28107   unsigned long long offset,     /* First byte to be locked */
28108   unsigned long long length,     /* Number of bytes to lock */
28109   int setLockFlag                /* True to set lock.  False to clear lock */
28110 ){
28111   struct ByteRangeLockPB2 pb;
28112   int err;
28113 
28114   pb.unLockFlag = setLockFlag ? 0 : 1;
28115   pb.startEndFlag = 0;
28116   pb.offset = offset;
28117   pb.length = length;
28118   pb.fd = pFile->h;
28119 
28120   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
28121     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
28122     offset, length));
28123   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
28124   if ( err==-1 ) {
28125     int rc;
28126     int tErrno = errno;
28127     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
28128              path, tErrno, strerror(tErrno)));
28129 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
28130     rc = SQLITE_BUSY;
28131 #else
28132     rc = sqliteErrorFromPosixError(tErrno,
28133                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
28134 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
28135     if( IS_LOCK_ERROR(rc) ){
28136       storeLastErrno(pFile, tErrno);
28137     }
28138     return rc;
28139   } else {
28140     return SQLITE_OK;
28141   }
28142 }
28143 
28144 /*
28145 ** This routine checks if there is a RESERVED lock held on the specified
28146 ** file by this or any other process. If such a lock is held, set *pResOut
28147 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
28148 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
28149 */
28150 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
28151   int rc = SQLITE_OK;
28152   int reserved = 0;
28153   unixFile *pFile = (unixFile*)id;
28154   afpLockingContext *context;
28155 
28156   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
28157 
28158   assert( pFile );
28159   context = (afpLockingContext *) pFile->lockingContext;
28160   if( context->reserved ){
28161     *pResOut = 1;
28162     return SQLITE_OK;
28163   }
28164   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
28165 
28166   /* Check if a thread in this process holds such a lock */
28167   if( pFile->pInode->eFileLock>SHARED_LOCK ){
28168     reserved = 1;
28169   }
28170 
28171   /* Otherwise see if some other process holds it.
28172    */
28173   if( !reserved ){
28174     /* lock the RESERVED byte */
28175     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
28176     if( SQLITE_OK==lrc ){
28177       /* if we succeeded in taking the reserved lock, unlock it to restore
28178       ** the original state */
28179       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
28180     } else {
28181       /* if we failed to get the lock then someone else must have it */
28182       reserved = 1;
28183     }
28184     if( IS_LOCK_ERROR(lrc) ){
28185       rc=lrc;
28186     }
28187   }
28188 
28189   unixLeaveMutex();
28190   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
28191 
28192   *pResOut = reserved;
28193   return rc;
28194 }
28195 
28196 /*
28197 ** Lock the file with the lock specified by parameter eFileLock - one
28198 ** of the following:
28199 **
28200 **     (1) SHARED_LOCK
28201 **     (2) RESERVED_LOCK
28202 **     (3) PENDING_LOCK
28203 **     (4) EXCLUSIVE_LOCK
28204 **
28205 ** Sometimes when requesting one lock state, additional lock states
28206 ** are inserted in between.  The locking might fail on one of the later
28207 ** transitions leaving the lock state different from what it started but
28208 ** still short of its goal.  The following chart shows the allowed
28209 ** transitions and the inserted intermediate states:
28210 **
28211 **    UNLOCKED -> SHARED
28212 **    SHARED -> RESERVED
28213 **    SHARED -> (PENDING) -> EXCLUSIVE
28214 **    RESERVED -> (PENDING) -> EXCLUSIVE
28215 **    PENDING -> EXCLUSIVE
28216 **
28217 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
28218 ** routine to lower a locking level.
28219 */
28220 static int afpLock(sqlite3_file *id, int eFileLock){
28221   int rc = SQLITE_OK;
28222   unixFile *pFile = (unixFile*)id;
28223   unixInodeInfo *pInode = pFile->pInode;
28224   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
28225 
28226   assert( pFile );
28227   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
28228            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
28229            azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
28230 
28231   /* If there is already a lock of this type or more restrictive on the
28232   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
28233   ** unixEnterMutex() hasn't been called yet.
28234   */
28235   if( pFile->eFileLock>=eFileLock ){
28236     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
28237            azFileLock(eFileLock)));
28238     return SQLITE_OK;
28239   }
28240 
28241   /* Make sure the locking sequence is correct
28242   **  (1) We never move from unlocked to anything higher than shared lock.
28243   **  (2) SQLite never explicitly requests a pendig lock.
28244   **  (3) A shared lock is always held when a reserve lock is requested.
28245   */
28246   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
28247   assert( eFileLock!=PENDING_LOCK );
28248   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
28249 
28250   /* This mutex is needed because pFile->pInode is shared across threads
28251   */
28252   unixEnterMutex();
28253   pInode = pFile->pInode;
28254 
28255   /* If some thread using this PID has a lock via a different unixFile*
28256   ** handle that precludes the requested lock, return BUSY.
28257   */
28258   if( (pFile->eFileLock!=pInode->eFileLock &&
28259        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
28260      ){
28261     rc = SQLITE_BUSY;
28262     goto afp_end_lock;
28263   }
28264 
28265   /* If a SHARED lock is requested, and some thread using this PID already
28266   ** has a SHARED or RESERVED lock, then increment reference counts and
28267   ** return SQLITE_OK.
28268   */
28269   if( eFileLock==SHARED_LOCK &&
28270      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
28271     assert( eFileLock==SHARED_LOCK );
28272     assert( pFile->eFileLock==0 );
28273     assert( pInode->nShared>0 );
28274     pFile->eFileLock = SHARED_LOCK;
28275     pInode->nShared++;
28276     pInode->nLock++;
28277     goto afp_end_lock;
28278   }
28279 
28280   /* A PENDING lock is needed before acquiring a SHARED lock and before
28281   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
28282   ** be released.
28283   */
28284   if( eFileLock==SHARED_LOCK
28285       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
28286   ){
28287     int failed;
28288     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
28289     if (failed) {
28290       rc = failed;
28291       goto afp_end_lock;
28292     }
28293   }
28294 
28295   /* If control gets to this point, then actually go ahead and make
28296   ** operating system calls for the specified lock.
28297   */
28298   if( eFileLock==SHARED_LOCK ){
28299     int lrc1, lrc2, lrc1Errno = 0;
28300     long lk, mask;
28301 
28302     assert( pInode->nShared==0 );
28303     assert( pInode->eFileLock==0 );
28304 
28305     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
28306     /* Now get the read-lock SHARED_LOCK */
28307     /* note that the quality of the randomness doesn't matter that much */
28308     lk = random();
28309     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
28310     lrc1 = afpSetLock(context->dbPath, pFile,
28311           SHARED_FIRST+pInode->sharedByte, 1, 1);
28312     if( IS_LOCK_ERROR(lrc1) ){
28313       lrc1Errno = pFile->lastErrno;
28314     }
28315     /* Drop the temporary PENDING lock */
28316     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
28317 
28318     if( IS_LOCK_ERROR(lrc1) ) {
28319       storeLastErrno(pFile, lrc1Errno);
28320       rc = lrc1;
28321       goto afp_end_lock;
28322     } else if( IS_LOCK_ERROR(lrc2) ){
28323       rc = lrc2;
28324       goto afp_end_lock;
28325     } else if( lrc1 != SQLITE_OK ) {
28326       rc = lrc1;
28327     } else {
28328       pFile->eFileLock = SHARED_LOCK;
28329       pInode->nLock++;
28330       pInode->nShared = 1;
28331     }
28332   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
28333     /* We are trying for an exclusive lock but another thread in this
28334      ** same process is still holding a shared lock. */
28335     rc = SQLITE_BUSY;
28336   }else{
28337     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
28338     ** assumed that there is a SHARED or greater lock on the file
28339     ** already.
28340     */
28341     int failed = 0;
28342     assert( 0!=pFile->eFileLock );
28343     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
28344         /* Acquire a RESERVED lock */
28345         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
28346       if( !failed ){
28347         context->reserved = 1;
28348       }
28349     }
28350     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
28351       /* Acquire an EXCLUSIVE lock */
28352 
28353       /* Remove the shared lock before trying the range.  we'll need to
28354       ** reestablish the shared lock if we can't get the  afpUnlock
28355       */
28356       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
28357                          pInode->sharedByte, 1, 0)) ){
28358         int failed2 = SQLITE_OK;
28359         /* now attemmpt to get the exclusive lock range */
28360         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
28361                                SHARED_SIZE, 1);
28362         if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
28363                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
28364           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
28365           ** a critical I/O error
28366           */
28367           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
28368                SQLITE_IOERR_LOCK;
28369           goto afp_end_lock;
28370         }
28371       }else{
28372         rc = failed;
28373       }
28374     }
28375     if( failed ){
28376       rc = failed;
28377     }
28378   }
28379 
28380   if( rc==SQLITE_OK ){
28381     pFile->eFileLock = eFileLock;
28382     pInode->eFileLock = eFileLock;
28383   }else if( eFileLock==EXCLUSIVE_LOCK ){
28384     pFile->eFileLock = PENDING_LOCK;
28385     pInode->eFileLock = PENDING_LOCK;
28386   }
28387 
28388 afp_end_lock:
28389   unixLeaveMutex();
28390   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
28391          rc==SQLITE_OK ? "ok" : "failed"));
28392   return rc;
28393 }
28394 
28395 /*
28396 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28397 ** must be either NO_LOCK or SHARED_LOCK.
28398 **
28399 ** If the locking level of the file descriptor is already at or below
28400 ** the requested locking level, this routine is a no-op.
28401 */
28402 static int afpUnlock(sqlite3_file *id, int eFileLock) {
28403   int rc = SQLITE_OK;
28404   unixFile *pFile = (unixFile*)id;
28405   unixInodeInfo *pInode;
28406   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
28407   int skipShared = 0;
28408 #ifdef SQLITE_TEST
28409   int h = pFile->h;
28410 #endif
28411 
28412   assert( pFile );
28413   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
28414            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
28415            osGetpid(0)));
28416 
28417   assert( eFileLock<=SHARED_LOCK );
28418   if( pFile->eFileLock<=eFileLock ){
28419     return SQLITE_OK;
28420   }
28421   unixEnterMutex();
28422   pInode = pFile->pInode;
28423   assert( pInode->nShared!=0 );
28424   if( pFile->eFileLock>SHARED_LOCK ){
28425     assert( pInode->eFileLock==pFile->eFileLock );
28426     SimulateIOErrorBenign(1);
28427     SimulateIOError( h=(-1) )
28428     SimulateIOErrorBenign(0);
28429 
28430 #ifdef SQLITE_DEBUG
28431     /* When reducing a lock such that other processes can start
28432     ** reading the database file again, make sure that the
28433     ** transaction counter was updated if any part of the database
28434     ** file changed.  If the transaction counter is not updated,
28435     ** other connections to the same file might not realize that
28436     ** the file has changed and hence might not know to flush their
28437     ** cache.  The use of a stale cache can lead to database corruption.
28438     */
28439     assert( pFile->inNormalWrite==0
28440            || pFile->dbUpdate==0
28441            || pFile->transCntrChng==1 );
28442     pFile->inNormalWrite = 0;
28443 #endif
28444 
28445     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
28446       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
28447       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
28448         /* only re-establish the shared lock if necessary */
28449         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
28450         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
28451       } else {
28452         skipShared = 1;
28453       }
28454     }
28455     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
28456       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
28457     }
28458     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
28459       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
28460       if( !rc ){
28461         context->reserved = 0;
28462       }
28463     }
28464     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
28465       pInode->eFileLock = SHARED_LOCK;
28466     }
28467   }
28468   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
28469 
28470     /* Decrement the shared lock counter.  Release the lock using an
28471     ** OS call only when all threads in this same process have released
28472     ** the lock.
28473     */
28474     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
28475     pInode->nShared--;
28476     if( pInode->nShared==0 ){
28477       SimulateIOErrorBenign(1);
28478       SimulateIOError( h=(-1) )
28479       SimulateIOErrorBenign(0);
28480       if( !skipShared ){
28481         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
28482       }
28483       if( !rc ){
28484         pInode->eFileLock = NO_LOCK;
28485         pFile->eFileLock = NO_LOCK;
28486       }
28487     }
28488     if( rc==SQLITE_OK ){
28489       pInode->nLock--;
28490       assert( pInode->nLock>=0 );
28491       if( pInode->nLock==0 ){
28492         closePendingFds(pFile);
28493       }
28494     }
28495   }
28496 
28497   unixLeaveMutex();
28498   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
28499   return rc;
28500 }
28501 
28502 /*
28503 ** Close a file & cleanup AFP specific locking context
28504 */
28505 static int afpClose(sqlite3_file *id) {
28506   int rc = SQLITE_OK;
28507   if( id ){
28508     unixFile *pFile = (unixFile*)id;
28509     afpUnlock(id, NO_LOCK);
28510     unixEnterMutex();
28511     if( pFile->pInode && pFile->pInode->nLock ){
28512       /* If there are outstanding locks, do not actually close the file just
28513       ** yet because that would clear those locks.  Instead, add the file
28514       ** descriptor to pInode->aPending.  It will be automatically closed when
28515       ** the last lock is cleared.
28516       */
28517       setPendingFd(pFile);
28518     }
28519     releaseInodeInfo(pFile);
28520     sqlite3_free(pFile->lockingContext);
28521     rc = closeUnixFile(id);
28522     unixLeaveMutex();
28523   }
28524   return rc;
28525 }
28526 
28527 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28528 /*
28529 ** The code above is the AFP lock implementation.  The code is specific
28530 ** to MacOSX and does not work on other unix platforms.  No alternative
28531 ** is available.  If you don't compile for a mac, then the "unix-afp"
28532 ** VFS is not available.
28533 **
28534 ********************* End of the AFP lock implementation **********************
28535 ******************************************************************************/
28536 
28537 /******************************************************************************
28538 *************************** Begin NFS Locking ********************************/
28539 
28540 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28541 /*
28542  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28543  ** must be either NO_LOCK or SHARED_LOCK.
28544  **
28545  ** If the locking level of the file descriptor is already at or below
28546  ** the requested locking level, this routine is a no-op.
28547  */
28548 static int nfsUnlock(sqlite3_file *id, int eFileLock){
28549   return posixUnlock(id, eFileLock, 1);
28550 }
28551 
28552 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28553 /*
28554 ** The code above is the NFS lock implementation.  The code is specific
28555 ** to MacOSX and does not work on other unix platforms.  No alternative
28556 ** is available.
28557 **
28558 ********************* End of the NFS lock implementation **********************
28559 ******************************************************************************/
28560 
28561 /******************************************************************************
28562 **************** Non-locking sqlite3_file methods *****************************
28563 **
28564 ** The next division contains implementations for all methods of the
28565 ** sqlite3_file object other than the locking methods.  The locking
28566 ** methods were defined in divisions above (one locking method per
28567 ** division).  Those methods that are common to all locking modes
28568 ** are gather together into this division.
28569 */
28570 
28571 /*
28572 ** Seek to the offset passed as the second argument, then read cnt
28573 ** bytes into pBuf. Return the number of bytes actually read.
28574 **
28575 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
28576 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
28577 ** one system to another.  Since SQLite does not define USE_PREAD
28578 ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
28579 ** See tickets #2741 and #2681.
28580 **
28581 ** To avoid stomping the errno value on a failed read the lastErrno value
28582 ** is set before returning.
28583 */
28584 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
28585   int got;
28586   int prior = 0;
28587 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
28588   i64 newOffset;
28589 #endif
28590   TIMER_START;
28591   assert( cnt==(cnt&0x1ffff) );
28592   assert( id->h>2 );
28593   cnt &= 0x1ffff;
28594   do{
28595 #if defined(USE_PREAD)
28596     got = osPread(id->h, pBuf, cnt, offset);
28597     SimulateIOError( got = -1 );
28598 #elif defined(USE_PREAD64)
28599     got = osPread64(id->h, pBuf, cnt, offset);
28600     SimulateIOError( got = -1 );
28601 #else
28602     newOffset = lseek(id->h, offset, SEEK_SET);
28603     SimulateIOError( newOffset-- );
28604     if( newOffset!=offset ){
28605       if( newOffset == -1 ){
28606         storeLastErrno((unixFile*)id, errno);
28607       }else{
28608         storeLastErrno((unixFile*)id, 0);
28609       }
28610       return -1;
28611     }
28612     got = osRead(id->h, pBuf, cnt);
28613 #endif
28614     if( got==cnt ) break;
28615     if( got<0 ){
28616       if( errno==EINTR ){ got = 1; continue; }
28617       prior = 0;
28618       storeLastErrno((unixFile*)id,  errno);
28619       break;
28620     }else if( got>0 ){
28621       cnt -= got;
28622       offset += got;
28623       prior += got;
28624       pBuf = (void*)(got + (char*)pBuf);
28625     }
28626   }while( got>0 );
28627   TIMER_END;
28628   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
28629             id->h, got+prior, offset-prior, TIMER_ELAPSED));
28630   return got+prior;
28631 }
28632 
28633 /*
28634 ** Read data from a file into a buffer.  Return SQLITE_OK if all
28635 ** bytes were read successfully and SQLITE_IOERR if anything goes
28636 ** wrong.
28637 */
28638 static int unixRead(
28639   sqlite3_file *id,
28640   void *pBuf,
28641   int amt,
28642   sqlite3_int64 offset
28643 ){
28644   unixFile *pFile = (unixFile *)id;
28645   int got;
28646   assert( id );
28647   assert( offset>=0 );
28648   assert( amt>0 );
28649 
28650   /* If this is a database file (not a journal, master-journal or temp
28651   ** file), the bytes in the locking range should never be read or written. */
28652 #if 0
28653   assert( pFile->pUnused==0
28654        || offset>=PENDING_BYTE+512
28655        || offset+amt<=PENDING_BYTE
28656   );
28657 #endif
28658 
28659 #if SQLITE_MAX_MMAP_SIZE>0
28660   /* Deal with as much of this read request as possible by transfering
28661   ** data from the memory mapping using memcpy().  */
28662   if( offset<pFile->mmapSize ){
28663     if( offset+amt <= pFile->mmapSize ){
28664       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
28665       return SQLITE_OK;
28666     }else{
28667       int nCopy = pFile->mmapSize - offset;
28668       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
28669       pBuf = &((u8 *)pBuf)[nCopy];
28670       amt -= nCopy;
28671       offset += nCopy;
28672     }
28673   }
28674 #endif
28675 
28676   got = seekAndRead(pFile, offset, pBuf, amt);
28677   if( got==amt ){
28678     return SQLITE_OK;
28679   }else if( got<0 ){
28680     /* lastErrno set by seekAndRead */
28681     return SQLITE_IOERR_READ;
28682   }else{
28683     storeLastErrno(pFile, 0);   /* not a system error */
28684     /* Unread parts of the buffer must be zero-filled */
28685     memset(&((char*)pBuf)[got], 0, amt-got);
28686     return SQLITE_IOERR_SHORT_READ;
28687   }
28688 }
28689 
28690 /*
28691 ** Attempt to seek the file-descriptor passed as the first argument to
28692 ** absolute offset iOff, then attempt to write nBuf bytes of data from
28693 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
28694 ** return the actual number of bytes written (which may be less than
28695 ** nBuf).
28696 */
28697 static int seekAndWriteFd(
28698   int fd,                         /* File descriptor to write to */
28699   i64 iOff,                       /* File offset to begin writing at */
28700   const void *pBuf,               /* Copy data from this buffer to the file */
28701   int nBuf,                       /* Size of buffer pBuf in bytes */
28702   int *piErrno                    /* OUT: Error number if error occurs */
28703 ){
28704   int rc = 0;                     /* Value returned by system call */
28705 
28706   assert( nBuf==(nBuf&0x1ffff) );
28707   assert( fd>2 );
28708   nBuf &= 0x1ffff;
28709   TIMER_START;
28710 
28711 #if defined(USE_PREAD)
28712   do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
28713 #elif defined(USE_PREAD64)
28714   do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
28715 #else
28716   do{
28717     i64 iSeek = lseek(fd, iOff, SEEK_SET);
28718     SimulateIOError( iSeek-- );
28719 
28720     if( iSeek!=iOff ){
28721       if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
28722       return -1;
28723     }
28724     rc = osWrite(fd, pBuf, nBuf);
28725   }while( rc<0 && errno==EINTR );
28726 #endif
28727 
28728   TIMER_END;
28729   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
28730 
28731   if( rc<0 && piErrno ) *piErrno = errno;
28732   return rc;
28733 }
28734 
28735 
28736 /*
28737 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
28738 ** Return the number of bytes actually read.  Update the offset.
28739 **
28740 ** To avoid stomping the errno value on a failed write the lastErrno value
28741 ** is set before returning.
28742 */
28743 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
28744   return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
28745 }
28746 
28747 
28748 /*
28749 ** Write data from a buffer into a file.  Return SQLITE_OK on success
28750 ** or some other error code on failure.
28751 */
28752 static int unixWrite(
28753   sqlite3_file *id,
28754   const void *pBuf,
28755   int amt,
28756   sqlite3_int64 offset
28757 ){
28758   unixFile *pFile = (unixFile*)id;
28759   int wrote = 0;
28760   assert( id );
28761   assert( amt>0 );
28762 
28763   /* If this is a database file (not a journal, master-journal or temp
28764   ** file), the bytes in the locking range should never be read or written. */
28765 #if 0
28766   assert( pFile->pUnused==0
28767        || offset>=PENDING_BYTE+512
28768        || offset+amt<=PENDING_BYTE
28769   );
28770 #endif
28771 
28772 #ifdef SQLITE_DEBUG
28773   /* If we are doing a normal write to a database file (as opposed to
28774   ** doing a hot-journal rollback or a write to some file other than a
28775   ** normal database file) then record the fact that the database
28776   ** has changed.  If the transaction counter is modified, record that
28777   ** fact too.
28778   */
28779   if( pFile->inNormalWrite ){
28780     pFile->dbUpdate = 1;  /* The database has been modified */
28781     if( offset<=24 && offset+amt>=27 ){
28782       int rc;
28783       char oldCntr[4];
28784       SimulateIOErrorBenign(1);
28785       rc = seekAndRead(pFile, 24, oldCntr, 4);
28786       SimulateIOErrorBenign(0);
28787       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
28788         pFile->transCntrChng = 1;  /* The transaction counter has changed */
28789       }
28790     }
28791   }
28792 #endif
28793 
28794 #if SQLITE_MAX_MMAP_SIZE>0
28795   /* Deal with as much of this write request as possible by transfering
28796   ** data from the memory mapping using memcpy().  */
28797   if( offset<pFile->mmapSize ){
28798     if( offset+amt <= pFile->mmapSize ){
28799       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
28800       return SQLITE_OK;
28801     }else{
28802       int nCopy = pFile->mmapSize - offset;
28803       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
28804       pBuf = &((u8 *)pBuf)[nCopy];
28805       amt -= nCopy;
28806       offset += nCopy;
28807     }
28808   }
28809 #endif
28810 
28811   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
28812     amt -= wrote;
28813     offset += wrote;
28814     pBuf = &((char*)pBuf)[wrote];
28815   }
28816   SimulateIOError(( wrote=(-1), amt=1 ));
28817   SimulateDiskfullError(( wrote=0, amt=1 ));
28818 
28819   if( amt>0 ){
28820     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
28821       /* lastErrno set by seekAndWrite */
28822       return SQLITE_IOERR_WRITE;
28823     }else{
28824       storeLastErrno(pFile, 0); /* not a system error */
28825       return SQLITE_FULL;
28826     }
28827   }
28828 
28829   return SQLITE_OK;
28830 }
28831 
28832 #ifdef SQLITE_TEST
28833 /*
28834 ** Count the number of fullsyncs and normal syncs.  This is used to test
28835 ** that syncs and fullsyncs are occurring at the right times.
28836 */
28837 SQLITE_API int sqlite3_sync_count = 0;
28838 SQLITE_API int sqlite3_fullsync_count = 0;
28839 #endif
28840 
28841 /*
28842 ** We do not trust systems to provide a working fdatasync().  Some do.
28843 ** Others do no.  To be safe, we will stick with the (slightly slower)
28844 ** fsync(). If you know that your system does support fdatasync() correctly,
28845 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
28846 */
28847 #if !defined(fdatasync) && !HAVE_FDATASYNC
28848 # define fdatasync fsync
28849 #endif
28850 
28851 /*
28852 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
28853 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
28854 ** only available on Mac OS X.  But that could change.
28855 */
28856 #ifdef F_FULLFSYNC
28857 # define HAVE_FULLFSYNC 1
28858 #else
28859 # define HAVE_FULLFSYNC 0
28860 #endif
28861 
28862 
28863 /*
28864 ** The fsync() system call does not work as advertised on many
28865 ** unix systems.  The following procedure is an attempt to make
28866 ** it work better.
28867 **
28868 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
28869 ** for testing when we want to run through the test suite quickly.
28870 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
28871 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
28872 ** or power failure will likely corrupt the database file.
28873 **
28874 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
28875 ** The idea behind dataOnly is that it should only write the file content
28876 ** to disk, not the inode.  We only set dataOnly if the file size is
28877 ** unchanged since the file size is part of the inode.  However,
28878 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
28879 ** file size has changed.  The only real difference between fdatasync()
28880 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
28881 ** inode if the mtime or owner or other inode attributes have changed.
28882 ** We only care about the file size, not the other file attributes, so
28883 ** as far as SQLite is concerned, an fdatasync() is always adequate.
28884 ** So, we always use fdatasync() if it is available, regardless of
28885 ** the value of the dataOnly flag.
28886 */
28887 static int full_fsync(int fd, int fullSync, int dataOnly){
28888   int rc;
28889 
28890   /* The following "ifdef/elif/else/" block has the same structure as
28891   ** the one below. It is replicated here solely to avoid cluttering
28892   ** up the real code with the UNUSED_PARAMETER() macros.
28893   */
28894 #ifdef SQLITE_NO_SYNC
28895   UNUSED_PARAMETER(fd);
28896   UNUSED_PARAMETER(fullSync);
28897   UNUSED_PARAMETER(dataOnly);
28898 #elif HAVE_FULLFSYNC
28899   UNUSED_PARAMETER(dataOnly);
28900 #else
28901   UNUSED_PARAMETER(fullSync);
28902   UNUSED_PARAMETER(dataOnly);
28903 #endif
28904 
28905   /* Record the number of times that we do a normal fsync() and
28906   ** FULLSYNC.  This is used during testing to verify that this procedure
28907   ** gets called with the correct arguments.
28908   */
28909 #ifdef SQLITE_TEST
28910   if( fullSync ) sqlite3_fullsync_count++;
28911   sqlite3_sync_count++;
28912 #endif
28913 
28914   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
28915   ** no-op
28916   */
28917 #ifdef SQLITE_NO_SYNC
28918   rc = SQLITE_OK;
28919 #elif HAVE_FULLFSYNC
28920   if( fullSync ){
28921     rc = osFcntl(fd, F_FULLFSYNC, 0);
28922   }else{
28923     rc = 1;
28924   }
28925   /* If the FULLFSYNC failed, fall back to attempting an fsync().
28926   ** It shouldn't be possible for fullfsync to fail on the local
28927   ** file system (on OSX), so failure indicates that FULLFSYNC
28928   ** isn't supported for this file system. So, attempt an fsync
28929   ** and (for now) ignore the overhead of a superfluous fcntl call.
28930   ** It'd be better to detect fullfsync support once and avoid
28931   ** the fcntl call every time sync is called.
28932   */
28933   if( rc ) rc = fsync(fd);
28934 
28935 #elif defined(__APPLE__)
28936   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
28937   ** so currently we default to the macro that redefines fdatasync to fsync
28938   */
28939   rc = fsync(fd);
28940 #else
28941   rc = fdatasync(fd);
28942 #if OS_VXWORKS
28943   if( rc==-1 && errno==ENOTSUP ){
28944     rc = fsync(fd);
28945   }
28946 #endif /* OS_VXWORKS */
28947 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
28948 
28949   if( OS_VXWORKS && rc!= -1 ){
28950     rc = 0;
28951   }
28952   return rc;
28953 }
28954 
28955 /*
28956 ** Open a file descriptor to the directory containing file zFilename.
28957 ** If successful, *pFd is set to the opened file descriptor and
28958 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
28959 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
28960 ** value.
28961 **
28962 ** The directory file descriptor is used for only one thing - to
28963 ** fsync() a directory to make sure file creation and deletion events
28964 ** are flushed to disk.  Such fsyncs are not needed on newer
28965 ** journaling filesystems, but are required on older filesystems.
28966 **
28967 ** This routine can be overridden using the xSetSysCall interface.
28968 ** The ability to override this routine was added in support of the
28969 ** chromium sandbox.  Opening a directory is a security risk (we are
28970 ** told) so making it overrideable allows the chromium sandbox to
28971 ** replace this routine with a harmless no-op.  To make this routine
28972 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
28973 ** *pFd set to a negative number.
28974 **
28975 ** If SQLITE_OK is returned, the caller is responsible for closing
28976 ** the file descriptor *pFd using close().
28977 */
28978 static int openDirectory(const char *zFilename, int *pFd){
28979   int ii;
28980   int fd = -1;
28981   char zDirname[MAX_PATHNAME+1];
28982 
28983   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
28984   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
28985   if( ii>0 ){
28986     zDirname[ii] = '\0';
28987     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
28988     if( fd>=0 ){
28989       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
28990     }
28991   }
28992   *pFd = fd;
28993   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
28994 }
28995 
28996 /*
28997 ** Make sure all writes to a particular file are committed to disk.
28998 **
28999 ** If dataOnly==0 then both the file itself and its metadata (file
29000 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
29001 ** file data is synced.
29002 **
29003 ** Under Unix, also make sure that the directory entry for the file
29004 ** has been created by fsync-ing the directory that contains the file.
29005 ** If we do not do this and we encounter a power failure, the directory
29006 ** entry for the journal might not exist after we reboot.  The next
29007 ** SQLite to access the file will not know that the journal exists (because
29008 ** the directory entry for the journal was never created) and the transaction
29009 ** will not roll back - possibly leading to database corruption.
29010 */
29011 static int unixSync(sqlite3_file *id, int flags){
29012   int rc;
29013   unixFile *pFile = (unixFile*)id;
29014 
29015   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
29016   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
29017 
29018   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
29019   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
29020       || (flags&0x0F)==SQLITE_SYNC_FULL
29021   );
29022 
29023   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
29024   ** line is to test that doing so does not cause any problems.
29025   */
29026   SimulateDiskfullError( return SQLITE_FULL );
29027 
29028   assert( pFile );
29029   OSTRACE(("SYNC    %-3d\n", pFile->h));
29030   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
29031   SimulateIOError( rc=1 );
29032   if( rc ){
29033     storeLastErrno(pFile, errno);
29034     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
29035   }
29036 
29037   /* Also fsync the directory containing the file if the DIRSYNC flag
29038   ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
29039   ** are unable to fsync a directory, so ignore errors on the fsync.
29040   */
29041   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
29042     int dirfd;
29043     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
29044             HAVE_FULLFSYNC, isFullsync));
29045     rc = osOpenDirectory(pFile->zPath, &dirfd);
29046     if( rc==SQLITE_OK && dirfd>=0 ){
29047       full_fsync(dirfd, 0, 0);
29048       robust_close(pFile, dirfd, __LINE__);
29049     }else if( rc==SQLITE_CANTOPEN ){
29050       rc = SQLITE_OK;
29051     }
29052     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
29053   }
29054   return rc;
29055 }
29056 
29057 /*
29058 ** Truncate an open file to a specified size
29059 */
29060 static int unixTruncate(sqlite3_file *id, i64 nByte){
29061   unixFile *pFile = (unixFile *)id;
29062   int rc;
29063   assert( pFile );
29064   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
29065 
29066   /* If the user has configured a chunk-size for this file, truncate the
29067   ** file so that it consists of an integer number of chunks (i.e. the
29068   ** actual file size after the operation may be larger than the requested
29069   ** size).
29070   */
29071   if( pFile->szChunk>0 ){
29072     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
29073   }
29074 
29075   rc = robust_ftruncate(pFile->h, nByte);
29076   if( rc ){
29077     storeLastErrno(pFile, errno);
29078     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
29079   }else{
29080 #ifdef SQLITE_DEBUG
29081     /* If we are doing a normal write to a database file (as opposed to
29082     ** doing a hot-journal rollback or a write to some file other than a
29083     ** normal database file) and we truncate the file to zero length,
29084     ** that effectively updates the change counter.  This might happen
29085     ** when restoring a database using the backup API from a zero-length
29086     ** source.
29087     */
29088     if( pFile->inNormalWrite && nByte==0 ){
29089       pFile->transCntrChng = 1;
29090     }
29091 #endif
29092 
29093 #if SQLITE_MAX_MMAP_SIZE>0
29094     /* If the file was just truncated to a size smaller than the currently
29095     ** mapped region, reduce the effective mapping size as well. SQLite will
29096     ** use read() and write() to access data beyond this point from now on.
29097     */
29098     if( nByte<pFile->mmapSize ){
29099       pFile->mmapSize = nByte;
29100     }
29101 #endif
29102 
29103     return SQLITE_OK;
29104   }
29105 }
29106 
29107 /*
29108 ** Determine the current size of a file in bytes
29109 */
29110 static int unixFileSize(sqlite3_file *id, i64 *pSize){
29111   int rc;
29112   struct stat buf;
29113   assert( id );
29114   rc = osFstat(((unixFile*)id)->h, &buf);
29115   SimulateIOError( rc=1 );
29116   if( rc!=0 ){
29117     storeLastErrno((unixFile*)id, errno);
29118     return SQLITE_IOERR_FSTAT;
29119   }
29120   *pSize = buf.st_size;
29121 
29122   /* When opening a zero-size database, the findInodeInfo() procedure
29123   ** writes a single byte into that file in order to work around a bug
29124   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
29125   ** layers, we need to report this file size as zero even though it is
29126   ** really 1.   Ticket #3260.
29127   */
29128   if( *pSize==1 ) *pSize = 0;
29129 
29130 
29131   return SQLITE_OK;
29132 }
29133 
29134 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29135 /*
29136 ** Handler for proxy-locking file-control verbs.  Defined below in the
29137 ** proxying locking division.
29138 */
29139 static int proxyFileControl(sqlite3_file*,int,void*);
29140 #endif
29141 
29142 /*
29143 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
29144 ** file-control operation.  Enlarge the database to nBytes in size
29145 ** (rounded up to the next chunk-size).  If the database is already
29146 ** nBytes or larger, this routine is a no-op.
29147 */
29148 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
29149   if( pFile->szChunk>0 ){
29150     i64 nSize;                    /* Required file size */
29151     struct stat buf;              /* Used to hold return values of fstat() */
29152 
29153     if( osFstat(pFile->h, &buf) ){
29154       return SQLITE_IOERR_FSTAT;
29155     }
29156 
29157     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
29158     if( nSize>(i64)buf.st_size ){
29159 
29160 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
29161       /* The code below is handling the return value of osFallocate()
29162       ** correctly. posix_fallocate() is defined to "returns zero on success,
29163       ** or an error number on  failure". See the manpage for details. */
29164       int err;
29165       do{
29166         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
29167       }while( err==EINTR );
29168       if( err ) return SQLITE_IOERR_WRITE;
29169 #else
29170       /* If the OS does not have posix_fallocate(), fake it. Write a
29171       ** single byte to the last byte in each block that falls entirely
29172       ** within the extended region. Then, if required, a single byte
29173       ** at offset (nSize-1), to set the size of the file correctly.
29174       ** This is a similar technique to that used by glibc on systems
29175       ** that do not have a real fallocate() call.
29176       */
29177       int nBlk = buf.st_blksize;  /* File-system block size */
29178       int nWrite = 0;             /* Number of bytes written by seekAndWrite */
29179       i64 iWrite;                 /* Next offset to write to */
29180 
29181       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
29182       assert( iWrite>=buf.st_size );
29183       assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
29184       assert( ((iWrite+1)%nBlk)==0 );
29185       for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
29186         nWrite = seekAndWrite(pFile, iWrite, "", 1);
29187         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
29188       }
29189       if( nWrite==0 || (nSize%nBlk) ){
29190         nWrite = seekAndWrite(pFile, nSize-1, "", 1);
29191         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
29192       }
29193 #endif
29194     }
29195   }
29196 
29197 #if SQLITE_MAX_MMAP_SIZE>0
29198   if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
29199     int rc;
29200     if( pFile->szChunk<=0 ){
29201       if( robust_ftruncate(pFile->h, nByte) ){
29202         storeLastErrno(pFile, errno);
29203         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
29204       }
29205     }
29206 
29207     rc = unixMapfile(pFile, nByte);
29208     return rc;
29209   }
29210 #endif
29211 
29212   return SQLITE_OK;
29213 }
29214 
29215 /*
29216 ** If *pArg is initially negative then this is a query.  Set *pArg to
29217 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
29218 **
29219 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
29220 */
29221 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
29222   if( *pArg<0 ){
29223     *pArg = (pFile->ctrlFlags & mask)!=0;
29224   }else if( (*pArg)==0 ){
29225     pFile->ctrlFlags &= ~mask;
29226   }else{
29227     pFile->ctrlFlags |= mask;
29228   }
29229 }
29230 
29231 /* Forward declaration */
29232 static int unixGetTempname(int nBuf, char *zBuf);
29233 
29234 /*
29235 ** Information and control of an open file handle.
29236 */
29237 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
29238   unixFile *pFile = (unixFile*)id;
29239   switch( op ){
29240     case SQLITE_FCNTL_WAL_BLOCK: {
29241       /* pFile->ctrlFlags |= UNIXFILE_BLOCK; // Deferred feature */
29242       return SQLITE_OK;
29243     }
29244     case SQLITE_FCNTL_LOCKSTATE: {
29245       *(int*)pArg = pFile->eFileLock;
29246       return SQLITE_OK;
29247     }
29248     case SQLITE_FCNTL_LAST_ERRNO: {
29249       *(int*)pArg = pFile->lastErrno;
29250       return SQLITE_OK;
29251     }
29252     case SQLITE_FCNTL_CHUNK_SIZE: {
29253       pFile->szChunk = *(int *)pArg;
29254       return SQLITE_OK;
29255     }
29256     case SQLITE_FCNTL_SIZE_HINT: {
29257       int rc;
29258       SimulateIOErrorBenign(1);
29259       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
29260       SimulateIOErrorBenign(0);
29261       return rc;
29262     }
29263     case SQLITE_FCNTL_PERSIST_WAL: {
29264       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
29265       return SQLITE_OK;
29266     }
29267     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
29268       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
29269       return SQLITE_OK;
29270     }
29271     case SQLITE_FCNTL_VFSNAME: {
29272       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
29273       return SQLITE_OK;
29274     }
29275     case SQLITE_FCNTL_TEMPFILENAME: {
29276       char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
29277       if( zTFile ){
29278         unixGetTempname(pFile->pVfs->mxPathname, zTFile);
29279         *(char**)pArg = zTFile;
29280       }
29281       return SQLITE_OK;
29282     }
29283     case SQLITE_FCNTL_HAS_MOVED: {
29284       *(int*)pArg = fileHasMoved(pFile);
29285       return SQLITE_OK;
29286     }
29287 #if SQLITE_MAX_MMAP_SIZE>0
29288     case SQLITE_FCNTL_MMAP_SIZE: {
29289       i64 newLimit = *(i64*)pArg;
29290       int rc = SQLITE_OK;
29291       if( newLimit>sqlite3GlobalConfig.mxMmap ){
29292         newLimit = sqlite3GlobalConfig.mxMmap;
29293       }
29294       *(i64*)pArg = pFile->mmapSizeMax;
29295       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
29296         pFile->mmapSizeMax = newLimit;
29297         if( pFile->mmapSize>0 ){
29298           unixUnmapfile(pFile);
29299           rc = unixMapfile(pFile, -1);
29300         }
29301       }
29302       return rc;
29303     }
29304 #endif
29305 #ifdef SQLITE_DEBUG
29306     /* The pager calls this method to signal that it has done
29307     ** a rollback and that the database is therefore unchanged and
29308     ** it hence it is OK for the transaction change counter to be
29309     ** unchanged.
29310     */
29311     case SQLITE_FCNTL_DB_UNCHANGED: {
29312       ((unixFile*)id)->dbUpdate = 0;
29313       return SQLITE_OK;
29314     }
29315 #endif
29316 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29317     case SQLITE_FCNTL_SET_LOCKPROXYFILE:
29318     case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
29319       return proxyFileControl(id,op,pArg);
29320     }
29321 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
29322   }
29323   return SQLITE_NOTFOUND;
29324 }
29325 
29326 /*
29327 ** Return the sector size in bytes of the underlying block device for
29328 ** the specified file. This is almost always 512 bytes, but may be
29329 ** larger for some devices.
29330 **
29331 ** SQLite code assumes this function cannot fail. It also assumes that
29332 ** if two files are created in the same file-system directory (i.e.
29333 ** a database and its journal file) that the sector size will be the
29334 ** same for both.
29335 */
29336 #ifndef __QNXNTO__
29337 static int unixSectorSize(sqlite3_file *NotUsed){
29338   UNUSED_PARAMETER(NotUsed);
29339   return SQLITE_DEFAULT_SECTOR_SIZE;
29340 }
29341 #endif
29342 
29343 /*
29344 ** The following version of unixSectorSize() is optimized for QNX.
29345 */
29346 #ifdef __QNXNTO__
29347 #include <sys/dcmd_blk.h>
29348 #include <sys/statvfs.h>
29349 static int unixSectorSize(sqlite3_file *id){
29350   unixFile *pFile = (unixFile*)id;
29351   if( pFile->sectorSize == 0 ){
29352     struct statvfs fsInfo;
29353 
29354     /* Set defaults for non-supported filesystems */
29355     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
29356     pFile->deviceCharacteristics = 0;
29357     if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
29358       return pFile->sectorSize;
29359     }
29360 
29361     if( !strcmp(fsInfo.f_basetype, "tmp") ) {
29362       pFile->sectorSize = fsInfo.f_bsize;
29363       pFile->deviceCharacteristics =
29364         SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
29365         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
29366                                       ** the write succeeds */
29367         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
29368                                       ** so it is ordered */
29369         0;
29370     }else if( strstr(fsInfo.f_basetype, "etfs") ){
29371       pFile->sectorSize = fsInfo.f_bsize;
29372       pFile->deviceCharacteristics =
29373         /* etfs cluster size writes are atomic */
29374         (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
29375         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
29376                                       ** the write succeeds */
29377         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
29378                                       ** so it is ordered */
29379         0;
29380     }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
29381       pFile->sectorSize = fsInfo.f_bsize;
29382       pFile->deviceCharacteristics =
29383         SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
29384         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
29385                                       ** the write succeeds */
29386         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
29387                                       ** so it is ordered */
29388         0;
29389     }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
29390       pFile->sectorSize = fsInfo.f_bsize;
29391       pFile->deviceCharacteristics =
29392         /* full bitset of atomics from max sector size and smaller */
29393         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
29394         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
29395                                       ** so it is ordered */
29396         0;
29397     }else if( strstr(fsInfo.f_basetype, "dos") ){
29398       pFile->sectorSize = fsInfo.f_bsize;
29399       pFile->deviceCharacteristics =
29400         /* full bitset of atomics from max sector size and smaller */
29401         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
29402         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
29403                                       ** so it is ordered */
29404         0;
29405     }else{
29406       pFile->deviceCharacteristics =
29407         SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
29408         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
29409                                       ** the write succeeds */
29410         0;
29411     }
29412   }
29413   /* Last chance verification.  If the sector size isn't a multiple of 512
29414   ** then it isn't valid.*/
29415   if( pFile->sectorSize % 512 != 0 ){
29416     pFile->deviceCharacteristics = 0;
29417     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
29418   }
29419   return pFile->sectorSize;
29420 }
29421 #endif /* __QNXNTO__ */
29422 
29423 /*
29424 ** Return the device characteristics for the file.
29425 **
29426 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
29427 ** However, that choice is controversial since technically the underlying
29428 ** file system does not always provide powersafe overwrites.  (In other
29429 ** words, after a power-loss event, parts of the file that were never
29430 ** written might end up being altered.)  However, non-PSOW behavior is very,
29431 ** very rare.  And asserting PSOW makes a large reduction in the amount
29432 ** of required I/O for journaling, since a lot of padding is eliminated.
29433 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
29434 ** available to turn it off and URI query parameter available to turn it off.
29435 */
29436 static int unixDeviceCharacteristics(sqlite3_file *id){
29437   unixFile *p = (unixFile*)id;
29438   int rc = 0;
29439 #ifdef __QNXNTO__
29440   if( p->sectorSize==0 ) unixSectorSize(id);
29441   rc = p->deviceCharacteristics;
29442 #endif
29443   if( p->ctrlFlags & UNIXFILE_PSOW ){
29444     rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
29445   }
29446   return rc;
29447 }
29448 
29449 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29450 
29451 /*
29452 ** Return the system page size.
29453 **
29454 ** This function should not be called directly by other code in this file.
29455 ** Instead, it should be called via macro osGetpagesize().
29456 */
29457 static int unixGetpagesize(void){
29458 #if OS_VXWORKS
29459   return 1024;
29460 #elif defined(_BSD_SOURCE)
29461   return getpagesize();
29462 #else
29463   return (int)sysconf(_SC_PAGESIZE);
29464 #endif
29465 }
29466 
29467 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
29468 
29469 #ifndef SQLITE_OMIT_WAL
29470 
29471 /*
29472 ** Object used to represent an shared memory buffer.
29473 **
29474 ** When multiple threads all reference the same wal-index, each thread
29475 ** has its own unixShm object, but they all point to a single instance
29476 ** of this unixShmNode object.  In other words, each wal-index is opened
29477 ** only once per process.
29478 **
29479 ** Each unixShmNode object is connected to a single unixInodeInfo object.
29480 ** We could coalesce this object into unixInodeInfo, but that would mean
29481 ** every open file that does not use shared memory (in other words, most
29482 ** open files) would have to carry around this extra information.  So
29483 ** the unixInodeInfo object contains a pointer to this unixShmNode object
29484 ** and the unixShmNode object is created only when needed.
29485 **
29486 ** unixMutexHeld() must be true when creating or destroying
29487 ** this object or while reading or writing the following fields:
29488 **
29489 **      nRef
29490 **
29491 ** The following fields are read-only after the object is created:
29492 **
29493 **      fid
29494 **      zFilename
29495 **
29496 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
29497 ** unixMutexHeld() is true when reading or writing any other field
29498 ** in this structure.
29499 */
29500 struct unixShmNode {
29501   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
29502   sqlite3_mutex *mutex;      /* Mutex to access this object */
29503   char *zFilename;           /* Name of the mmapped file */
29504   int h;                     /* Open file descriptor */
29505   int szRegion;              /* Size of shared-memory regions */
29506   u16 nRegion;               /* Size of array apRegion */
29507   u8 isReadonly;             /* True if read-only */
29508   char **apRegion;           /* Array of mapped shared-memory regions */
29509   int nRef;                  /* Number of unixShm objects pointing to this */
29510   unixShm *pFirst;           /* All unixShm objects pointing to this */
29511 #ifdef SQLITE_DEBUG
29512   u8 exclMask;               /* Mask of exclusive locks held */
29513   u8 sharedMask;             /* Mask of shared locks held */
29514   u8 nextShmId;              /* Next available unixShm.id value */
29515 #endif
29516 };
29517 
29518 /*
29519 ** Structure used internally by this VFS to record the state of an
29520 ** open shared memory connection.
29521 **
29522 ** The following fields are initialized when this object is created and
29523 ** are read-only thereafter:
29524 **
29525 **    unixShm.pFile
29526 **    unixShm.id
29527 **
29528 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
29529 ** while accessing any read/write fields.
29530 */
29531 struct unixShm {
29532   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
29533   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
29534   u8 hasMutex;               /* True if holding the unixShmNode mutex */
29535   u8 id;                     /* Id of this connection within its unixShmNode */
29536   u16 sharedMask;            /* Mask of shared locks held */
29537   u16 exclMask;              /* Mask of exclusive locks held */
29538 };
29539 
29540 /*
29541 ** Constants used for locking
29542 */
29543 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
29544 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
29545 
29546 /*
29547 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
29548 **
29549 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
29550 ** otherwise.
29551 */
29552 static int unixShmSystemLock(
29553   unixFile *pFile,       /* Open connection to the WAL file */
29554   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
29555   int ofst,              /* First byte of the locking range */
29556   int n                  /* Number of bytes to lock */
29557 ){
29558   unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
29559   struct flock f;        /* The posix advisory locking structure */
29560   int rc = SQLITE_OK;    /* Result code form fcntl() */
29561 
29562   /* Access to the unixShmNode object is serialized by the caller */
29563   pShmNode = pFile->pInode->pShmNode;
29564   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
29565 
29566   /* Shared locks never span more than one byte */
29567   assert( n==1 || lockType!=F_RDLCK );
29568 
29569   /* Locks are within range */
29570   assert( n>=1 && n<SQLITE_SHM_NLOCK );
29571 
29572   if( pShmNode->h>=0 ){
29573     int lkType;
29574     /* Initialize the locking parameters */
29575     memset(&f, 0, sizeof(f));
29576     f.l_type = lockType;
29577     f.l_whence = SEEK_SET;
29578     f.l_start = ofst;
29579     f.l_len = n;
29580 
29581     lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
29582     rc = osFcntl(pShmNode->h, lkType, &f);
29583     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
29584     pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
29585   }
29586 
29587   /* Update the global lock state and do debug tracing */
29588 #ifdef SQLITE_DEBUG
29589   { u16 mask;
29590   OSTRACE(("SHM-LOCK "));
29591   mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
29592   if( rc==SQLITE_OK ){
29593     if( lockType==F_UNLCK ){
29594       OSTRACE(("unlock %d ok", ofst));
29595       pShmNode->exclMask &= ~mask;
29596       pShmNode->sharedMask &= ~mask;
29597     }else if( lockType==F_RDLCK ){
29598       OSTRACE(("read-lock %d ok", ofst));
29599       pShmNode->exclMask &= ~mask;
29600       pShmNode->sharedMask |= mask;
29601     }else{
29602       assert( lockType==F_WRLCK );
29603       OSTRACE(("write-lock %d ok", ofst));
29604       pShmNode->exclMask |= mask;
29605       pShmNode->sharedMask &= ~mask;
29606     }
29607   }else{
29608     if( lockType==F_UNLCK ){
29609       OSTRACE(("unlock %d failed", ofst));
29610     }else if( lockType==F_RDLCK ){
29611       OSTRACE(("read-lock failed"));
29612     }else{
29613       assert( lockType==F_WRLCK );
29614       OSTRACE(("write-lock %d failed", ofst));
29615     }
29616   }
29617   OSTRACE((" - afterwards %03x,%03x\n",
29618            pShmNode->sharedMask, pShmNode->exclMask));
29619   }
29620 #endif
29621 
29622   return rc;
29623 }
29624 
29625 /*
29626 ** Return the minimum number of 32KB shm regions that should be mapped at
29627 ** a time, assuming that each mapping must be an integer multiple of the
29628 ** current system page-size.
29629 **
29630 ** Usually, this is 1. The exception seems to be systems that are configured
29631 ** to use 64KB pages - in this case each mapping must cover at least two
29632 ** shm regions.
29633 */
29634 static int unixShmRegionPerMap(void){
29635   int shmsz = 32*1024;            /* SHM region size */
29636   int pgsz = osGetpagesize();   /* System page size */
29637   assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
29638   if( pgsz<shmsz ) return 1;
29639   return pgsz/shmsz;
29640 }
29641 
29642 /*
29643 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
29644 **
29645 ** This is not a VFS shared-memory method; it is a utility function called
29646 ** by VFS shared-memory methods.
29647 */
29648 static void unixShmPurge(unixFile *pFd){
29649   unixShmNode *p = pFd->pInode->pShmNode;
29650   assert( unixMutexHeld() );
29651   if( p && p->nRef==0 ){
29652     int nShmPerMap = unixShmRegionPerMap();
29653     int i;
29654     assert( p->pInode==pFd->pInode );
29655     sqlite3_mutex_free(p->mutex);
29656     for(i=0; i<p->nRegion; i+=nShmPerMap){
29657       if( p->h>=0 ){
29658         osMunmap(p->apRegion[i], p->szRegion);
29659       }else{
29660         sqlite3_free(p->apRegion[i]);
29661       }
29662     }
29663     sqlite3_free(p->apRegion);
29664     if( p->h>=0 ){
29665       robust_close(pFd, p->h, __LINE__);
29666       p->h = -1;
29667     }
29668     p->pInode->pShmNode = 0;
29669     sqlite3_free(p);
29670   }
29671 }
29672 
29673 /*
29674 ** Open a shared-memory area associated with open database file pDbFd.
29675 ** This particular implementation uses mmapped files.
29676 **
29677 ** The file used to implement shared-memory is in the same directory
29678 ** as the open database file and has the same name as the open database
29679 ** file with the "-shm" suffix added.  For example, if the database file
29680 ** is "/home/user1/config.db" then the file that is created and mmapped
29681 ** for shared memory will be called "/home/user1/config.db-shm".
29682 **
29683 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
29684 ** some other tmpfs mount. But if a file in a different directory
29685 ** from the database file is used, then differing access permissions
29686 ** or a chroot() might cause two different processes on the same
29687 ** database to end up using different files for shared memory -
29688 ** meaning that their memory would not really be shared - resulting
29689 ** in database corruption.  Nevertheless, this tmpfs file usage
29690 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
29691 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
29692 ** option results in an incompatible build of SQLite;  builds of SQLite
29693 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
29694 ** same database file at the same time, database corruption will likely
29695 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
29696 ** "unsupported" and may go away in a future SQLite release.
29697 **
29698 ** When opening a new shared-memory file, if no other instances of that
29699 ** file are currently open, in this process or in other processes, then
29700 ** the file must be truncated to zero length or have its header cleared.
29701 **
29702 ** If the original database file (pDbFd) is using the "unix-excl" VFS
29703 ** that means that an exclusive lock is held on the database file and
29704 ** that no other processes are able to read or write the database.  In
29705 ** that case, we do not really need shared memory.  No shared memory
29706 ** file is created.  The shared memory will be simulated with heap memory.
29707 */
29708 static int unixOpenSharedMemory(unixFile *pDbFd){
29709   struct unixShm *p = 0;          /* The connection to be opened */
29710   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
29711   int rc;                         /* Result code */
29712   unixInodeInfo *pInode;          /* The inode of fd */
29713   char *zShmFilename;             /* Name of the file used for SHM */
29714   int nShmFilename;               /* Size of the SHM filename in bytes */
29715 
29716   /* Allocate space for the new unixShm object. */
29717   p = sqlite3_malloc64( sizeof(*p) );
29718   if( p==0 ) return SQLITE_NOMEM;
29719   memset(p, 0, sizeof(*p));
29720   assert( pDbFd->pShm==0 );
29721 
29722   /* Check to see if a unixShmNode object already exists. Reuse an existing
29723   ** one if present. Create a new one if necessary.
29724   */
29725   unixEnterMutex();
29726   pInode = pDbFd->pInode;
29727   pShmNode = pInode->pShmNode;
29728   if( pShmNode==0 ){
29729     struct stat sStat;                 /* fstat() info for database file */
29730 #ifndef SQLITE_SHM_DIRECTORY
29731     const char *zBasePath = pDbFd->zPath;
29732 #endif
29733 
29734     /* Call fstat() to figure out the permissions on the database file. If
29735     ** a new *-shm file is created, an attempt will be made to create it
29736     ** with the same permissions.
29737     */
29738     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
29739       rc = SQLITE_IOERR_FSTAT;
29740       goto shm_open_err;
29741     }
29742 
29743 #ifdef SQLITE_SHM_DIRECTORY
29744     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
29745 #else
29746     nShmFilename = 6 + (int)strlen(zBasePath);
29747 #endif
29748     pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
29749     if( pShmNode==0 ){
29750       rc = SQLITE_NOMEM;
29751       goto shm_open_err;
29752     }
29753     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
29754     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
29755 #ifdef SQLITE_SHM_DIRECTORY
29756     sqlite3_snprintf(nShmFilename, zShmFilename,
29757                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
29758                      (u32)sStat.st_ino, (u32)sStat.st_dev);
29759 #else
29760     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
29761     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
29762 #endif
29763     pShmNode->h = -1;
29764     pDbFd->pInode->pShmNode = pShmNode;
29765     pShmNode->pInode = pDbFd->pInode;
29766     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
29767     if( pShmNode->mutex==0 ){
29768       rc = SQLITE_NOMEM;
29769       goto shm_open_err;
29770     }
29771 
29772     if( pInode->bProcessLock==0 ){
29773       int openFlags = O_RDWR | O_CREAT;
29774       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
29775         openFlags = O_RDONLY;
29776         pShmNode->isReadonly = 1;
29777       }
29778       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
29779       if( pShmNode->h<0 ){
29780         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
29781         goto shm_open_err;
29782       }
29783 
29784       /* If this process is running as root, make sure that the SHM file
29785       ** is owned by the same user that owns the original database.  Otherwise,
29786       ** the original owner will not be able to connect.
29787       */
29788       osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
29789 
29790       /* Check to see if another process is holding the dead-man switch.
29791       ** If not, truncate the file to zero length.
29792       */
29793       rc = SQLITE_OK;
29794       if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
29795         if( robust_ftruncate(pShmNode->h, 0) ){
29796           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
29797         }
29798       }
29799       if( rc==SQLITE_OK ){
29800         rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
29801       }
29802       if( rc ) goto shm_open_err;
29803     }
29804   }
29805 
29806   /* Make the new connection a child of the unixShmNode */
29807   p->pShmNode = pShmNode;
29808 #ifdef SQLITE_DEBUG
29809   p->id = pShmNode->nextShmId++;
29810 #endif
29811   pShmNode->nRef++;
29812   pDbFd->pShm = p;
29813   unixLeaveMutex();
29814 
29815   /* The reference count on pShmNode has already been incremented under
29816   ** the cover of the unixEnterMutex() mutex and the pointer from the
29817   ** new (struct unixShm) object to the pShmNode has been set. All that is
29818   ** left to do is to link the new object into the linked list starting
29819   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
29820   ** mutex.
29821   */
29822   sqlite3_mutex_enter(pShmNode->mutex);
29823   p->pNext = pShmNode->pFirst;
29824   pShmNode->pFirst = p;
29825   sqlite3_mutex_leave(pShmNode->mutex);
29826   return SQLITE_OK;
29827 
29828   /* Jump here on any error */
29829 shm_open_err:
29830   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
29831   sqlite3_free(p);
29832   unixLeaveMutex();
29833   return rc;
29834 }
29835 
29836 /*
29837 ** This function is called to obtain a pointer to region iRegion of the
29838 ** shared-memory associated with the database file fd. Shared-memory regions
29839 ** are numbered starting from zero. Each shared-memory region is szRegion
29840 ** bytes in size.
29841 **
29842 ** If an error occurs, an error code is returned and *pp is set to NULL.
29843 **
29844 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
29845 ** region has not been allocated (by any client, including one running in a
29846 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
29847 ** bExtend is non-zero and the requested shared-memory region has not yet
29848 ** been allocated, it is allocated by this function.
29849 **
29850 ** If the shared-memory region has already been allocated or is allocated by
29851 ** this call as described above, then it is mapped into this processes
29852 ** address space (if it is not already), *pp is set to point to the mapped
29853 ** memory and SQLITE_OK returned.
29854 */
29855 static int unixShmMap(
29856   sqlite3_file *fd,               /* Handle open on database file */
29857   int iRegion,                    /* Region to retrieve */
29858   int szRegion,                   /* Size of regions */
29859   int bExtend,                    /* True to extend file if necessary */
29860   void volatile **pp              /* OUT: Mapped memory */
29861 ){
29862   unixFile *pDbFd = (unixFile*)fd;
29863   unixShm *p;
29864   unixShmNode *pShmNode;
29865   int rc = SQLITE_OK;
29866   int nShmPerMap = unixShmRegionPerMap();
29867   int nReqRegion;
29868 
29869   /* If the shared-memory file has not yet been opened, open it now. */
29870   if( pDbFd->pShm==0 ){
29871     rc = unixOpenSharedMemory(pDbFd);
29872     if( rc!=SQLITE_OK ) return rc;
29873   }
29874 
29875   p = pDbFd->pShm;
29876   pShmNode = p->pShmNode;
29877   sqlite3_mutex_enter(pShmNode->mutex);
29878   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
29879   assert( pShmNode->pInode==pDbFd->pInode );
29880   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29881   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29882 
29883   /* Minimum number of regions required to be mapped. */
29884   nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
29885 
29886   if( pShmNode->nRegion<nReqRegion ){
29887     char **apNew;                      /* New apRegion[] array */
29888     int nByte = nReqRegion*szRegion;   /* Minimum required file size */
29889     struct stat sStat;                 /* Used by fstat() */
29890 
29891     pShmNode->szRegion = szRegion;
29892 
29893     if( pShmNode->h>=0 ){
29894       /* The requested region is not mapped into this processes address space.
29895       ** Check to see if it has been allocated (i.e. if the wal-index file is
29896       ** large enough to contain the requested region).
29897       */
29898       if( osFstat(pShmNode->h, &sStat) ){
29899         rc = SQLITE_IOERR_SHMSIZE;
29900         goto shmpage_out;
29901       }
29902 
29903       if( sStat.st_size<nByte ){
29904         /* The requested memory region does not exist. If bExtend is set to
29905         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
29906         */
29907         if( !bExtend ){
29908           goto shmpage_out;
29909         }
29910 
29911         /* Alternatively, if bExtend is true, extend the file. Do this by
29912         ** writing a single byte to the end of each (OS) page being
29913         ** allocated or extended. Technically, we need only write to the
29914         ** last page in order to extend the file. But writing to all new
29915         ** pages forces the OS to allocate them immediately, which reduces
29916         ** the chances of SIGBUS while accessing the mapped region later on.
29917         */
29918         else{
29919           static const int pgsz = 4096;
29920           int iPg;
29921 
29922           /* Write to the last byte of each newly allocated or extended page */
29923           assert( (nByte % pgsz)==0 );
29924           for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
29925             if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
29926               const char *zFile = pShmNode->zFilename;
29927               rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
29928               goto shmpage_out;
29929             }
29930           }
29931         }
29932       }
29933     }
29934 
29935     /* Map the requested memory region into this processes address space. */
29936     apNew = (char **)sqlite3_realloc(
29937         pShmNode->apRegion, nReqRegion*sizeof(char *)
29938     );
29939     if( !apNew ){
29940       rc = SQLITE_IOERR_NOMEM;
29941       goto shmpage_out;
29942     }
29943     pShmNode->apRegion = apNew;
29944     while( pShmNode->nRegion<nReqRegion ){
29945       int nMap = szRegion*nShmPerMap;
29946       int i;
29947       void *pMem;
29948       if( pShmNode->h>=0 ){
29949         pMem = osMmap(0, nMap,
29950             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
29951             MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
29952         );
29953         if( pMem==MAP_FAILED ){
29954           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
29955           goto shmpage_out;
29956         }
29957       }else{
29958         pMem = sqlite3_malloc64(szRegion);
29959         if( pMem==0 ){
29960           rc = SQLITE_NOMEM;
29961           goto shmpage_out;
29962         }
29963         memset(pMem, 0, szRegion);
29964       }
29965 
29966       for(i=0; i<nShmPerMap; i++){
29967         pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
29968       }
29969       pShmNode->nRegion += nShmPerMap;
29970     }
29971   }
29972 
29973 shmpage_out:
29974   if( pShmNode->nRegion>iRegion ){
29975     *pp = pShmNode->apRegion[iRegion];
29976   }else{
29977     *pp = 0;
29978   }
29979   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
29980   sqlite3_mutex_leave(pShmNode->mutex);
29981   return rc;
29982 }
29983 
29984 /*
29985 ** Change the lock state for a shared-memory segment.
29986 **
29987 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
29988 ** different here than in posix.  In xShmLock(), one can go from unlocked
29989 ** to shared and back or from unlocked to exclusive and back.  But one may
29990 ** not go from shared to exclusive or from exclusive to shared.
29991 */
29992 static int unixShmLock(
29993   sqlite3_file *fd,          /* Database file holding the shared memory */
29994   int ofst,                  /* First lock to acquire or release */
29995   int n,                     /* Number of locks to acquire or release */
29996   int flags                  /* What to do with the lock */
29997 ){
29998   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
29999   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
30000   unixShm *pX;                          /* For looping over all siblings */
30001   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
30002   int rc = SQLITE_OK;                   /* Result code */
30003   u16 mask;                             /* Mask of locks to take or release */
30004 
30005   assert( pShmNode==pDbFd->pInode->pShmNode );
30006   assert( pShmNode->pInode==pDbFd->pInode );
30007   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
30008   assert( n>=1 );
30009   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
30010        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
30011        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
30012        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
30013   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
30014   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
30015   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
30016 
30017   mask = (1<<(ofst+n)) - (1<<ofst);
30018   assert( n>1 || mask==(1<<ofst) );
30019   sqlite3_mutex_enter(pShmNode->mutex);
30020   if( flags & SQLITE_SHM_UNLOCK ){
30021     u16 allMask = 0; /* Mask of locks held by siblings */
30022 
30023     /* See if any siblings hold this same lock */
30024     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30025       if( pX==p ) continue;
30026       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
30027       allMask |= pX->sharedMask;
30028     }
30029 
30030     /* Unlock the system-level locks */
30031     if( (mask & allMask)==0 ){
30032       rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
30033     }else{
30034       rc = SQLITE_OK;
30035     }
30036 
30037     /* Undo the local locks */
30038     if( rc==SQLITE_OK ){
30039       p->exclMask &= ~mask;
30040       p->sharedMask &= ~mask;
30041     }
30042   }else if( flags & SQLITE_SHM_SHARED ){
30043     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
30044 
30045     /* Find out which shared locks are already held by sibling connections.
30046     ** If any sibling already holds an exclusive lock, go ahead and return
30047     ** SQLITE_BUSY.
30048     */
30049     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30050       if( (pX->exclMask & mask)!=0 ){
30051         rc = SQLITE_BUSY;
30052         break;
30053       }
30054       allShared |= pX->sharedMask;
30055     }
30056 
30057     /* Get shared locks at the system level, if necessary */
30058     if( rc==SQLITE_OK ){
30059       if( (allShared & mask)==0 ){
30060         rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
30061       }else{
30062         rc = SQLITE_OK;
30063       }
30064     }
30065 
30066     /* Get the local shared locks */
30067     if( rc==SQLITE_OK ){
30068       p->sharedMask |= mask;
30069     }
30070   }else{
30071     /* Make sure no sibling connections hold locks that will block this
30072     ** lock.  If any do, return SQLITE_BUSY right away.
30073     */
30074     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30075       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
30076         rc = SQLITE_BUSY;
30077         break;
30078       }
30079     }
30080 
30081     /* Get the exclusive locks at the system level.  Then if successful
30082     ** also mark the local connection as being locked.
30083     */
30084     if( rc==SQLITE_OK ){
30085       rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
30086       if( rc==SQLITE_OK ){
30087         assert( (p->sharedMask & mask)==0 );
30088         p->exclMask |= mask;
30089       }
30090     }
30091   }
30092   sqlite3_mutex_leave(pShmNode->mutex);
30093   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
30094            p->id, osGetpid(0), p->sharedMask, p->exclMask));
30095   return rc;
30096 }
30097 
30098 /*
30099 ** Implement a memory barrier or memory fence on shared memory.
30100 **
30101 ** All loads and stores begun before the barrier must complete before
30102 ** any load or store begun after the barrier.
30103 */
30104 static void unixShmBarrier(
30105   sqlite3_file *fd                /* Database file holding the shared memory */
30106 ){
30107   UNUSED_PARAMETER(fd);
30108   unixEnterMutex();
30109   unixLeaveMutex();
30110 }
30111 
30112 /*
30113 ** Close a connection to shared-memory.  Delete the underlying
30114 ** storage if deleteFlag is true.
30115 **
30116 ** If there is no shared memory associated with the connection then this
30117 ** routine is a harmless no-op.
30118 */
30119 static int unixShmUnmap(
30120   sqlite3_file *fd,               /* The underlying database file */
30121   int deleteFlag                  /* Delete shared-memory if true */
30122 ){
30123   unixShm *p;                     /* The connection to be closed */
30124   unixShmNode *pShmNode;          /* The underlying shared-memory file */
30125   unixShm **pp;                   /* For looping over sibling connections */
30126   unixFile *pDbFd;                /* The underlying database file */
30127 
30128   pDbFd = (unixFile*)fd;
30129   p = pDbFd->pShm;
30130   if( p==0 ) return SQLITE_OK;
30131   pShmNode = p->pShmNode;
30132 
30133   assert( pShmNode==pDbFd->pInode->pShmNode );
30134   assert( pShmNode->pInode==pDbFd->pInode );
30135 
30136   /* Remove connection p from the set of connections associated
30137   ** with pShmNode */
30138   sqlite3_mutex_enter(pShmNode->mutex);
30139   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
30140   *pp = p->pNext;
30141 
30142   /* Free the connection p */
30143   sqlite3_free(p);
30144   pDbFd->pShm = 0;
30145   sqlite3_mutex_leave(pShmNode->mutex);
30146 
30147   /* If pShmNode->nRef has reached 0, then close the underlying
30148   ** shared-memory file, too */
30149   unixEnterMutex();
30150   assert( pShmNode->nRef>0 );
30151   pShmNode->nRef--;
30152   if( pShmNode->nRef==0 ){
30153     if( deleteFlag && pShmNode->h>=0 ){
30154       osUnlink(pShmNode->zFilename);
30155     }
30156     unixShmPurge(pDbFd);
30157   }
30158   unixLeaveMutex();
30159 
30160   return SQLITE_OK;
30161 }
30162 
30163 
30164 #else
30165 # define unixShmMap     0
30166 # define unixShmLock    0
30167 # define unixShmBarrier 0
30168 # define unixShmUnmap   0
30169 #endif /* #ifndef SQLITE_OMIT_WAL */
30170 
30171 #if SQLITE_MAX_MMAP_SIZE>0
30172 /*
30173 ** If it is currently memory mapped, unmap file pFd.
30174 */
30175 static void unixUnmapfile(unixFile *pFd){
30176   assert( pFd->nFetchOut==0 );
30177   if( pFd->pMapRegion ){
30178     osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
30179     pFd->pMapRegion = 0;
30180     pFd->mmapSize = 0;
30181     pFd->mmapSizeActual = 0;
30182   }
30183 }
30184 
30185 /*
30186 ** Attempt to set the size of the memory mapping maintained by file
30187 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
30188 **
30189 ** If successful, this function sets the following variables:
30190 **
30191 **       unixFile.pMapRegion
30192 **       unixFile.mmapSize
30193 **       unixFile.mmapSizeActual
30194 **
30195 ** If unsuccessful, an error message is logged via sqlite3_log() and
30196 ** the three variables above are zeroed. In this case SQLite should
30197 ** continue accessing the database using the xRead() and xWrite()
30198 ** methods.
30199 */
30200 static void unixRemapfile(
30201   unixFile *pFd,                  /* File descriptor object */
30202   i64 nNew                        /* Required mapping size */
30203 ){
30204   const char *zErr = "mmap";
30205   int h = pFd->h;                      /* File descriptor open on db file */
30206   u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
30207   i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
30208   u8 *pNew = 0;                        /* Location of new mapping */
30209   int flags = PROT_READ;               /* Flags to pass to mmap() */
30210 
30211   assert( pFd->nFetchOut==0 );
30212   assert( nNew>pFd->mmapSize );
30213   assert( nNew<=pFd->mmapSizeMax );
30214   assert( nNew>0 );
30215   assert( pFd->mmapSizeActual>=pFd->mmapSize );
30216   assert( MAP_FAILED!=0 );
30217 
30218   if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
30219 
30220   if( pOrig ){
30221 #if HAVE_MREMAP
30222     i64 nReuse = pFd->mmapSize;
30223 #else
30224     const int szSyspage = osGetpagesize();
30225     i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
30226 #endif
30227     u8 *pReq = &pOrig[nReuse];
30228 
30229     /* Unmap any pages of the existing mapping that cannot be reused. */
30230     if( nReuse!=nOrig ){
30231       osMunmap(pReq, nOrig-nReuse);
30232     }
30233 
30234 #if HAVE_MREMAP
30235     pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
30236     zErr = "mremap";
30237 #else
30238     pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
30239     if( pNew!=MAP_FAILED ){
30240       if( pNew!=pReq ){
30241         osMunmap(pNew, nNew - nReuse);
30242         pNew = 0;
30243       }else{
30244         pNew = pOrig;
30245       }
30246     }
30247 #endif
30248 
30249     /* The attempt to extend the existing mapping failed. Free it. */
30250     if( pNew==MAP_FAILED || pNew==0 ){
30251       osMunmap(pOrig, nReuse);
30252     }
30253   }
30254 
30255   /* If pNew is still NULL, try to create an entirely new mapping. */
30256   if( pNew==0 ){
30257     pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
30258   }
30259 
30260   if( pNew==MAP_FAILED ){
30261     pNew = 0;
30262     nNew = 0;
30263     unixLogError(SQLITE_OK, zErr, pFd->zPath);
30264 
30265     /* If the mmap() above failed, assume that all subsequent mmap() calls
30266     ** will probably fail too. Fall back to using xRead/xWrite exclusively
30267     ** in this case.  */
30268     pFd->mmapSizeMax = 0;
30269   }
30270   pFd->pMapRegion = (void *)pNew;
30271   pFd->mmapSize = pFd->mmapSizeActual = nNew;
30272 }
30273 
30274 /*
30275 ** Memory map or remap the file opened by file-descriptor pFd (if the file
30276 ** is already mapped, the existing mapping is replaced by the new). Or, if
30277 ** there already exists a mapping for this file, and there are still
30278 ** outstanding xFetch() references to it, this function is a no-op.
30279 **
30280 ** If parameter nByte is non-negative, then it is the requested size of
30281 ** the mapping to create. Otherwise, if nByte is less than zero, then the
30282 ** requested size is the size of the file on disk. The actual size of the
30283 ** created mapping is either the requested size or the value configured
30284 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
30285 **
30286 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
30287 ** recreated as a result of outstanding references) or an SQLite error
30288 ** code otherwise.
30289 */
30290 static int unixMapfile(unixFile *pFd, i64 nByte){
30291   i64 nMap = nByte;
30292   int rc;
30293 
30294   assert( nMap>=0 || pFd->nFetchOut==0 );
30295   if( pFd->nFetchOut>0 ) return SQLITE_OK;
30296 
30297   if( nMap<0 ){
30298     struct stat statbuf;          /* Low-level file information */
30299     rc = osFstat(pFd->h, &statbuf);
30300     if( rc!=SQLITE_OK ){
30301       return SQLITE_IOERR_FSTAT;
30302     }
30303     nMap = statbuf.st_size;
30304   }
30305   if( nMap>pFd->mmapSizeMax ){
30306     nMap = pFd->mmapSizeMax;
30307   }
30308 
30309   if( nMap!=pFd->mmapSize ){
30310     if( nMap>0 ){
30311       unixRemapfile(pFd, nMap);
30312     }else{
30313       unixUnmapfile(pFd);
30314     }
30315   }
30316 
30317   return SQLITE_OK;
30318 }
30319 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
30320 
30321 /*
30322 ** If possible, return a pointer to a mapping of file fd starting at offset
30323 ** iOff. The mapping must be valid for at least nAmt bytes.
30324 **
30325 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
30326 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
30327 ** Finally, if an error does occur, return an SQLite error code. The final
30328 ** value of *pp is undefined in this case.
30329 **
30330 ** If this function does return a pointer, the caller must eventually
30331 ** release the reference by calling unixUnfetch().
30332 */
30333 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
30334 #if SQLITE_MAX_MMAP_SIZE>0
30335   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
30336 #endif
30337   *pp = 0;
30338 
30339 #if SQLITE_MAX_MMAP_SIZE>0
30340   if( pFd->mmapSizeMax>0 ){
30341     if( pFd->pMapRegion==0 ){
30342       int rc = unixMapfile(pFd, -1);
30343       if( rc!=SQLITE_OK ) return rc;
30344     }
30345     if( pFd->mmapSize >= iOff+nAmt ){
30346       *pp = &((u8 *)pFd->pMapRegion)[iOff];
30347       pFd->nFetchOut++;
30348     }
30349   }
30350 #endif
30351   return SQLITE_OK;
30352 }
30353 
30354 /*
30355 ** If the third argument is non-NULL, then this function releases a
30356 ** reference obtained by an earlier call to unixFetch(). The second
30357 ** argument passed to this function must be the same as the corresponding
30358 ** argument that was passed to the unixFetch() invocation.
30359 **
30360 ** Or, if the third argument is NULL, then this function is being called
30361 ** to inform the VFS layer that, according to POSIX, any existing mapping
30362 ** may now be invalid and should be unmapped.
30363 */
30364 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
30365 #if SQLITE_MAX_MMAP_SIZE>0
30366   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
30367   UNUSED_PARAMETER(iOff);
30368 
30369   /* If p==0 (unmap the entire file) then there must be no outstanding
30370   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
30371   ** then there must be at least one outstanding.  */
30372   assert( (p==0)==(pFd->nFetchOut==0) );
30373 
30374   /* If p!=0, it must match the iOff value. */
30375   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
30376 
30377   if( p ){
30378     pFd->nFetchOut--;
30379   }else{
30380     unixUnmapfile(pFd);
30381   }
30382 
30383   assert( pFd->nFetchOut>=0 );
30384 #else
30385   UNUSED_PARAMETER(fd);
30386   UNUSED_PARAMETER(p);
30387   UNUSED_PARAMETER(iOff);
30388 #endif
30389   return SQLITE_OK;
30390 }
30391 
30392 /*
30393 ** Here ends the implementation of all sqlite3_file methods.
30394 **
30395 ********************** End sqlite3_file Methods *******************************
30396 ******************************************************************************/
30397 
30398 /*
30399 ** This division contains definitions of sqlite3_io_methods objects that
30400 ** implement various file locking strategies.  It also contains definitions
30401 ** of "finder" functions.  A finder-function is used to locate the appropriate
30402 ** sqlite3_io_methods object for a particular database file.  The pAppData
30403 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
30404 ** the correct finder-function for that VFS.
30405 **
30406 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
30407 ** object.  The only interesting finder-function is autolockIoFinder, which
30408 ** looks at the filesystem type and tries to guess the best locking
30409 ** strategy from that.
30410 **
30411 ** For finder-function F, two objects are created:
30412 **
30413 **    (1) The real finder-function named "FImpt()".
30414 **
30415 **    (2) A constant pointer to this function named just "F".
30416 **
30417 **
30418 ** A pointer to the F pointer is used as the pAppData value for VFS
30419 ** objects.  We have to do this instead of letting pAppData point
30420 ** directly at the finder-function since C90 rules prevent a void*
30421 ** from be cast into a function pointer.
30422 **
30423 **
30424 ** Each instance of this macro generates two objects:
30425 **
30426 **   *  A constant sqlite3_io_methods object call METHOD that has locking
30427 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
30428 **
30429 **   *  An I/O method finder function called FINDER that returns a pointer
30430 **      to the METHOD object in the previous bullet.
30431 */
30432 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP)     \
30433 static const sqlite3_io_methods METHOD = {                                   \
30434    VERSION,                    /* iVersion */                                \
30435    CLOSE,                      /* xClose */                                  \
30436    unixRead,                   /* xRead */                                   \
30437    unixWrite,                  /* xWrite */                                  \
30438    unixTruncate,               /* xTruncate */                               \
30439    unixSync,                   /* xSync */                                   \
30440    unixFileSize,               /* xFileSize */                               \
30441    LOCK,                       /* xLock */                                   \
30442    UNLOCK,                     /* xUnlock */                                 \
30443    CKLOCK,                     /* xCheckReservedLock */                      \
30444    unixFileControl,            /* xFileControl */                            \
30445    unixSectorSize,             /* xSectorSize */                             \
30446    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
30447    SHMMAP,                     /* xShmMap */                                 \
30448    unixShmLock,                /* xShmLock */                                \
30449    unixShmBarrier,             /* xShmBarrier */                             \
30450    unixShmUnmap,               /* xShmUnmap */                               \
30451    unixFetch,                  /* xFetch */                                  \
30452    unixUnfetch,                /* xUnfetch */                                \
30453 };                                                                           \
30454 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
30455   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
30456   return &METHOD;                                                            \
30457 }                                                                            \
30458 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
30459     = FINDER##Impl;
30460 
30461 /*
30462 ** Here are all of the sqlite3_io_methods objects for each of the
30463 ** locking strategies.  Functions that return pointers to these methods
30464 ** are also created.
30465 */
30466 IOMETHODS(
30467   posixIoFinder,            /* Finder function name */
30468   posixIoMethods,           /* sqlite3_io_methods object name */
30469   3,                        /* shared memory and mmap are enabled */
30470   unixClose,                /* xClose method */
30471   unixLock,                 /* xLock method */
30472   unixUnlock,               /* xUnlock method */
30473   unixCheckReservedLock,    /* xCheckReservedLock method */
30474   unixShmMap                /* xShmMap method */
30475 )
30476 IOMETHODS(
30477   nolockIoFinder,           /* Finder function name */
30478   nolockIoMethods,          /* sqlite3_io_methods object name */
30479   3,                        /* shared memory is disabled */
30480   nolockClose,              /* xClose method */
30481   nolockLock,               /* xLock method */
30482   nolockUnlock,             /* xUnlock method */
30483   nolockCheckReservedLock,  /* xCheckReservedLock method */
30484   0                         /* xShmMap method */
30485 )
30486 IOMETHODS(
30487   dotlockIoFinder,          /* Finder function name */
30488   dotlockIoMethods,         /* sqlite3_io_methods object name */
30489   1,                        /* shared memory is disabled */
30490   dotlockClose,             /* xClose method */
30491   dotlockLock,              /* xLock method */
30492   dotlockUnlock,            /* xUnlock method */
30493   dotlockCheckReservedLock, /* xCheckReservedLock method */
30494   0                         /* xShmMap method */
30495 )
30496 
30497 #if SQLITE_ENABLE_LOCKING_STYLE
30498 IOMETHODS(
30499   flockIoFinder,            /* Finder function name */
30500   flockIoMethods,           /* sqlite3_io_methods object name */
30501   1,                        /* shared memory is disabled */
30502   flockClose,               /* xClose method */
30503   flockLock,                /* xLock method */
30504   flockUnlock,              /* xUnlock method */
30505   flockCheckReservedLock,   /* xCheckReservedLock method */
30506   0                         /* xShmMap method */
30507 )
30508 #endif
30509 
30510 #if OS_VXWORKS
30511 IOMETHODS(
30512   semIoFinder,              /* Finder function name */
30513   semIoMethods,             /* sqlite3_io_methods object name */
30514   1,                        /* shared memory is disabled */
30515   semXClose,                /* xClose method */
30516   semXLock,                 /* xLock method */
30517   semXUnlock,               /* xUnlock method */
30518   semXCheckReservedLock,    /* xCheckReservedLock method */
30519   0                         /* xShmMap method */
30520 )
30521 #endif
30522 
30523 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30524 IOMETHODS(
30525   afpIoFinder,              /* Finder function name */
30526   afpIoMethods,             /* sqlite3_io_methods object name */
30527   1,                        /* shared memory is disabled */
30528   afpClose,                 /* xClose method */
30529   afpLock,                  /* xLock method */
30530   afpUnlock,                /* xUnlock method */
30531   afpCheckReservedLock,     /* xCheckReservedLock method */
30532   0                         /* xShmMap method */
30533 )
30534 #endif
30535 
30536 /*
30537 ** The proxy locking method is a "super-method" in the sense that it
30538 ** opens secondary file descriptors for the conch and lock files and
30539 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
30540 ** secondary files.  For this reason, the division that implements
30541 ** proxy locking is located much further down in the file.  But we need
30542 ** to go ahead and define the sqlite3_io_methods and finder function
30543 ** for proxy locking here.  So we forward declare the I/O methods.
30544 */
30545 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30546 static int proxyClose(sqlite3_file*);
30547 static int proxyLock(sqlite3_file*, int);
30548 static int proxyUnlock(sqlite3_file*, int);
30549 static int proxyCheckReservedLock(sqlite3_file*, int*);
30550 IOMETHODS(
30551   proxyIoFinder,            /* Finder function name */
30552   proxyIoMethods,           /* sqlite3_io_methods object name */
30553   1,                        /* shared memory is disabled */
30554   proxyClose,               /* xClose method */
30555   proxyLock,                /* xLock method */
30556   proxyUnlock,              /* xUnlock method */
30557   proxyCheckReservedLock,   /* xCheckReservedLock method */
30558   0                         /* xShmMap method */
30559 )
30560 #endif
30561 
30562 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
30563 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30564 IOMETHODS(
30565   nfsIoFinder,               /* Finder function name */
30566   nfsIoMethods,              /* sqlite3_io_methods object name */
30567   1,                         /* shared memory is disabled */
30568   unixClose,                 /* xClose method */
30569   unixLock,                  /* xLock method */
30570   nfsUnlock,                 /* xUnlock method */
30571   unixCheckReservedLock,     /* xCheckReservedLock method */
30572   0                          /* xShmMap method */
30573 )
30574 #endif
30575 
30576 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30577 /*
30578 ** This "finder" function attempts to determine the best locking strategy
30579 ** for the database file "filePath".  It then returns the sqlite3_io_methods
30580 ** object that implements that strategy.
30581 **
30582 ** This is for MacOSX only.
30583 */
30584 static const sqlite3_io_methods *autolockIoFinderImpl(
30585   const char *filePath,    /* name of the database file */
30586   unixFile *pNew           /* open file object for the database file */
30587 ){
30588   static const struct Mapping {
30589     const char *zFilesystem;              /* Filesystem type name */
30590     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
30591   } aMap[] = {
30592     { "hfs",    &posixIoMethods },
30593     { "ufs",    &posixIoMethods },
30594     { "afpfs",  &afpIoMethods },
30595     { "smbfs",  &afpIoMethods },
30596     { "webdav", &nolockIoMethods },
30597     { 0, 0 }
30598   };
30599   int i;
30600   struct statfs fsInfo;
30601   struct flock lockInfo;
30602 
30603   if( !filePath ){
30604     /* If filePath==NULL that means we are dealing with a transient file
30605     ** that does not need to be locked. */
30606     return &nolockIoMethods;
30607   }
30608   if( statfs(filePath, &fsInfo) != -1 ){
30609     if( fsInfo.f_flags & MNT_RDONLY ){
30610       return &nolockIoMethods;
30611     }
30612     for(i=0; aMap[i].zFilesystem; i++){
30613       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
30614         return aMap[i].pMethods;
30615       }
30616     }
30617   }
30618 
30619   /* Default case. Handles, amongst others, "nfs".
30620   ** Test byte-range lock using fcntl(). If the call succeeds,
30621   ** assume that the file-system supports POSIX style locks.
30622   */
30623   lockInfo.l_len = 1;
30624   lockInfo.l_start = 0;
30625   lockInfo.l_whence = SEEK_SET;
30626   lockInfo.l_type = F_RDLCK;
30627   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
30628     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
30629       return &nfsIoMethods;
30630     } else {
30631       return &posixIoMethods;
30632     }
30633   }else{
30634     return &dotlockIoMethods;
30635   }
30636 }
30637 static const sqlite3_io_methods
30638   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
30639 
30640 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
30641 
30642 #if OS_VXWORKS
30643 /*
30644 ** This "finder" function for VxWorks checks to see if posix advisory
30645 ** locking works.  If it does, then that is what is used.  If it does not
30646 ** work, then fallback to named semaphore locking.
30647 */
30648 static const sqlite3_io_methods *vxworksIoFinderImpl(
30649   const char *filePath,    /* name of the database file */
30650   unixFile *pNew           /* the open file object */
30651 ){
30652   struct flock lockInfo;
30653 
30654   if( !filePath ){
30655     /* If filePath==NULL that means we are dealing with a transient file
30656     ** that does not need to be locked. */
30657     return &nolockIoMethods;
30658   }
30659 
30660   /* Test if fcntl() is supported and use POSIX style locks.
30661   ** Otherwise fall back to the named semaphore method.
30662   */
30663   lockInfo.l_len = 1;
30664   lockInfo.l_start = 0;
30665   lockInfo.l_whence = SEEK_SET;
30666   lockInfo.l_type = F_RDLCK;
30667   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
30668     return &posixIoMethods;
30669   }else{
30670     return &semIoMethods;
30671   }
30672 }
30673 static const sqlite3_io_methods
30674   *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
30675 
30676 #endif /* OS_VXWORKS */
30677 
30678 /*
30679 ** An abstract type for a pointer to an IO method finder function:
30680 */
30681 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
30682 
30683 
30684 /****************************************************************************
30685 **************************** sqlite3_vfs methods ****************************
30686 **
30687 ** This division contains the implementation of methods on the
30688 ** sqlite3_vfs object.
30689 */
30690 
30691 /*
30692 ** Initialize the contents of the unixFile structure pointed to by pId.
30693 */
30694 static int fillInUnixFile(
30695   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
30696   int h,                  /* Open file descriptor of file being opened */
30697   sqlite3_file *pId,      /* Write to the unixFile structure here */
30698   const char *zFilename,  /* Name of the file being opened */
30699   int ctrlFlags           /* Zero or more UNIXFILE_* values */
30700 ){
30701   const sqlite3_io_methods *pLockingStyle;
30702   unixFile *pNew = (unixFile *)pId;
30703   int rc = SQLITE_OK;
30704 
30705   assert( pNew->pInode==NULL );
30706 
30707   /* Usually the path zFilename should not be a relative pathname. The
30708   ** exception is when opening the proxy "conch" file in builds that
30709   ** include the special Apple locking styles.
30710   */
30711 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30712   assert( zFilename==0 || zFilename[0]=='/'
30713     || pVfs->pAppData==(void*)&autolockIoFinder );
30714 #else
30715   assert( zFilename==0 || zFilename[0]=='/' );
30716 #endif
30717 
30718   /* No locking occurs in temporary files */
30719   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
30720 
30721   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
30722   pNew->h = h;
30723   pNew->pVfs = pVfs;
30724   pNew->zPath = zFilename;
30725   pNew->ctrlFlags = (u8)ctrlFlags;
30726 #if SQLITE_MAX_MMAP_SIZE>0
30727   pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
30728 #endif
30729   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
30730                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
30731     pNew->ctrlFlags |= UNIXFILE_PSOW;
30732   }
30733   if( strcmp(pVfs->zName,"unix-excl")==0 ){
30734     pNew->ctrlFlags |= UNIXFILE_EXCL;
30735   }
30736 
30737 #if OS_VXWORKS
30738   pNew->pId = vxworksFindFileId(zFilename);
30739   if( pNew->pId==0 ){
30740     ctrlFlags |= UNIXFILE_NOLOCK;
30741     rc = SQLITE_NOMEM;
30742   }
30743 #endif
30744 
30745   if( ctrlFlags & UNIXFILE_NOLOCK ){
30746     pLockingStyle = &nolockIoMethods;
30747   }else{
30748     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
30749 #if SQLITE_ENABLE_LOCKING_STYLE
30750     /* Cache zFilename in the locking context (AFP and dotlock override) for
30751     ** proxyLock activation is possible (remote proxy is based on db name)
30752     ** zFilename remains valid until file is closed, to support */
30753     pNew->lockingContext = (void*)zFilename;
30754 #endif
30755   }
30756 
30757   if( pLockingStyle == &posixIoMethods
30758 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30759     || pLockingStyle == &nfsIoMethods
30760 #endif
30761   ){
30762     unixEnterMutex();
30763     rc = findInodeInfo(pNew, &pNew->pInode);
30764     if( rc!=SQLITE_OK ){
30765       /* If an error occurred in findInodeInfo(), close the file descriptor
30766       ** immediately, before releasing the mutex. findInodeInfo() may fail
30767       ** in two scenarios:
30768       **
30769       **   (a) A call to fstat() failed.
30770       **   (b) A malloc failed.
30771       **
30772       ** Scenario (b) may only occur if the process is holding no other
30773       ** file descriptors open on the same file. If there were other file
30774       ** descriptors on this file, then no malloc would be required by
30775       ** findInodeInfo(). If this is the case, it is quite safe to close
30776       ** handle h - as it is guaranteed that no posix locks will be released
30777       ** by doing so.
30778       **
30779       ** If scenario (a) caused the error then things are not so safe. The
30780       ** implicit assumption here is that if fstat() fails, things are in
30781       ** such bad shape that dropping a lock or two doesn't matter much.
30782       */
30783       robust_close(pNew, h, __LINE__);
30784       h = -1;
30785     }
30786     unixLeaveMutex();
30787   }
30788 
30789 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30790   else if( pLockingStyle == &afpIoMethods ){
30791     /* AFP locking uses the file path so it needs to be included in
30792     ** the afpLockingContext.
30793     */
30794     afpLockingContext *pCtx;
30795     pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
30796     if( pCtx==0 ){
30797       rc = SQLITE_NOMEM;
30798     }else{
30799       /* NB: zFilename exists and remains valid until the file is closed
30800       ** according to requirement F11141.  So we do not need to make a
30801       ** copy of the filename. */
30802       pCtx->dbPath = zFilename;
30803       pCtx->reserved = 0;
30804       srandomdev();
30805       unixEnterMutex();
30806       rc = findInodeInfo(pNew, &pNew->pInode);
30807       if( rc!=SQLITE_OK ){
30808         sqlite3_free(pNew->lockingContext);
30809         robust_close(pNew, h, __LINE__);
30810         h = -1;
30811       }
30812       unixLeaveMutex();
30813     }
30814   }
30815 #endif
30816 
30817   else if( pLockingStyle == &dotlockIoMethods ){
30818     /* Dotfile locking uses the file path so it needs to be included in
30819     ** the dotlockLockingContext
30820     */
30821     char *zLockFile;
30822     int nFilename;
30823     assert( zFilename!=0 );
30824     nFilename = (int)strlen(zFilename) + 6;
30825     zLockFile = (char *)sqlite3_malloc64(nFilename);
30826     if( zLockFile==0 ){
30827       rc = SQLITE_NOMEM;
30828     }else{
30829       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
30830     }
30831     pNew->lockingContext = zLockFile;
30832   }
30833 
30834 #if OS_VXWORKS
30835   else if( pLockingStyle == &semIoMethods ){
30836     /* Named semaphore locking uses the file path so it needs to be
30837     ** included in the semLockingContext
30838     */
30839     unixEnterMutex();
30840     rc = findInodeInfo(pNew, &pNew->pInode);
30841     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
30842       char *zSemName = pNew->pInode->aSemName;
30843       int n;
30844       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
30845                        pNew->pId->zCanonicalName);
30846       for( n=1; zSemName[n]; n++ )
30847         if( zSemName[n]=='/' ) zSemName[n] = '_';
30848       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
30849       if( pNew->pInode->pSem == SEM_FAILED ){
30850         rc = SQLITE_NOMEM;
30851         pNew->pInode->aSemName[0] = '\0';
30852       }
30853     }
30854     unixLeaveMutex();
30855   }
30856 #endif
30857 
30858   storeLastErrno(pNew, 0);
30859 #if OS_VXWORKS
30860   if( rc!=SQLITE_OK ){
30861     if( h>=0 ) robust_close(pNew, h, __LINE__);
30862     h = -1;
30863     osUnlink(zFilename);
30864     pNew->ctrlFlags |= UNIXFILE_DELETE;
30865   }
30866 #endif
30867   if( rc!=SQLITE_OK ){
30868     if( h>=0 ) robust_close(pNew, h, __LINE__);
30869   }else{
30870     pNew->pMethod = pLockingStyle;
30871     OpenCounter(+1);
30872     verifyDbFile(pNew);
30873   }
30874   return rc;
30875 }
30876 
30877 /*
30878 ** Return the name of a directory in which to put temporary files.
30879 ** If no suitable temporary file directory can be found, return NULL.
30880 */
30881 static const char *unixTempFileDir(void){
30882   static const char *azDirs[] = {
30883      0,
30884      0,
30885      0,
30886      "/var/tmp",
30887      "/usr/tmp",
30888      "/tmp",
30889      0        /* List terminator */
30890   };
30891   unsigned int i;
30892   struct stat buf;
30893   const char *zDir = 0;
30894 
30895   azDirs[0] = sqlite3_temp_directory;
30896   if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
30897   if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
30898   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
30899     if( zDir==0 ) continue;
30900     if( osStat(zDir, &buf) ) continue;
30901     if( !S_ISDIR(buf.st_mode) ) continue;
30902     if( osAccess(zDir, 07) ) continue;
30903     break;
30904   }
30905   return zDir;
30906 }
30907 
30908 /*
30909 ** Create a temporary file name in zBuf.  zBuf must be allocated
30910 ** by the calling process and must be big enough to hold at least
30911 ** pVfs->mxPathname bytes.
30912 */
30913 static int unixGetTempname(int nBuf, char *zBuf){
30914   static const unsigned char zChars[] =
30915     "abcdefghijklmnopqrstuvwxyz"
30916     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
30917     "0123456789";
30918   unsigned int i, j;
30919   const char *zDir;
30920 
30921   /* It's odd to simulate an io-error here, but really this is just
30922   ** using the io-error infrastructure to test that SQLite handles this
30923   ** function failing.
30924   */
30925   SimulateIOError( return SQLITE_IOERR );
30926 
30927   zDir = unixTempFileDir();
30928   if( zDir==0 ) zDir = ".";
30929 
30930   /* Check that the output buffer is large enough for the temporary file
30931   ** name. If it is not, return SQLITE_ERROR.
30932   */
30933   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
30934     return SQLITE_ERROR;
30935   }
30936 
30937   do{
30938     sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
30939     j = (int)strlen(zBuf);
30940     sqlite3_randomness(15, &zBuf[j]);
30941     for(i=0; i<15; i++, j++){
30942       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
30943     }
30944     zBuf[j] = 0;
30945     zBuf[j+1] = 0;
30946   }while( osAccess(zBuf,0)==0 );
30947   return SQLITE_OK;
30948 }
30949 
30950 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30951 /*
30952 ** Routine to transform a unixFile into a proxy-locking unixFile.
30953 ** Implementation in the proxy-lock division, but used by unixOpen()
30954 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
30955 */
30956 static int proxyTransformUnixFile(unixFile*, const char*);
30957 #endif
30958 
30959 /*
30960 ** Search for an unused file descriptor that was opened on the database
30961 ** file (not a journal or master-journal file) identified by pathname
30962 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
30963 ** argument to this function.
30964 **
30965 ** Such a file descriptor may exist if a database connection was closed
30966 ** but the associated file descriptor could not be closed because some
30967 ** other file descriptor open on the same file is holding a file-lock.
30968 ** Refer to comments in the unixClose() function and the lengthy comment
30969 ** describing "Posix Advisory Locking" at the start of this file for
30970 ** further details. Also, ticket #4018.
30971 **
30972 ** If a suitable file descriptor is found, then it is returned. If no
30973 ** such file descriptor is located, -1 is returned.
30974 */
30975 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
30976   UnixUnusedFd *pUnused = 0;
30977 
30978   /* Do not search for an unused file descriptor on vxworks. Not because
30979   ** vxworks would not benefit from the change (it might, we're not sure),
30980   ** but because no way to test it is currently available. It is better
30981   ** not to risk breaking vxworks support for the sake of such an obscure
30982   ** feature.  */
30983 #if !OS_VXWORKS
30984   struct stat sStat;                   /* Results of stat() call */
30985 
30986   /* A stat() call may fail for various reasons. If this happens, it is
30987   ** almost certain that an open() call on the same path will also fail.
30988   ** For this reason, if an error occurs in the stat() call here, it is
30989   ** ignored and -1 is returned. The caller will try to open a new file
30990   ** descriptor on the same path, fail, and return an error to SQLite.
30991   **
30992   ** Even if a subsequent open() call does succeed, the consequences of
30993   ** not searching for a reusable file descriptor are not dire.  */
30994   if( 0==osStat(zPath, &sStat) ){
30995     unixInodeInfo *pInode;
30996 
30997     unixEnterMutex();
30998     pInode = inodeList;
30999     while( pInode && (pInode->fileId.dev!=sStat.st_dev
31000                      || pInode->fileId.ino!=sStat.st_ino) ){
31001        pInode = pInode->pNext;
31002     }
31003     if( pInode ){
31004       UnixUnusedFd **pp;
31005       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
31006       pUnused = *pp;
31007       if( pUnused ){
31008         *pp = pUnused->pNext;
31009       }
31010     }
31011     unixLeaveMutex();
31012   }
31013 #endif    /* if !OS_VXWORKS */
31014   return pUnused;
31015 }
31016 
31017 /*
31018 ** This function is called by unixOpen() to determine the unix permissions
31019 ** to create new files with. If no error occurs, then SQLITE_OK is returned
31020 ** and a value suitable for passing as the third argument to open(2) is
31021 ** written to *pMode. If an IO error occurs, an SQLite error code is
31022 ** returned and the value of *pMode is not modified.
31023 **
31024 ** In most cases, this routine sets *pMode to 0, which will become
31025 ** an indication to robust_open() to create the file using
31026 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
31027 ** But if the file being opened is a WAL or regular journal file, then
31028 ** this function queries the file-system for the permissions on the
31029 ** corresponding database file and sets *pMode to this value. Whenever
31030 ** possible, WAL and journal files are created using the same permissions
31031 ** as the associated database file.
31032 **
31033 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
31034 ** original filename is unavailable.  But 8_3_NAMES is only used for
31035 ** FAT filesystems and permissions do not matter there, so just use
31036 ** the default permissions.
31037 */
31038 static int findCreateFileMode(
31039   const char *zPath,              /* Path of file (possibly) being created */
31040   int flags,                      /* Flags passed as 4th argument to xOpen() */
31041   mode_t *pMode,                  /* OUT: Permissions to open file with */
31042   uid_t *pUid,                    /* OUT: uid to set on the file */
31043   gid_t *pGid                     /* OUT: gid to set on the file */
31044 ){
31045   int rc = SQLITE_OK;             /* Return Code */
31046   *pMode = 0;
31047   *pUid = 0;
31048   *pGid = 0;
31049   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
31050     char zDb[MAX_PATHNAME+1];     /* Database file path */
31051     int nDb;                      /* Number of valid bytes in zDb */
31052     struct stat sStat;            /* Output of stat() on database file */
31053 
31054     /* zPath is a path to a WAL or journal file. The following block derives
31055     ** the path to the associated database file from zPath. This block handles
31056     ** the following naming conventions:
31057     **
31058     **   "<path to db>-journal"
31059     **   "<path to db>-wal"
31060     **   "<path to db>-journalNN"
31061     **   "<path to db>-walNN"
31062     **
31063     ** where NN is a decimal number. The NN naming schemes are
31064     ** used by the test_multiplex.c module.
31065     */
31066     nDb = sqlite3Strlen30(zPath) - 1;
31067 #ifdef SQLITE_ENABLE_8_3_NAMES
31068     while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
31069     if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
31070 #else
31071     while( zPath[nDb]!='-' ){
31072       assert( nDb>0 );
31073       assert( zPath[nDb]!='\n' );
31074       nDb--;
31075     }
31076 #endif
31077     memcpy(zDb, zPath, nDb);
31078     zDb[nDb] = '\0';
31079 
31080     if( 0==osStat(zDb, &sStat) ){
31081       *pMode = sStat.st_mode & 0777;
31082       *pUid = sStat.st_uid;
31083       *pGid = sStat.st_gid;
31084     }else{
31085       rc = SQLITE_IOERR_FSTAT;
31086     }
31087   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
31088     *pMode = 0600;
31089   }
31090   return rc;
31091 }
31092 
31093 /*
31094 ** Open the file zPath.
31095 **
31096 ** Previously, the SQLite OS layer used three functions in place of this
31097 ** one:
31098 **
31099 **     sqlite3OsOpenReadWrite();
31100 **     sqlite3OsOpenReadOnly();
31101 **     sqlite3OsOpenExclusive();
31102 **
31103 ** These calls correspond to the following combinations of flags:
31104 **
31105 **     ReadWrite() ->     (READWRITE | CREATE)
31106 **     ReadOnly()  ->     (READONLY)
31107 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
31108 **
31109 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
31110 ** true, the file was configured to be automatically deleted when the
31111 ** file handle closed. To achieve the same effect using this new
31112 ** interface, add the DELETEONCLOSE flag to those specified above for
31113 ** OpenExclusive().
31114 */
31115 static int unixOpen(
31116   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
31117   const char *zPath,           /* Pathname of file to be opened */
31118   sqlite3_file *pFile,         /* The file descriptor to be filled in */
31119   int flags,                   /* Input flags to control the opening */
31120   int *pOutFlags               /* Output flags returned to SQLite core */
31121 ){
31122   unixFile *p = (unixFile *)pFile;
31123   int fd = -1;                   /* File descriptor returned by open() */
31124   int openFlags = 0;             /* Flags to pass to open() */
31125   int eType = flags&0xFFFFFF00;  /* Type of file to open */
31126   int noLock;                    /* True to omit locking primitives */
31127   int rc = SQLITE_OK;            /* Function Return Code */
31128   int ctrlFlags = 0;             /* UNIXFILE_* flags */
31129 
31130   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
31131   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
31132   int isCreate     = (flags & SQLITE_OPEN_CREATE);
31133   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
31134   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
31135 #if SQLITE_ENABLE_LOCKING_STYLE
31136   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
31137 #endif
31138 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
31139   struct statfs fsInfo;
31140 #endif
31141 
31142   /* If creating a master or main-file journal, this function will open
31143   ** a file-descriptor on the directory too. The first time unixSync()
31144   ** is called the directory file descriptor will be fsync()ed and close()d.
31145   */
31146   int syncDir = (isCreate && (
31147         eType==SQLITE_OPEN_MASTER_JOURNAL
31148      || eType==SQLITE_OPEN_MAIN_JOURNAL
31149      || eType==SQLITE_OPEN_WAL
31150   ));
31151 
31152   /* If argument zPath is a NULL pointer, this function is required to open
31153   ** a temporary file. Use this buffer to store the file name in.
31154   */
31155   char zTmpname[MAX_PATHNAME+2];
31156   const char *zName = zPath;
31157 
31158   /* Check the following statements are true:
31159   **
31160   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
31161   **   (b) if CREATE is set, then READWRITE must also be set, and
31162   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
31163   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
31164   */
31165   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
31166   assert(isCreate==0 || isReadWrite);
31167   assert(isExclusive==0 || isCreate);
31168   assert(isDelete==0 || isCreate);
31169 
31170   /* The main DB, main journal, WAL file and master journal are never
31171   ** automatically deleted. Nor are they ever temporary files.  */
31172   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
31173   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
31174   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
31175   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
31176 
31177   /* Assert that the upper layer has set one of the "file-type" flags. */
31178   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
31179        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
31180        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
31181        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
31182   );
31183 
31184   /* Detect a pid change and reset the PRNG.  There is a race condition
31185   ** here such that two or more threads all trying to open databases at
31186   ** the same instant might all reset the PRNG.  But multiple resets
31187   ** are harmless.
31188   */
31189   if( randomnessPid!=osGetpid(0) ){
31190     randomnessPid = osGetpid(0);
31191     sqlite3_randomness(0,0);
31192   }
31193 
31194   memset(p, 0, sizeof(unixFile));
31195 
31196   if( eType==SQLITE_OPEN_MAIN_DB ){
31197     UnixUnusedFd *pUnused;
31198     pUnused = findReusableFd(zName, flags);
31199     if( pUnused ){
31200       fd = pUnused->fd;
31201     }else{
31202       pUnused = sqlite3_malloc64(sizeof(*pUnused));
31203       if( !pUnused ){
31204         return SQLITE_NOMEM;
31205       }
31206     }
31207     p->pUnused = pUnused;
31208 
31209     /* Database filenames are double-zero terminated if they are not
31210     ** URIs with parameters.  Hence, they can always be passed into
31211     ** sqlite3_uri_parameter(). */
31212     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
31213 
31214   }else if( !zName ){
31215     /* If zName is NULL, the upper layer is requesting a temp file. */
31216     assert(isDelete && !syncDir);
31217     rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
31218     if( rc!=SQLITE_OK ){
31219       return rc;
31220     }
31221     zName = zTmpname;
31222 
31223     /* Generated temporary filenames are always double-zero terminated
31224     ** for use by sqlite3_uri_parameter(). */
31225     assert( zName[strlen(zName)+1]==0 );
31226   }
31227 
31228   /* Determine the value of the flags parameter passed to POSIX function
31229   ** open(). These must be calculated even if open() is not called, as
31230   ** they may be stored as part of the file handle and used by the
31231   ** 'conch file' locking functions later on.  */
31232   if( isReadonly )  openFlags |= O_RDONLY;
31233   if( isReadWrite ) openFlags |= O_RDWR;
31234   if( isCreate )    openFlags |= O_CREAT;
31235   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
31236   openFlags |= (O_LARGEFILE|O_BINARY);
31237 
31238   if( fd<0 ){
31239     mode_t openMode;              /* Permissions to create file with */
31240     uid_t uid;                    /* Userid for the file */
31241     gid_t gid;                    /* Groupid for the file */
31242     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
31243     if( rc!=SQLITE_OK ){
31244       assert( !p->pUnused );
31245       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
31246       return rc;
31247     }
31248     fd = robust_open(zName, openFlags, openMode);
31249     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
31250     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
31251       /* Failed to open the file for read/write access. Try read-only. */
31252       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
31253       openFlags &= ~(O_RDWR|O_CREAT);
31254       flags |= SQLITE_OPEN_READONLY;
31255       openFlags |= O_RDONLY;
31256       isReadonly = 1;
31257       fd = robust_open(zName, openFlags, openMode);
31258     }
31259     if( fd<0 ){
31260       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
31261       goto open_finished;
31262     }
31263 
31264     /* If this process is running as root and if creating a new rollback
31265     ** journal or WAL file, set the ownership of the journal or WAL to be
31266     ** the same as the original database.
31267     */
31268     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
31269       osFchown(fd, uid, gid);
31270     }
31271   }
31272   assert( fd>=0 );
31273   if( pOutFlags ){
31274     *pOutFlags = flags;
31275   }
31276 
31277   if( p->pUnused ){
31278     p->pUnused->fd = fd;
31279     p->pUnused->flags = flags;
31280   }
31281 
31282   if( isDelete ){
31283 #if OS_VXWORKS
31284     zPath = zName;
31285 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
31286     zPath = sqlite3_mprintf("%s", zName);
31287     if( zPath==0 ){
31288       robust_close(p, fd, __LINE__);
31289       return SQLITE_NOMEM;
31290     }
31291 #else
31292     osUnlink(zName);
31293 #endif
31294   }
31295 #if SQLITE_ENABLE_LOCKING_STYLE
31296   else{
31297     p->openFlags = openFlags;
31298   }
31299 #endif
31300 
31301   noLock = eType!=SQLITE_OPEN_MAIN_DB;
31302 
31303 
31304 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
31305   if( fstatfs(fd, &fsInfo) == -1 ){
31306     storeLastErrno(p, errno);
31307     robust_close(p, fd, __LINE__);
31308     return SQLITE_IOERR_ACCESS;
31309   }
31310   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
31311     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
31312   }
31313   if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
31314     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
31315   }
31316 #endif
31317 
31318   /* Set up appropriate ctrlFlags */
31319   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
31320   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
31321   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
31322   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
31323   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
31324 
31325 #if SQLITE_ENABLE_LOCKING_STYLE
31326 #if SQLITE_PREFER_PROXY_LOCKING
31327   isAutoProxy = 1;
31328 #endif
31329   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
31330     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
31331     int useProxy = 0;
31332 
31333     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
31334     ** never use proxy, NULL means use proxy for non-local files only.  */
31335     if( envforce!=NULL ){
31336       useProxy = atoi(envforce)>0;
31337     }else{
31338       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
31339     }
31340     if( useProxy ){
31341       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
31342       if( rc==SQLITE_OK ){
31343         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
31344         if( rc!=SQLITE_OK ){
31345           /* Use unixClose to clean up the resources added in fillInUnixFile
31346           ** and clear all the structure's references.  Specifically,
31347           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
31348           */
31349           unixClose(pFile);
31350           return rc;
31351         }
31352       }
31353       goto open_finished;
31354     }
31355   }
31356 #endif
31357 
31358   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
31359 
31360 open_finished:
31361   if( rc!=SQLITE_OK ){
31362     sqlite3_free(p->pUnused);
31363   }
31364   return rc;
31365 }
31366 
31367 
31368 /*
31369 ** Delete the file at zPath. If the dirSync argument is true, fsync()
31370 ** the directory after deleting the file.
31371 */
31372 static int unixDelete(
31373   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
31374   const char *zPath,        /* Name of file to be deleted */
31375   int dirSync               /* If true, fsync() directory after deleting file */
31376 ){
31377   int rc = SQLITE_OK;
31378   UNUSED_PARAMETER(NotUsed);
31379   SimulateIOError(return SQLITE_IOERR_DELETE);
31380   if( osUnlink(zPath)==(-1) ){
31381     if( errno==ENOENT
31382 #if OS_VXWORKS
31383         || osAccess(zPath,0)!=0
31384 #endif
31385     ){
31386       rc = SQLITE_IOERR_DELETE_NOENT;
31387     }else{
31388       rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
31389     }
31390     return rc;
31391   }
31392 #ifndef SQLITE_DISABLE_DIRSYNC
31393   if( (dirSync & 1)!=0 ){
31394     int fd;
31395     rc = osOpenDirectory(zPath, &fd);
31396     if( rc==SQLITE_OK ){
31397 #if OS_VXWORKS
31398       if( fsync(fd)==-1 )
31399 #else
31400       if( fsync(fd) )
31401 #endif
31402       {
31403         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
31404       }
31405       robust_close(0, fd, __LINE__);
31406     }else if( rc==SQLITE_CANTOPEN ){
31407       rc = SQLITE_OK;
31408     }
31409   }
31410 #endif
31411   return rc;
31412 }
31413 
31414 /*
31415 ** Test the existence of or access permissions of file zPath. The
31416 ** test performed depends on the value of flags:
31417 **
31418 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
31419 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
31420 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
31421 **
31422 ** Otherwise return 0.
31423 */
31424 static int unixAccess(
31425   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
31426   const char *zPath,      /* Path of the file to examine */
31427   int flags,              /* What do we want to learn about the zPath file? */
31428   int *pResOut            /* Write result boolean here */
31429 ){
31430   int amode = 0;
31431   UNUSED_PARAMETER(NotUsed);
31432   SimulateIOError( return SQLITE_IOERR_ACCESS; );
31433   switch( flags ){
31434     case SQLITE_ACCESS_EXISTS:
31435       amode = F_OK;
31436       break;
31437     case SQLITE_ACCESS_READWRITE:
31438       amode = W_OK|R_OK;
31439       break;
31440     case SQLITE_ACCESS_READ:
31441       amode = R_OK;
31442       break;
31443 
31444     default:
31445       assert(!"Invalid flags argument");
31446   }
31447   *pResOut = (osAccess(zPath, amode)==0);
31448   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
31449     struct stat buf;
31450     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
31451       *pResOut = 0;
31452     }
31453   }
31454   return SQLITE_OK;
31455 }
31456 
31457 
31458 /*
31459 ** Turn a relative pathname into a full pathname. The relative path
31460 ** is stored as a nul-terminated string in the buffer pointed to by
31461 ** zPath.
31462 **
31463 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
31464 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
31465 ** this buffer before returning.
31466 */
31467 static int unixFullPathname(
31468   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
31469   const char *zPath,            /* Possibly relative input path */
31470   int nOut,                     /* Size of output buffer in bytes */
31471   char *zOut                    /* Output buffer */
31472 ){
31473 
31474   /* It's odd to simulate an io-error here, but really this is just
31475   ** using the io-error infrastructure to test that SQLite handles this
31476   ** function failing. This function could fail if, for example, the
31477   ** current working directory has been unlinked.
31478   */
31479   SimulateIOError( return SQLITE_ERROR );
31480 
31481   assert( pVfs->mxPathname==MAX_PATHNAME );
31482   UNUSED_PARAMETER(pVfs);
31483 
31484   zOut[nOut-1] = '\0';
31485   if( zPath[0]=='/' ){
31486     sqlite3_snprintf(nOut, zOut, "%s", zPath);
31487   }else{
31488     int nCwd;
31489     if( osGetcwd(zOut, nOut-1)==0 ){
31490       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
31491     }
31492     nCwd = (int)strlen(zOut);
31493     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
31494   }
31495   return SQLITE_OK;
31496 }
31497 
31498 
31499 #ifndef SQLITE_OMIT_LOAD_EXTENSION
31500 /*
31501 ** Interfaces for opening a shared library, finding entry points
31502 ** within the shared library, and closing the shared library.
31503 */
31504 #include <dlfcn.h>
31505 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
31506   UNUSED_PARAMETER(NotUsed);
31507   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
31508 }
31509 
31510 /*
31511 ** SQLite calls this function immediately after a call to unixDlSym() or
31512 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
31513 ** message is available, it is written to zBufOut. If no error message
31514 ** is available, zBufOut is left unmodified and SQLite uses a default
31515 ** error message.
31516 */
31517 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
31518   const char *zErr;
31519   UNUSED_PARAMETER(NotUsed);
31520   unixEnterMutex();
31521   zErr = dlerror();
31522   if( zErr ){
31523     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
31524   }
31525   unixLeaveMutex();
31526 }
31527 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
31528   /*
31529   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
31530   ** cast into a pointer to a function.  And yet the library dlsym() routine
31531   ** returns a void* which is really a pointer to a function.  So how do we
31532   ** use dlsym() with -pedantic-errors?
31533   **
31534   ** Variable x below is defined to be a pointer to a function taking
31535   ** parameters void* and const char* and returning a pointer to a function.
31536   ** We initialize x by assigning it a pointer to the dlsym() function.
31537   ** (That assignment requires a cast.)  Then we call the function that
31538   ** x points to.
31539   **
31540   ** This work-around is unlikely to work correctly on any system where
31541   ** you really cannot cast a function pointer into void*.  But then, on the
31542   ** other hand, dlsym() will not work on such a system either, so we have
31543   ** not really lost anything.
31544   */
31545   void (*(*x)(void*,const char*))(void);
31546   UNUSED_PARAMETER(NotUsed);
31547   x = (void(*(*)(void*,const char*))(void))dlsym;
31548   return (*x)(p, zSym);
31549 }
31550 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
31551   UNUSED_PARAMETER(NotUsed);
31552   dlclose(pHandle);
31553 }
31554 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
31555   #define unixDlOpen  0
31556   #define unixDlError 0
31557   #define unixDlSym   0
31558   #define unixDlClose 0
31559 #endif
31560 
31561 /*
31562 ** Write nBuf bytes of random data to the supplied buffer zBuf.
31563 */
31564 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
31565   UNUSED_PARAMETER(NotUsed);
31566   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
31567 
31568   /* We have to initialize zBuf to prevent valgrind from reporting
31569   ** errors.  The reports issued by valgrind are incorrect - we would
31570   ** prefer that the randomness be increased by making use of the
31571   ** uninitialized space in zBuf - but valgrind errors tend to worry
31572   ** some users.  Rather than argue, it seems easier just to initialize
31573   ** the whole array and silence valgrind, even if that means less randomness
31574   ** in the random seed.
31575   **
31576   ** When testing, initializing zBuf[] to zero is all we do.  That means
31577   ** that we always use the same random number sequence.  This makes the
31578   ** tests repeatable.
31579   */
31580   memset(zBuf, 0, nBuf);
31581   randomnessPid = osGetpid(0);
31582 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
31583   {
31584     int fd, got;
31585     fd = robust_open("/dev/urandom", O_RDONLY, 0);
31586     if( fd<0 ){
31587       time_t t;
31588       time(&t);
31589       memcpy(zBuf, &t, sizeof(t));
31590       memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
31591       assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
31592       nBuf = sizeof(t) + sizeof(randomnessPid);
31593     }else{
31594       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
31595       robust_close(0, fd, __LINE__);
31596     }
31597   }
31598 #endif
31599   return nBuf;
31600 }
31601 
31602 
31603 /*
31604 ** Sleep for a little while.  Return the amount of time slept.
31605 ** The argument is the number of microseconds we want to sleep.
31606 ** The return value is the number of microseconds of sleep actually
31607 ** requested from the underlying operating system, a number which
31608 ** might be greater than or equal to the argument, but not less
31609 ** than the argument.
31610 */
31611 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
31612 #if OS_VXWORKS
31613   struct timespec sp;
31614 
31615   sp.tv_sec = microseconds / 1000000;
31616   sp.tv_nsec = (microseconds % 1000000) * 1000;
31617   nanosleep(&sp, NULL);
31618   UNUSED_PARAMETER(NotUsed);
31619   return microseconds;
31620 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
31621   usleep(microseconds);
31622   UNUSED_PARAMETER(NotUsed);
31623   return microseconds;
31624 #else
31625   int seconds = (microseconds+999999)/1000000;
31626   sleep(seconds);
31627   UNUSED_PARAMETER(NotUsed);
31628   return seconds*1000000;
31629 #endif
31630 }
31631 
31632 /*
31633 ** The following variable, if set to a non-zero value, is interpreted as
31634 ** the number of seconds since 1970 and is used to set the result of
31635 ** sqlite3OsCurrentTime() during testing.
31636 */
31637 #ifdef SQLITE_TEST
31638 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
31639 #endif
31640 
31641 /*
31642 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
31643 ** the current time and date as a Julian Day number times 86_400_000.  In
31644 ** other words, write into *piNow the number of milliseconds since the Julian
31645 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
31646 ** proleptic Gregorian calendar.
31647 **
31648 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
31649 ** cannot be found.
31650 */
31651 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
31652   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
31653   int rc = SQLITE_OK;
31654 #if defined(NO_GETTOD)
31655   time_t t;
31656   time(&t);
31657   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
31658 #elif OS_VXWORKS
31659   struct timespec sNow;
31660   clock_gettime(CLOCK_REALTIME, &sNow);
31661   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
31662 #else
31663   struct timeval sNow;
31664   if( gettimeofday(&sNow, 0)==0 ){
31665     *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
31666   }else{
31667     rc = SQLITE_ERROR;
31668   }
31669 #endif
31670 
31671 #ifdef SQLITE_TEST
31672   if( sqlite3_current_time ){
31673     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
31674   }
31675 #endif
31676   UNUSED_PARAMETER(NotUsed);
31677   return rc;
31678 }
31679 
31680 /*
31681 ** Find the current time (in Universal Coordinated Time).  Write the
31682 ** current time and date as a Julian Day number into *prNow and
31683 ** return 0.  Return 1 if the time and date cannot be found.
31684 */
31685 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
31686   sqlite3_int64 i = 0;
31687   int rc;
31688   UNUSED_PARAMETER(NotUsed);
31689   rc = unixCurrentTimeInt64(0, &i);
31690   *prNow = i/86400000.0;
31691   return rc;
31692 }
31693 
31694 /*
31695 ** We added the xGetLastError() method with the intention of providing
31696 ** better low-level error messages when operating-system problems come up
31697 ** during SQLite operation.  But so far, none of that has been implemented
31698 ** in the core.  So this routine is never called.  For now, it is merely
31699 ** a place-holder.
31700 */
31701 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
31702   UNUSED_PARAMETER(NotUsed);
31703   UNUSED_PARAMETER(NotUsed2);
31704   UNUSED_PARAMETER(NotUsed3);
31705   return 0;
31706 }
31707 
31708 
31709 /*
31710 ************************ End of sqlite3_vfs methods ***************************
31711 ******************************************************************************/
31712 
31713 /******************************************************************************
31714 ************************** Begin Proxy Locking ********************************
31715 **
31716 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
31717 ** other locking methods on secondary lock files.  Proxy locking is a
31718 ** meta-layer over top of the primitive locking implemented above.  For
31719 ** this reason, the division that implements of proxy locking is deferred
31720 ** until late in the file (here) after all of the other I/O methods have
31721 ** been defined - so that the primitive locking methods are available
31722 ** as services to help with the implementation of proxy locking.
31723 **
31724 ****
31725 **
31726 ** The default locking schemes in SQLite use byte-range locks on the
31727 ** database file to coordinate safe, concurrent access by multiple readers
31728 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
31729 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
31730 ** as POSIX read & write locks over fixed set of locations (via fsctl),
31731 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
31732 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
31733 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
31734 ** address in the shared range is taken for a SHARED lock, the entire
31735 ** shared range is taken for an EXCLUSIVE lock):
31736 **
31737 **      PENDING_BYTE        0x40000000
31738 **      RESERVED_BYTE       0x40000001
31739 **      SHARED_RANGE        0x40000002 -> 0x40000200
31740 **
31741 ** This works well on the local file system, but shows a nearly 100x
31742 ** slowdown in read performance on AFP because the AFP client disables
31743 ** the read cache when byte-range locks are present.  Enabling the read
31744 ** cache exposes a cache coherency problem that is present on all OS X
31745 ** supported network file systems.  NFS and AFP both observe the
31746 ** close-to-open semantics for ensuring cache coherency
31747 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
31748 ** address the requirements for concurrent database access by multiple
31749 ** readers and writers
31750 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
31751 **
31752 ** To address the performance and cache coherency issues, proxy file locking
31753 ** changes the way database access is controlled by limiting access to a
31754 ** single host at a time and moving file locks off of the database file
31755 ** and onto a proxy file on the local file system.
31756 **
31757 **
31758 ** Using proxy locks
31759 ** -----------------
31760 **
31761 ** C APIs
31762 **
31763 **  sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
31764 **                       <proxy_path> | ":auto:");
31765 **  sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
31766 **                       &<proxy_path>);
31767 **
31768 **
31769 ** SQL pragmas
31770 **
31771 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
31772 **  PRAGMA [database.]lock_proxy_file
31773 **
31774 ** Specifying ":auto:" means that if there is a conch file with a matching
31775 ** host ID in it, the proxy path in the conch file will be used, otherwise
31776 ** a proxy path based on the user's temp dir
31777 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
31778 ** actual proxy file name is generated from the name and path of the
31779 ** database file.  For example:
31780 **
31781 **       For database path "/Users/me/foo.db"
31782 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
31783 **
31784 ** Once a lock proxy is configured for a database connection, it can not
31785 ** be removed, however it may be switched to a different proxy path via
31786 ** the above APIs (assuming the conch file is not being held by another
31787 ** connection or process).
31788 **
31789 **
31790 ** How proxy locking works
31791 ** -----------------------
31792 **
31793 ** Proxy file locking relies primarily on two new supporting files:
31794 **
31795 **   *  conch file to limit access to the database file to a single host
31796 **      at a time
31797 **
31798 **   *  proxy file to act as a proxy for the advisory locks normally
31799 **      taken on the database
31800 **
31801 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
31802 ** by taking an sqlite-style shared lock on the conch file, reading the
31803 ** contents and comparing the host's unique host ID (see below) and lock
31804 ** proxy path against the values stored in the conch.  The conch file is
31805 ** stored in the same directory as the database file and the file name
31806 ** is patterned after the database file name as ".<databasename>-conch".
31807 ** If the conch file does not exist, or its contents do not match the
31808 ** host ID and/or proxy path, then the lock is escalated to an exclusive
31809 ** lock and the conch file contents is updated with the host ID and proxy
31810 ** path and the lock is downgraded to a shared lock again.  If the conch
31811 ** is held by another process (with a shared lock), the exclusive lock
31812 ** will fail and SQLITE_BUSY is returned.
31813 **
31814 ** The proxy file - a single-byte file used for all advisory file locks
31815 ** normally taken on the database file.   This allows for safe sharing
31816 ** of the database file for multiple readers and writers on the same
31817 ** host (the conch ensures that they all use the same local lock file).
31818 **
31819 ** Requesting the lock proxy does not immediately take the conch, it is
31820 ** only taken when the first request to lock database file is made.
31821 ** This matches the semantics of the traditional locking behavior, where
31822 ** opening a connection to a database file does not take a lock on it.
31823 ** The shared lock and an open file descriptor are maintained until
31824 ** the connection to the database is closed.
31825 **
31826 ** The proxy file and the lock file are never deleted so they only need
31827 ** to be created the first time they are used.
31828 **
31829 ** Configuration options
31830 ** ---------------------
31831 **
31832 **  SQLITE_PREFER_PROXY_LOCKING
31833 **
31834 **       Database files accessed on non-local file systems are
31835 **       automatically configured for proxy locking, lock files are
31836 **       named automatically using the same logic as
31837 **       PRAGMA lock_proxy_file=":auto:"
31838 **
31839 **  SQLITE_PROXY_DEBUG
31840 **
31841 **       Enables the logging of error messages during host id file
31842 **       retrieval and creation
31843 **
31844 **  LOCKPROXYDIR
31845 **
31846 **       Overrides the default directory used for lock proxy files that
31847 **       are named automatically via the ":auto:" setting
31848 **
31849 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
31850 **
31851 **       Permissions to use when creating a directory for storing the
31852 **       lock proxy files, only used when LOCKPROXYDIR is not set.
31853 **
31854 **
31855 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
31856 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
31857 ** force proxy locking to be used for every database file opened, and 0
31858 ** will force automatic proxy locking to be disabled for all database
31859 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
31860 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
31861 */
31862 
31863 /*
31864 ** Proxy locking is only available on MacOSX
31865 */
31866 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31867 
31868 /*
31869 ** The proxyLockingContext has the path and file structures for the remote
31870 ** and local proxy files in it
31871 */
31872 typedef struct proxyLockingContext proxyLockingContext;
31873 struct proxyLockingContext {
31874   unixFile *conchFile;         /* Open conch file */
31875   char *conchFilePath;         /* Name of the conch file */
31876   unixFile *lockProxy;         /* Open proxy lock file */
31877   char *lockProxyPath;         /* Name of the proxy lock file */
31878   char *dbPath;                /* Name of the open file */
31879   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
31880   int nFails;                  /* Number of conch taking failures */
31881   void *oldLockingContext;     /* Original lockingcontext to restore on close */
31882   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
31883 };
31884 
31885 /*
31886 ** The proxy lock file path for the database at dbPath is written into lPath,
31887 ** which must point to valid, writable memory large enough for a maxLen length
31888 ** file path.
31889 */
31890 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
31891   int len;
31892   int dbLen;
31893   int i;
31894 
31895 #ifdef LOCKPROXYDIR
31896   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
31897 #else
31898 # ifdef _CS_DARWIN_USER_TEMP_DIR
31899   {
31900     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
31901       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
31902                lPath, errno, osGetpid(0)));
31903       return SQLITE_IOERR_LOCK;
31904     }
31905     len = strlcat(lPath, "sqliteplocks", maxLen);
31906   }
31907 # else
31908   len = strlcpy(lPath, "/tmp/", maxLen);
31909 # endif
31910 #endif
31911 
31912   if( lPath[len-1]!='/' ){
31913     len = strlcat(lPath, "/", maxLen);
31914   }
31915 
31916   /* transform the db path to a unique cache name */
31917   dbLen = (int)strlen(dbPath);
31918   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
31919     char c = dbPath[i];
31920     lPath[i+len] = (c=='/')?'_':c;
31921   }
31922   lPath[i+len]='\0';
31923   strlcat(lPath, ":auto:", maxLen);
31924   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
31925   return SQLITE_OK;
31926 }
31927 
31928 /*
31929  ** Creates the lock file and any missing directories in lockPath
31930  */
31931 static int proxyCreateLockPath(const char *lockPath){
31932   int i, len;
31933   char buf[MAXPATHLEN];
31934   int start = 0;
31935 
31936   assert(lockPath!=NULL);
31937   /* try to create all the intermediate directories */
31938   len = (int)strlen(lockPath);
31939   buf[0] = lockPath[0];
31940   for( i=1; i<len; i++ ){
31941     if( lockPath[i] == '/' && (i - start > 0) ){
31942       /* only mkdir if leaf dir != "." or "/" or ".." */
31943       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
31944          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
31945         buf[i]='\0';
31946         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
31947           int err=errno;
31948           if( err!=EEXIST ) {
31949             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
31950                      "'%s' proxy lock path=%s pid=%d\n",
31951                      buf, strerror(err), lockPath, osGetpid(0)));
31952             return err;
31953           }
31954         }
31955       }
31956       start=i+1;
31957     }
31958     buf[i] = lockPath[i];
31959   }
31960   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, osGetpid(0)));
31961   return 0;
31962 }
31963 
31964 /*
31965 ** Create a new VFS file descriptor (stored in memory obtained from
31966 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
31967 **
31968 ** The caller is responsible not only for closing the file descriptor
31969 ** but also for freeing the memory associated with the file descriptor.
31970 */
31971 static int proxyCreateUnixFile(
31972     const char *path,        /* path for the new unixFile */
31973     unixFile **ppFile,       /* unixFile created and returned by ref */
31974     int islockfile           /* if non zero missing dirs will be created */
31975 ) {
31976   int fd = -1;
31977   unixFile *pNew;
31978   int rc = SQLITE_OK;
31979   int openFlags = O_RDWR | O_CREAT;
31980   sqlite3_vfs dummyVfs;
31981   int terrno = 0;
31982   UnixUnusedFd *pUnused = NULL;
31983 
31984   /* 1. first try to open/create the file
31985   ** 2. if that fails, and this is a lock file (not-conch), try creating
31986   ** the parent directories and then try again.
31987   ** 3. if that fails, try to open the file read-only
31988   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
31989   */
31990   pUnused = findReusableFd(path, openFlags);
31991   if( pUnused ){
31992     fd = pUnused->fd;
31993   }else{
31994     pUnused = sqlite3_malloc64(sizeof(*pUnused));
31995     if( !pUnused ){
31996       return SQLITE_NOMEM;
31997     }
31998   }
31999   if( fd<0 ){
32000     fd = robust_open(path, openFlags, 0);
32001     terrno = errno;
32002     if( fd<0 && errno==ENOENT && islockfile ){
32003       if( proxyCreateLockPath(path) == SQLITE_OK ){
32004         fd = robust_open(path, openFlags, 0);
32005       }
32006     }
32007   }
32008   if( fd<0 ){
32009     openFlags = O_RDONLY;
32010     fd = robust_open(path, openFlags, 0);
32011     terrno = errno;
32012   }
32013   if( fd<0 ){
32014     if( islockfile ){
32015       return SQLITE_BUSY;
32016     }
32017     switch (terrno) {
32018       case EACCES:
32019         return SQLITE_PERM;
32020       case EIO:
32021         return SQLITE_IOERR_LOCK; /* even though it is the conch */
32022       default:
32023         return SQLITE_CANTOPEN_BKPT;
32024     }
32025   }
32026 
32027   pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
32028   if( pNew==NULL ){
32029     rc = SQLITE_NOMEM;
32030     goto end_create_proxy;
32031   }
32032   memset(pNew, 0, sizeof(unixFile));
32033   pNew->openFlags = openFlags;
32034   memset(&dummyVfs, 0, sizeof(dummyVfs));
32035   dummyVfs.pAppData = (void*)&autolockIoFinder;
32036   dummyVfs.zName = "dummy";
32037   pUnused->fd = fd;
32038   pUnused->flags = openFlags;
32039   pNew->pUnused = pUnused;
32040 
32041   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
32042   if( rc==SQLITE_OK ){
32043     *ppFile = pNew;
32044     return SQLITE_OK;
32045   }
32046 end_create_proxy:
32047   robust_close(pNew, fd, __LINE__);
32048   sqlite3_free(pNew);
32049   sqlite3_free(pUnused);
32050   return rc;
32051 }
32052 
32053 #ifdef SQLITE_TEST
32054 /* simulate multiple hosts by creating unique hostid file paths */
32055 SQLITE_API int sqlite3_hostid_num = 0;
32056 #endif
32057 
32058 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
32059 
32060 #ifdef HAVE_GETHOSTUUID
32061 /* Not always defined in the headers as it ought to be */
32062 extern int gethostuuid(uuid_t id, const struct timespec *wait);
32063 #endif
32064 
32065 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
32066 ** bytes of writable memory.
32067 */
32068 static int proxyGetHostID(unsigned char *pHostID, int *pError){
32069   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
32070   memset(pHostID, 0, PROXY_HOSTIDLEN);
32071 #ifdef HAVE_GETHOSTUUID
32072   {
32073     struct timespec timeout = {1, 0}; /* 1 sec timeout */
32074     if( gethostuuid(pHostID, &timeout) ){
32075       int err = errno;
32076       if( pError ){
32077         *pError = err;
32078       }
32079       return SQLITE_IOERR;
32080     }
32081   }
32082 #else
32083   UNUSED_PARAMETER(pError);
32084 #endif
32085 #ifdef SQLITE_TEST
32086   /* simulate multiple hosts by creating unique hostid file paths */
32087   if( sqlite3_hostid_num != 0){
32088     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
32089   }
32090 #endif
32091 
32092   return SQLITE_OK;
32093 }
32094 
32095 /* The conch file contains the header, host id and lock file path
32096  */
32097 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
32098 #define PROXY_HEADERLEN    1   /* conch file header length */
32099 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
32100 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
32101 
32102 /*
32103 ** Takes an open conch file, copies the contents to a new path and then moves
32104 ** it back.  The newly created file's file descriptor is assigned to the
32105 ** conch file structure and finally the original conch file descriptor is
32106 ** closed.  Returns zero if successful.
32107 */
32108 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
32109   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32110   unixFile *conchFile = pCtx->conchFile;
32111   char tPath[MAXPATHLEN];
32112   char buf[PROXY_MAXCONCHLEN];
32113   char *cPath = pCtx->conchFilePath;
32114   size_t readLen = 0;
32115   size_t pathLen = 0;
32116   char errmsg[64] = "";
32117   int fd = -1;
32118   int rc = -1;
32119   UNUSED_PARAMETER(myHostID);
32120 
32121   /* create a new path by replace the trailing '-conch' with '-break' */
32122   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
32123   if( pathLen>MAXPATHLEN || pathLen<6 ||
32124      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
32125     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
32126     goto end_breaklock;
32127   }
32128   /* read the conch content */
32129   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
32130   if( readLen<PROXY_PATHINDEX ){
32131     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
32132     goto end_breaklock;
32133   }
32134   /* write it out to the temporary break file */
32135   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
32136   if( fd<0 ){
32137     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
32138     goto end_breaklock;
32139   }
32140   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
32141     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
32142     goto end_breaklock;
32143   }
32144   if( rename(tPath, cPath) ){
32145     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
32146     goto end_breaklock;
32147   }
32148   rc = 0;
32149   fprintf(stderr, "broke stale lock on %s\n", cPath);
32150   robust_close(pFile, conchFile->h, __LINE__);
32151   conchFile->h = fd;
32152   conchFile->openFlags = O_RDWR | O_CREAT;
32153 
32154 end_breaklock:
32155   if( rc ){
32156     if( fd>=0 ){
32157       osUnlink(tPath);
32158       robust_close(pFile, fd, __LINE__);
32159     }
32160     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
32161   }
32162   return rc;
32163 }
32164 
32165 /* Take the requested lock on the conch file and break a stale lock if the
32166 ** host id matches.
32167 */
32168 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
32169   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32170   unixFile *conchFile = pCtx->conchFile;
32171   int rc = SQLITE_OK;
32172   int nTries = 0;
32173   struct timespec conchModTime;
32174 
32175   memset(&conchModTime, 0, sizeof(conchModTime));
32176   do {
32177     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
32178     nTries ++;
32179     if( rc==SQLITE_BUSY ){
32180       /* If the lock failed (busy):
32181        * 1st try: get the mod time of the conch, wait 0.5s and try again.
32182        * 2nd try: fail if the mod time changed or host id is different, wait
32183        *           10 sec and try again
32184        * 3rd try: break the lock unless the mod time has changed.
32185        */
32186       struct stat buf;
32187       if( osFstat(conchFile->h, &buf) ){
32188         storeLastErrno(pFile, errno);
32189         return SQLITE_IOERR_LOCK;
32190       }
32191 
32192       if( nTries==1 ){
32193         conchModTime = buf.st_mtimespec;
32194         usleep(500000); /* wait 0.5 sec and try the lock again*/
32195         continue;
32196       }
32197 
32198       assert( nTries>1 );
32199       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
32200          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
32201         return SQLITE_BUSY;
32202       }
32203 
32204       if( nTries==2 ){
32205         char tBuf[PROXY_MAXCONCHLEN];
32206         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
32207         if( len<0 ){
32208           storeLastErrno(pFile, errno);
32209           return SQLITE_IOERR_LOCK;
32210         }
32211         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
32212           /* don't break the lock if the host id doesn't match */
32213           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
32214             return SQLITE_BUSY;
32215           }
32216         }else{
32217           /* don't break the lock on short read or a version mismatch */
32218           return SQLITE_BUSY;
32219         }
32220         usleep(10000000); /* wait 10 sec and try the lock again */
32221         continue;
32222       }
32223 
32224       assert( nTries==3 );
32225       if( 0==proxyBreakConchLock(pFile, myHostID) ){
32226         rc = SQLITE_OK;
32227         if( lockType==EXCLUSIVE_LOCK ){
32228           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
32229         }
32230         if( !rc ){
32231           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
32232         }
32233       }
32234     }
32235   } while( rc==SQLITE_BUSY && nTries<3 );
32236 
32237   return rc;
32238 }
32239 
32240 /* Takes the conch by taking a shared lock and read the contents conch, if
32241 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
32242 ** lockPath means that the lockPath in the conch file will be used if the
32243 ** host IDs match, or a new lock path will be generated automatically
32244 ** and written to the conch file.
32245 */
32246 static int proxyTakeConch(unixFile *pFile){
32247   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32248 
32249   if( pCtx->conchHeld!=0 ){
32250     return SQLITE_OK;
32251   }else{
32252     unixFile *conchFile = pCtx->conchFile;
32253     uuid_t myHostID;
32254     int pError = 0;
32255     char readBuf[PROXY_MAXCONCHLEN];
32256     char lockPath[MAXPATHLEN];
32257     char *tempLockPath = NULL;
32258     int rc = SQLITE_OK;
32259     int createConch = 0;
32260     int hostIdMatch = 0;
32261     int readLen = 0;
32262     int tryOldLockPath = 0;
32263     int forceNewLockPath = 0;
32264 
32265     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
32266              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
32267              osGetpid(0)));
32268 
32269     rc = proxyGetHostID(myHostID, &pError);
32270     if( (rc&0xff)==SQLITE_IOERR ){
32271       storeLastErrno(pFile, pError);
32272       goto end_takeconch;
32273     }
32274     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
32275     if( rc!=SQLITE_OK ){
32276       goto end_takeconch;
32277     }
32278     /* read the existing conch file */
32279     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
32280     if( readLen<0 ){
32281       /* I/O error: lastErrno set by seekAndRead */
32282       storeLastErrno(pFile, conchFile->lastErrno);
32283       rc = SQLITE_IOERR_READ;
32284       goto end_takeconch;
32285     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
32286              readBuf[0]!=(char)PROXY_CONCHVERSION ){
32287       /* a short read or version format mismatch means we need to create a new
32288       ** conch file.
32289       */
32290       createConch = 1;
32291     }
32292     /* if the host id matches and the lock path already exists in the conch
32293     ** we'll try to use the path there, if we can't open that path, we'll
32294     ** retry with a new auto-generated path
32295     */
32296     do { /* in case we need to try again for an :auto: named lock file */
32297 
32298       if( !createConch && !forceNewLockPath ){
32299         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
32300                                   PROXY_HOSTIDLEN);
32301         /* if the conch has data compare the contents */
32302         if( !pCtx->lockProxyPath ){
32303           /* for auto-named local lock file, just check the host ID and we'll
32304            ** use the local lock file path that's already in there
32305            */
32306           if( hostIdMatch ){
32307             size_t pathLen = (readLen - PROXY_PATHINDEX);
32308 
32309             if( pathLen>=MAXPATHLEN ){
32310               pathLen=MAXPATHLEN-1;
32311             }
32312             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
32313             lockPath[pathLen] = 0;
32314             tempLockPath = lockPath;
32315             tryOldLockPath = 1;
32316             /* create a copy of the lock path if the conch is taken */
32317             goto end_takeconch;
32318           }
32319         }else if( hostIdMatch
32320                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
32321                            readLen-PROXY_PATHINDEX)
32322         ){
32323           /* conch host and lock path match */
32324           goto end_takeconch;
32325         }
32326       }
32327 
32328       /* if the conch isn't writable and doesn't match, we can't take it */
32329       if( (conchFile->openFlags&O_RDWR) == 0 ){
32330         rc = SQLITE_BUSY;
32331         goto end_takeconch;
32332       }
32333 
32334       /* either the conch didn't match or we need to create a new one */
32335       if( !pCtx->lockProxyPath ){
32336         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
32337         tempLockPath = lockPath;
32338         /* create a copy of the lock path _only_ if the conch is taken */
32339       }
32340 
32341       /* update conch with host and path (this will fail if other process
32342       ** has a shared lock already), if the host id matches, use the big
32343       ** stick.
32344       */
32345       futimes(conchFile->h, NULL);
32346       if( hostIdMatch && !createConch ){
32347         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
32348           /* We are trying for an exclusive lock but another thread in this
32349            ** same process is still holding a shared lock. */
32350           rc = SQLITE_BUSY;
32351         } else {
32352           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
32353         }
32354       }else{
32355         rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
32356       }
32357       if( rc==SQLITE_OK ){
32358         char writeBuffer[PROXY_MAXCONCHLEN];
32359         int writeSize = 0;
32360 
32361         writeBuffer[0] = (char)PROXY_CONCHVERSION;
32362         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
32363         if( pCtx->lockProxyPath!=NULL ){
32364           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
32365                   MAXPATHLEN);
32366         }else{
32367           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
32368         }
32369         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
32370         robust_ftruncate(conchFile->h, writeSize);
32371         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
32372         fsync(conchFile->h);
32373         /* If we created a new conch file (not just updated the contents of a
32374          ** valid conch file), try to match the permissions of the database
32375          */
32376         if( rc==SQLITE_OK && createConch ){
32377           struct stat buf;
32378           int err = osFstat(pFile->h, &buf);
32379           if( err==0 ){
32380             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
32381                                         S_IROTH|S_IWOTH);
32382             /* try to match the database file R/W permissions, ignore failure */
32383 #ifndef SQLITE_PROXY_DEBUG
32384             osFchmod(conchFile->h, cmode);
32385 #else
32386             do{
32387               rc = osFchmod(conchFile->h, cmode);
32388             }while( rc==(-1) && errno==EINTR );
32389             if( rc!=0 ){
32390               int code = errno;
32391               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
32392                       cmode, code, strerror(code));
32393             } else {
32394               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
32395             }
32396           }else{
32397             int code = errno;
32398             fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
32399                     err, code, strerror(code));
32400 #endif
32401           }
32402         }
32403       }
32404       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
32405 
32406     end_takeconch:
32407       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
32408       if( rc==SQLITE_OK && pFile->openFlags ){
32409         int fd;
32410         if( pFile->h>=0 ){
32411           robust_close(pFile, pFile->h, __LINE__);
32412         }
32413         pFile->h = -1;
32414         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
32415         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
32416         if( fd>=0 ){
32417           pFile->h = fd;
32418         }else{
32419           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
32420            during locking */
32421         }
32422       }
32423       if( rc==SQLITE_OK && !pCtx->lockProxy ){
32424         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
32425         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
32426         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
32427           /* we couldn't create the proxy lock file with the old lock file path
32428            ** so try again via auto-naming
32429            */
32430           forceNewLockPath = 1;
32431           tryOldLockPath = 0;
32432           continue; /* go back to the do {} while start point, try again */
32433         }
32434       }
32435       if( rc==SQLITE_OK ){
32436         /* Need to make a copy of path if we extracted the value
32437          ** from the conch file or the path was allocated on the stack
32438          */
32439         if( tempLockPath ){
32440           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
32441           if( !pCtx->lockProxyPath ){
32442             rc = SQLITE_NOMEM;
32443           }
32444         }
32445       }
32446       if( rc==SQLITE_OK ){
32447         pCtx->conchHeld = 1;
32448 
32449         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
32450           afpLockingContext *afpCtx;
32451           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
32452           afpCtx->dbPath = pCtx->lockProxyPath;
32453         }
32454       } else {
32455         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
32456       }
32457       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
32458                rc==SQLITE_OK?"ok":"failed"));
32459       return rc;
32460     } while (1); /* in case we need to retry the :auto: lock file -
32461                  ** we should never get here except via the 'continue' call. */
32462   }
32463 }
32464 
32465 /*
32466 ** If pFile holds a lock on a conch file, then release that lock.
32467 */
32468 static int proxyReleaseConch(unixFile *pFile){
32469   int rc = SQLITE_OK;         /* Subroutine return code */
32470   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
32471   unixFile *conchFile;        /* Name of the conch file */
32472 
32473   pCtx = (proxyLockingContext *)pFile->lockingContext;
32474   conchFile = pCtx->conchFile;
32475   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
32476            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
32477            osGetpid(0)));
32478   if( pCtx->conchHeld>0 ){
32479     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
32480   }
32481   pCtx->conchHeld = 0;
32482   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
32483            (rc==SQLITE_OK ? "ok" : "failed")));
32484   return rc;
32485 }
32486 
32487 /*
32488 ** Given the name of a database file, compute the name of its conch file.
32489 ** Store the conch filename in memory obtained from sqlite3_malloc64().
32490 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
32491 ** or SQLITE_NOMEM if unable to obtain memory.
32492 **
32493 ** The caller is responsible for ensuring that the allocated memory
32494 ** space is eventually freed.
32495 **
32496 ** *pConchPath is set to NULL if a memory allocation error occurs.
32497 */
32498 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
32499   int i;                        /* Loop counter */
32500   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
32501   char *conchPath;              /* buffer in which to construct conch name */
32502 
32503   /* Allocate space for the conch filename and initialize the name to
32504   ** the name of the original database file. */
32505   *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
32506   if( conchPath==0 ){
32507     return SQLITE_NOMEM;
32508   }
32509   memcpy(conchPath, dbPath, len+1);
32510 
32511   /* now insert a "." before the last / character */
32512   for( i=(len-1); i>=0; i-- ){
32513     if( conchPath[i]=='/' ){
32514       i++;
32515       break;
32516     }
32517   }
32518   conchPath[i]='.';
32519   while ( i<len ){
32520     conchPath[i+1]=dbPath[i];
32521     i++;
32522   }
32523 
32524   /* append the "-conch" suffix to the file */
32525   memcpy(&conchPath[i+1], "-conch", 7);
32526   assert( (int)strlen(conchPath) == len+7 );
32527 
32528   return SQLITE_OK;
32529 }
32530 
32531 
32532 /* Takes a fully configured proxy locking-style unix file and switches
32533 ** the local lock file path
32534 */
32535 static int switchLockProxyPath(unixFile *pFile, const char *path) {
32536   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
32537   char *oldPath = pCtx->lockProxyPath;
32538   int rc = SQLITE_OK;
32539 
32540   if( pFile->eFileLock!=NO_LOCK ){
32541     return SQLITE_BUSY;
32542   }
32543 
32544   /* nothing to do if the path is NULL, :auto: or matches the existing path */
32545   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
32546     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
32547     return SQLITE_OK;
32548   }else{
32549     unixFile *lockProxy = pCtx->lockProxy;
32550     pCtx->lockProxy=NULL;
32551     pCtx->conchHeld = 0;
32552     if( lockProxy!=NULL ){
32553       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
32554       if( rc ) return rc;
32555       sqlite3_free(lockProxy);
32556     }
32557     sqlite3_free(oldPath);
32558     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
32559   }
32560 
32561   return rc;
32562 }
32563 
32564 /*
32565 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
32566 ** is a string buffer at least MAXPATHLEN+1 characters in size.
32567 **
32568 ** This routine find the filename associated with pFile and writes it
32569 ** int dbPath.
32570 */
32571 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
32572 #if defined(__APPLE__)
32573   if( pFile->pMethod == &afpIoMethods ){
32574     /* afp style keeps a reference to the db path in the filePath field
32575     ** of the struct */
32576     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
32577     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
32578             MAXPATHLEN);
32579   } else
32580 #endif
32581   if( pFile->pMethod == &dotlockIoMethods ){
32582     /* dot lock style uses the locking context to store the dot lock
32583     ** file path */
32584     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
32585     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
32586   }else{
32587     /* all other styles use the locking context to store the db file path */
32588     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
32589     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
32590   }
32591   return SQLITE_OK;
32592 }
32593 
32594 /*
32595 ** Takes an already filled in unix file and alters it so all file locking
32596 ** will be performed on the local proxy lock file.  The following fields
32597 ** are preserved in the locking context so that they can be restored and
32598 ** the unix structure properly cleaned up at close time:
32599 **  ->lockingContext
32600 **  ->pMethod
32601 */
32602 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
32603   proxyLockingContext *pCtx;
32604   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
32605   char *lockPath=NULL;
32606   int rc = SQLITE_OK;
32607 
32608   if( pFile->eFileLock!=NO_LOCK ){
32609     return SQLITE_BUSY;
32610   }
32611   proxyGetDbPathForUnixFile(pFile, dbPath);
32612   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
32613     lockPath=NULL;
32614   }else{
32615     lockPath=(char *)path;
32616   }
32617 
32618   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
32619            (lockPath ? lockPath : ":auto:"), osGetpid(0)));
32620 
32621   pCtx = sqlite3_malloc64( sizeof(*pCtx) );
32622   if( pCtx==0 ){
32623     return SQLITE_NOMEM;
32624   }
32625   memset(pCtx, 0, sizeof(*pCtx));
32626 
32627   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
32628   if( rc==SQLITE_OK ){
32629     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
32630     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
32631       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
32632       ** (c) the file system is read-only, then enable no-locking access.
32633       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
32634       ** that openFlags will have only one of O_RDONLY or O_RDWR.
32635       */
32636       struct statfs fsInfo;
32637       struct stat conchInfo;
32638       int goLockless = 0;
32639 
32640       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
32641         int err = errno;
32642         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
32643           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
32644         }
32645       }
32646       if( goLockless ){
32647         pCtx->conchHeld = -1; /* read only FS/ lockless */
32648         rc = SQLITE_OK;
32649       }
32650     }
32651   }
32652   if( rc==SQLITE_OK && lockPath ){
32653     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
32654   }
32655 
32656   if( rc==SQLITE_OK ){
32657     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
32658     if( pCtx->dbPath==NULL ){
32659       rc = SQLITE_NOMEM;
32660     }
32661   }
32662   if( rc==SQLITE_OK ){
32663     /* all memory is allocated, proxys are created and assigned,
32664     ** switch the locking context and pMethod then return.
32665     */
32666     pCtx->oldLockingContext = pFile->lockingContext;
32667     pFile->lockingContext = pCtx;
32668     pCtx->pOldMethod = pFile->pMethod;
32669     pFile->pMethod = &proxyIoMethods;
32670   }else{
32671     if( pCtx->conchFile ){
32672       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
32673       sqlite3_free(pCtx->conchFile);
32674     }
32675     sqlite3DbFree(0, pCtx->lockProxyPath);
32676     sqlite3_free(pCtx->conchFilePath);
32677     sqlite3_free(pCtx);
32678   }
32679   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
32680            (rc==SQLITE_OK ? "ok" : "failed")));
32681   return rc;
32682 }
32683 
32684 
32685 /*
32686 ** This routine handles sqlite3_file_control() calls that are specific
32687 ** to proxy locking.
32688 */
32689 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
32690   switch( op ){
32691     case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
32692       unixFile *pFile = (unixFile*)id;
32693       if( pFile->pMethod == &proxyIoMethods ){
32694         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
32695         proxyTakeConch(pFile);
32696         if( pCtx->lockProxyPath ){
32697           *(const char **)pArg = pCtx->lockProxyPath;
32698         }else{
32699           *(const char **)pArg = ":auto: (not held)";
32700         }
32701       } else {
32702         *(const char **)pArg = NULL;
32703       }
32704       return SQLITE_OK;
32705     }
32706     case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
32707       unixFile *pFile = (unixFile*)id;
32708       int rc = SQLITE_OK;
32709       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
32710       if( pArg==NULL || (const char *)pArg==0 ){
32711         if( isProxyStyle ){
32712           /* turn off proxy locking - not supported.  If support is added for
32713           ** switching proxy locking mode off then it will need to fail if
32714           ** the journal mode is WAL mode.
32715           */
32716           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
32717         }else{
32718           /* turn off proxy locking - already off - NOOP */
32719           rc = SQLITE_OK;
32720         }
32721       }else{
32722         const char *proxyPath = (const char *)pArg;
32723         if( isProxyStyle ){
32724           proxyLockingContext *pCtx =
32725             (proxyLockingContext*)pFile->lockingContext;
32726           if( !strcmp(pArg, ":auto:")
32727            || (pCtx->lockProxyPath &&
32728                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
32729           ){
32730             rc = SQLITE_OK;
32731           }else{
32732             rc = switchLockProxyPath(pFile, proxyPath);
32733           }
32734         }else{
32735           /* turn on proxy file locking */
32736           rc = proxyTransformUnixFile(pFile, proxyPath);
32737         }
32738       }
32739       return rc;
32740     }
32741     default: {
32742       assert( 0 );  /* The call assures that only valid opcodes are sent */
32743     }
32744   }
32745   /*NOTREACHED*/
32746   return SQLITE_ERROR;
32747 }
32748 
32749 /*
32750 ** Within this division (the proxying locking implementation) the procedures
32751 ** above this point are all utilities.  The lock-related methods of the
32752 ** proxy-locking sqlite3_io_method object follow.
32753 */
32754 
32755 
32756 /*
32757 ** This routine checks if there is a RESERVED lock held on the specified
32758 ** file by this or any other process. If such a lock is held, set *pResOut
32759 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
32760 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32761 */
32762 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
32763   unixFile *pFile = (unixFile*)id;
32764   int rc = proxyTakeConch(pFile);
32765   if( rc==SQLITE_OK ){
32766     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32767     if( pCtx->conchHeld>0 ){
32768       unixFile *proxy = pCtx->lockProxy;
32769       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
32770     }else{ /* conchHeld < 0 is lockless */
32771       pResOut=0;
32772     }
32773   }
32774   return rc;
32775 }
32776 
32777 /*
32778 ** Lock the file with the lock specified by parameter eFileLock - one
32779 ** of the following:
32780 **
32781 **     (1) SHARED_LOCK
32782 **     (2) RESERVED_LOCK
32783 **     (3) PENDING_LOCK
32784 **     (4) EXCLUSIVE_LOCK
32785 **
32786 ** Sometimes when requesting one lock state, additional lock states
32787 ** are inserted in between.  The locking might fail on one of the later
32788 ** transitions leaving the lock state different from what it started but
32789 ** still short of its goal.  The following chart shows the allowed
32790 ** transitions and the inserted intermediate states:
32791 **
32792 **    UNLOCKED -> SHARED
32793 **    SHARED -> RESERVED
32794 **    SHARED -> (PENDING) -> EXCLUSIVE
32795 **    RESERVED -> (PENDING) -> EXCLUSIVE
32796 **    PENDING -> EXCLUSIVE
32797 **
32798 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
32799 ** routine to lower a locking level.
32800 */
32801 static int proxyLock(sqlite3_file *id, int eFileLock) {
32802   unixFile *pFile = (unixFile*)id;
32803   int rc = proxyTakeConch(pFile);
32804   if( rc==SQLITE_OK ){
32805     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32806     if( pCtx->conchHeld>0 ){
32807       unixFile *proxy = pCtx->lockProxy;
32808       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
32809       pFile->eFileLock = proxy->eFileLock;
32810     }else{
32811       /* conchHeld < 0 is lockless */
32812     }
32813   }
32814   return rc;
32815 }
32816 
32817 
32818 /*
32819 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32820 ** must be either NO_LOCK or SHARED_LOCK.
32821 **
32822 ** If the locking level of the file descriptor is already at or below
32823 ** the requested locking level, this routine is a no-op.
32824 */
32825 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
32826   unixFile *pFile = (unixFile*)id;
32827   int rc = proxyTakeConch(pFile);
32828   if( rc==SQLITE_OK ){
32829     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32830     if( pCtx->conchHeld>0 ){
32831       unixFile *proxy = pCtx->lockProxy;
32832       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
32833       pFile->eFileLock = proxy->eFileLock;
32834     }else{
32835       /* conchHeld < 0 is lockless */
32836     }
32837   }
32838   return rc;
32839 }
32840 
32841 /*
32842 ** Close a file that uses proxy locks.
32843 */
32844 static int proxyClose(sqlite3_file *id) {
32845   if( id ){
32846     unixFile *pFile = (unixFile*)id;
32847     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32848     unixFile *lockProxy = pCtx->lockProxy;
32849     unixFile *conchFile = pCtx->conchFile;
32850     int rc = SQLITE_OK;
32851 
32852     if( lockProxy ){
32853       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
32854       if( rc ) return rc;
32855       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
32856       if( rc ) return rc;
32857       sqlite3_free(lockProxy);
32858       pCtx->lockProxy = 0;
32859     }
32860     if( conchFile ){
32861       if( pCtx->conchHeld ){
32862         rc = proxyReleaseConch(pFile);
32863         if( rc ) return rc;
32864       }
32865       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
32866       if( rc ) return rc;
32867       sqlite3_free(conchFile);
32868     }
32869     sqlite3DbFree(0, pCtx->lockProxyPath);
32870     sqlite3_free(pCtx->conchFilePath);
32871     sqlite3DbFree(0, pCtx->dbPath);
32872     /* restore the original locking context and pMethod then close it */
32873     pFile->lockingContext = pCtx->oldLockingContext;
32874     pFile->pMethod = pCtx->pOldMethod;
32875     sqlite3_free(pCtx);
32876     return pFile->pMethod->xClose(id);
32877   }
32878   return SQLITE_OK;
32879 }
32880 
32881 
32882 
32883 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32884 /*
32885 ** The proxy locking style is intended for use with AFP filesystems.
32886 ** And since AFP is only supported on MacOSX, the proxy locking is also
32887 ** restricted to MacOSX.
32888 **
32889 **
32890 ******************* End of the proxy lock implementation **********************
32891 ******************************************************************************/
32892 
32893 /*
32894 ** Initialize the operating system interface.
32895 **
32896 ** This routine registers all VFS implementations for unix-like operating
32897 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
32898 ** should be the only routines in this file that are visible from other
32899 ** files.
32900 **
32901 ** This routine is called once during SQLite initialization and by a
32902 ** single thread.  The memory allocation and mutex subsystems have not
32903 ** necessarily been initialized when this routine is called, and so they
32904 ** should not be used.
32905 */
32906 SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
32907   /*
32908   ** The following macro defines an initializer for an sqlite3_vfs object.
32909   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
32910   ** to the "finder" function.  (pAppData is a pointer to a pointer because
32911   ** silly C90 rules prohibit a void* from being cast to a function pointer
32912   ** and so we have to go through the intermediate pointer to avoid problems
32913   ** when compiling with -pedantic-errors on GCC.)
32914   **
32915   ** The FINDER parameter to this macro is the name of the pointer to the
32916   ** finder-function.  The finder-function returns a pointer to the
32917   ** sqlite_io_methods object that implements the desired locking
32918   ** behaviors.  See the division above that contains the IOMETHODS
32919   ** macro for addition information on finder-functions.
32920   **
32921   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
32922   ** object.  But the "autolockIoFinder" available on MacOSX does a little
32923   ** more than that; it looks at the filesystem type that hosts the
32924   ** database file and tries to choose an locking method appropriate for
32925   ** that filesystem time.
32926   */
32927   #define UNIXVFS(VFSNAME, FINDER) {                        \
32928     3,                    /* iVersion */                    \
32929     sizeof(unixFile),     /* szOsFile */                    \
32930     MAX_PATHNAME,         /* mxPathname */                  \
32931     0,                    /* pNext */                       \
32932     VFSNAME,              /* zName */                       \
32933     (void*)&FINDER,       /* pAppData */                    \
32934     unixOpen,             /* xOpen */                       \
32935     unixDelete,           /* xDelete */                     \
32936     unixAccess,           /* xAccess */                     \
32937     unixFullPathname,     /* xFullPathname */               \
32938     unixDlOpen,           /* xDlOpen */                     \
32939     unixDlError,          /* xDlError */                    \
32940     unixDlSym,            /* xDlSym */                      \
32941     unixDlClose,          /* xDlClose */                    \
32942     unixRandomness,       /* xRandomness */                 \
32943     unixSleep,            /* xSleep */                      \
32944     unixCurrentTime,      /* xCurrentTime */                \
32945     unixGetLastError,     /* xGetLastError */               \
32946     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
32947     unixSetSystemCall,    /* xSetSystemCall */              \
32948     unixGetSystemCall,    /* xGetSystemCall */              \
32949     unixNextSystemCall,   /* xNextSystemCall */             \
32950   }
32951 
32952   /*
32953   ** All default VFSes for unix are contained in the following array.
32954   **
32955   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
32956   ** by the SQLite core when the VFS is registered.  So the following
32957   ** array cannot be const.
32958   */
32959   static sqlite3_vfs aVfs[] = {
32960 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
32961     UNIXVFS("unix",          autolockIoFinder ),
32962 #elif OS_VXWORKS
32963     UNIXVFS("unix",          vxworksIoFinder ),
32964 #else
32965     UNIXVFS("unix",          posixIoFinder ),
32966 #endif
32967     UNIXVFS("unix-none",     nolockIoFinder ),
32968     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
32969     UNIXVFS("unix-excl",     posixIoFinder ),
32970 #if OS_VXWORKS
32971     UNIXVFS("unix-namedsem", semIoFinder ),
32972 #endif
32973 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
32974     UNIXVFS("unix-posix",    posixIoFinder ),
32975 #endif
32976 #if SQLITE_ENABLE_LOCKING_STYLE
32977     UNIXVFS("unix-flock",    flockIoFinder ),
32978 #endif
32979 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
32980     UNIXVFS("unix-afp",      afpIoFinder ),
32981     UNIXVFS("unix-nfs",      nfsIoFinder ),
32982     UNIXVFS("unix-proxy",    proxyIoFinder ),
32983 #endif
32984   };
32985   unsigned int i;          /* Loop counter */
32986 
32987   /* Double-check that the aSyscall[] array has been constructed
32988   ** correctly.  See ticket [bb3a86e890c8e96ab] */
32989   assert( ArraySize(aSyscall)==25 );
32990 
32991   /* Register all VFSes defined in the aVfs[] array */
32992   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
32993     sqlite3_vfs_register(&aVfs[i], i==0);
32994   }
32995   return SQLITE_OK;
32996 }
32997 
32998 /*
32999 ** Shutdown the operating system interface.
33000 **
33001 ** Some operating systems might need to do some cleanup in this routine,
33002 ** to release dynamically allocated objects.  But not on unix.
33003 ** This routine is a no-op for unix.
33004 */
33005 SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
33006   return SQLITE_OK;
33007 }
33008 
33009 #endif /* SQLITE_OS_UNIX */
33010 
33011 /************** End of os_unix.c *********************************************/
33012 /************** Begin file os_win.c ******************************************/
33013 /*
33014 ** 2004 May 22
33015 **
33016 ** The author disclaims copyright to this source code.  In place of
33017 ** a legal notice, here is a blessing:
33018 **
33019 **    May you do good and not evil.
33020 **    May you find forgiveness for yourself and forgive others.
33021 **    May you share freely, never taking more than you give.
33022 **
33023 ******************************************************************************
33024 **
33025 ** This file contains code that is specific to Windows.
33026 */
33027 #if SQLITE_OS_WIN               /* This file is used for Windows only */
33028 
33029 /*
33030 ** Include code that is common to all os_*.c files
33031 */
33032 /************** Include os_common.h in the middle of os_win.c ****************/
33033 /************** Begin file os_common.h ***************************************/
33034 /*
33035 ** 2004 May 22
33036 **
33037 ** The author disclaims copyright to this source code.  In place of
33038 ** a legal notice, here is a blessing:
33039 **
33040 **    May you do good and not evil.
33041 **    May you find forgiveness for yourself and forgive others.
33042 **    May you share freely, never taking more than you give.
33043 **
33044 ******************************************************************************
33045 **
33046 ** This file contains macros and a little bit of code that is common to
33047 ** all of the platform-specific files (os_*.c) and is #included into those
33048 ** files.
33049 **
33050 ** This file should be #included by the os_*.c files only.  It is not a
33051 ** general purpose header file.
33052 */
33053 #ifndef _OS_COMMON_H_
33054 #define _OS_COMMON_H_
33055 
33056 /*
33057 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
33058 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
33059 ** switch.  The following code should catch this problem at compile-time.
33060 */
33061 #ifdef MEMORY_DEBUG
33062 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
33063 #endif
33064 
33065 /*
33066 ** Macros for performance tracing.  Normally turned off.  Only works
33067 ** on i486 hardware.
33068 */
33069 #ifdef SQLITE_PERFORMANCE_TRACE
33070 
33071 /*
33072 ** hwtime.h contains inline assembler code for implementing
33073 ** high-performance timing routines.
33074 */
33075 /************** Include hwtime.h in the middle of os_common.h ****************/
33076 /************** Begin file hwtime.h ******************************************/
33077 /*
33078 ** 2008 May 27
33079 **
33080 ** The author disclaims copyright to this source code.  In place of
33081 ** a legal notice, here is a blessing:
33082 **
33083 **    May you do good and not evil.
33084 **    May you find forgiveness for yourself and forgive others.
33085 **    May you share freely, never taking more than you give.
33086 **
33087 ******************************************************************************
33088 **
33089 ** This file contains inline asm code for retrieving "high-performance"
33090 ** counters for x86 class CPUs.
33091 */
33092 #ifndef _HWTIME_H_
33093 #define _HWTIME_H_
33094 
33095 /*
33096 ** The following routine only works on pentium-class (or newer) processors.
33097 ** It uses the RDTSC opcode to read the cycle count value out of the
33098 ** processor and returns that value.  This can be used for high-res
33099 ** profiling.
33100 */
33101 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
33102       (defined(i386) || defined(__i386__) || defined(_M_IX86))
33103 
33104   #if defined(__GNUC__)
33105 
33106   __inline__ sqlite_uint64 sqlite3Hwtime(void){
33107      unsigned int lo, hi;
33108      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
33109      return (sqlite_uint64)hi << 32 | lo;
33110   }
33111 
33112   #elif defined(_MSC_VER)
33113 
33114   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
33115      __asm {
33116         rdtsc
33117         ret       ; return value at EDX:EAX
33118      }
33119   }
33120 
33121   #endif
33122 
33123 #elif (defined(__GNUC__) && defined(__x86_64__))
33124 
33125   __inline__ sqlite_uint64 sqlite3Hwtime(void){
33126       unsigned long val;
33127       __asm__ __volatile__ ("rdtsc" : "=A" (val));
33128       return val;
33129   }
33130 
33131 #elif (defined(__GNUC__) && defined(__ppc__))
33132 
33133   __inline__ sqlite_uint64 sqlite3Hwtime(void){
33134       unsigned long long retval;
33135       unsigned long junk;
33136       __asm__ __volatile__ ("\n\
33137           1:      mftbu   %1\n\
33138                   mftb    %L0\n\
33139                   mftbu   %0\n\
33140                   cmpw    %0,%1\n\
33141                   bne     1b"
33142                   : "=r" (retval), "=r" (junk));
33143       return retval;
33144   }
33145 
33146 #else
33147 
33148   #error Need implementation of sqlite3Hwtime() for your platform.
33149 
33150   /*
33151   ** To compile without implementing sqlite3Hwtime() for your platform,
33152   ** you can remove the above #error and use the following
33153   ** stub function.  You will lose timing support for many
33154   ** of the debugging and testing utilities, but it should at
33155   ** least compile and run.
33156   */
33157 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
33158 
33159 #endif
33160 
33161 #endif /* !defined(_HWTIME_H_) */
33162 
33163 /************** End of hwtime.h **********************************************/
33164 /************** Continuing where we left off in os_common.h ******************/
33165 
33166 static sqlite_uint64 g_start;
33167 static sqlite_uint64 g_elapsed;
33168 #define TIMER_START       g_start=sqlite3Hwtime()
33169 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
33170 #define TIMER_ELAPSED     g_elapsed
33171 #else
33172 #define TIMER_START
33173 #define TIMER_END
33174 #define TIMER_ELAPSED     ((sqlite_uint64)0)
33175 #endif
33176 
33177 /*
33178 ** If we compile with the SQLITE_TEST macro set, then the following block
33179 ** of code will give us the ability to simulate a disk I/O error.  This
33180 ** is used for testing the I/O recovery logic.
33181 */
33182 #ifdef SQLITE_TEST
33183 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
33184 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
33185 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
33186 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
33187 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
33188 SQLITE_API int sqlite3_diskfull_pending = 0;
33189 SQLITE_API int sqlite3_diskfull = 0;
33190 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
33191 #define SimulateIOError(CODE)  \
33192   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
33193        || sqlite3_io_error_pending-- == 1 )  \
33194               { local_ioerr(); CODE; }
33195 static void local_ioerr(){
33196   IOTRACE(("IOERR\n"));
33197   sqlite3_io_error_hit++;
33198   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
33199 }
33200 #define SimulateDiskfullError(CODE) \
33201    if( sqlite3_diskfull_pending ){ \
33202      if( sqlite3_diskfull_pending == 1 ){ \
33203        local_ioerr(); \
33204        sqlite3_diskfull = 1; \
33205        sqlite3_io_error_hit = 1; \
33206        CODE; \
33207      }else{ \
33208        sqlite3_diskfull_pending--; \
33209      } \
33210    }
33211 #else
33212 #define SimulateIOErrorBenign(X)
33213 #define SimulateIOError(A)
33214 #define SimulateDiskfullError(A)
33215 #endif
33216 
33217 /*
33218 ** When testing, keep a count of the number of open files.
33219 */
33220 #ifdef SQLITE_TEST
33221 SQLITE_API int sqlite3_open_file_count = 0;
33222 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
33223 #else
33224 #define OpenCounter(X)
33225 #endif
33226 
33227 #endif /* !defined(_OS_COMMON_H_) */
33228 
33229 /************** End of os_common.h *******************************************/
33230 /************** Continuing where we left off in os_win.c *********************/
33231 
33232 /*
33233 ** Include the header file for the Windows VFS.
33234 */
33235 
33236 /*
33237 ** Compiling and using WAL mode requires several APIs that are only
33238 ** available in Windows platforms based on the NT kernel.
33239 */
33240 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
33241 #  error "WAL mode requires support from the Windows NT kernel, compile\
33242  with SQLITE_OMIT_WAL."
33243 #endif
33244 
33245 #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
33246 #  error "Memory mapped files require support from the Windows NT kernel,\
33247  compile with SQLITE_MAX_MMAP_SIZE=0."
33248 #endif
33249 
33250 /*
33251 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
33252 ** based on the sub-platform)?
33253 */
33254 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
33255 #  define SQLITE_WIN32_HAS_ANSI
33256 #endif
33257 
33258 /*
33259 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
33260 ** based on the sub-platform)?
33261 */
33262 #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
33263     !defined(SQLITE_WIN32_NO_WIDE)
33264 #  define SQLITE_WIN32_HAS_WIDE
33265 #endif
33266 
33267 /*
33268 ** Make sure at least one set of Win32 APIs is available.
33269 */
33270 #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
33271 #  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
33272  must be defined."
33273 #endif
33274 
33275 /*
33276 ** Define the required Windows SDK version constants if they are not
33277 ** already available.
33278 */
33279 #ifndef NTDDI_WIN8
33280 #  define NTDDI_WIN8                        0x06020000
33281 #endif
33282 
33283 #ifndef NTDDI_WINBLUE
33284 #  define NTDDI_WINBLUE                     0x06030000
33285 #endif
33286 
33287 /*
33288 ** Check to see if the GetVersionEx[AW] functions are deprecated on the
33289 ** target system.  GetVersionEx was first deprecated in Win8.1.
33290 */
33291 #ifndef SQLITE_WIN32_GETVERSIONEX
33292 #  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
33293 #    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
33294 #  else
33295 #    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
33296 #  endif
33297 #endif
33298 
33299 /*
33300 ** This constant should already be defined (in the "WinDef.h" SDK file).
33301 */
33302 #ifndef MAX_PATH
33303 #  define MAX_PATH                      (260)
33304 #endif
33305 
33306 /*
33307 ** Maximum pathname length (in chars) for Win32.  This should normally be
33308 ** MAX_PATH.
33309 */
33310 #ifndef SQLITE_WIN32_MAX_PATH_CHARS
33311 #  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
33312 #endif
33313 
33314 /*
33315 ** This constant should already be defined (in the "WinNT.h" SDK file).
33316 */
33317 #ifndef UNICODE_STRING_MAX_CHARS
33318 #  define UNICODE_STRING_MAX_CHARS      (32767)
33319 #endif
33320 
33321 /*
33322 ** Maximum pathname length (in chars) for WinNT.  This should normally be
33323 ** UNICODE_STRING_MAX_CHARS.
33324 */
33325 #ifndef SQLITE_WINNT_MAX_PATH_CHARS
33326 #  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
33327 #endif
33328 
33329 /*
33330 ** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
33331 ** characters, so we allocate 4 bytes per character assuming worst-case of
33332 ** 4-bytes-per-character for UTF8.
33333 */
33334 #ifndef SQLITE_WIN32_MAX_PATH_BYTES
33335 #  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
33336 #endif
33337 
33338 /*
33339 ** Maximum pathname length (in bytes) for WinNT.  This should normally be
33340 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
33341 */
33342 #ifndef SQLITE_WINNT_MAX_PATH_BYTES
33343 #  define SQLITE_WINNT_MAX_PATH_BYTES   \
33344                             (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
33345 #endif
33346 
33347 /*
33348 ** Maximum error message length (in chars) for WinRT.
33349 */
33350 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
33351 #  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
33352 #endif
33353 
33354 /*
33355 ** Returns non-zero if the character should be treated as a directory
33356 ** separator.
33357 */
33358 #ifndef winIsDirSep
33359 #  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
33360 #endif
33361 
33362 /*
33363 ** This macro is used when a local variable is set to a value that is
33364 ** [sometimes] not used by the code (e.g. via conditional compilation).
33365 */
33366 #ifndef UNUSED_VARIABLE_VALUE
33367 #  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
33368 #endif
33369 
33370 /*
33371 ** Returns the character that should be used as the directory separator.
33372 */
33373 #ifndef winGetDirSep
33374 #  define winGetDirSep()                '\\'
33375 #endif
33376 
33377 /*
33378 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
33379 ** mode or memory mapped files (e.g. these APIs are available in the Windows
33380 ** CE SDK; however, they are not present in the header file)?
33381 */
33382 #if SQLITE_WIN32_FILEMAPPING_API && \
33383         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
33384 /*
33385 ** Two of the file mapping APIs are different under WinRT.  Figure out which
33386 ** set we need.
33387 */
33388 #if SQLITE_OS_WINRT
33389 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
33390         LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
33391 
33392 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
33393 #else
33394 #if defined(SQLITE_WIN32_HAS_ANSI)
33395 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
33396         DWORD, DWORD, DWORD, LPCSTR);
33397 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
33398 
33399 #if defined(SQLITE_WIN32_HAS_WIDE)
33400 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
33401         DWORD, DWORD, DWORD, LPCWSTR);
33402 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
33403 
33404 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
33405 #endif /* SQLITE_OS_WINRT */
33406 
33407 /*
33408 ** These file mapping APIs are common to both Win32 and WinRT.
33409 */
33410 
33411 WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
33412 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
33413 #endif /* SQLITE_WIN32_FILEMAPPING_API */
33414 
33415 /*
33416 ** Some Microsoft compilers lack this definition.
33417 */
33418 #ifndef INVALID_FILE_ATTRIBUTES
33419 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
33420 #endif
33421 
33422 #ifndef FILE_FLAG_MASK
33423 # define FILE_FLAG_MASK          (0xFF3C0000)
33424 #endif
33425 
33426 #ifndef FILE_ATTRIBUTE_MASK
33427 # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
33428 #endif
33429 
33430 #ifndef SQLITE_OMIT_WAL
33431 /* Forward references to structures used for WAL */
33432 typedef struct winShm winShm;           /* A connection to shared-memory */
33433 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
33434 #endif
33435 
33436 /*
33437 ** WinCE lacks native support for file locking so we have to fake it
33438 ** with some code of our own.
33439 */
33440 #if SQLITE_OS_WINCE
33441 typedef struct winceLock {
33442   int nReaders;       /* Number of reader locks obtained */
33443   BOOL bPending;      /* Indicates a pending lock has been obtained */
33444   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
33445   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
33446 } winceLock;
33447 #endif
33448 
33449 /*
33450 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
33451 ** portability layer.
33452 */
33453 typedef struct winFile winFile;
33454 struct winFile {
33455   const sqlite3_io_methods *pMethod; /*** Must be first ***/
33456   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
33457   HANDLE h;               /* Handle for accessing the file */
33458   u8 locktype;            /* Type of lock currently held on this file */
33459   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
33460   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
33461   DWORD lastErrno;        /* The Windows errno from the last I/O error */
33462 #ifndef SQLITE_OMIT_WAL
33463   winShm *pShm;           /* Instance of shared memory on this file */
33464 #endif
33465   const char *zPath;      /* Full pathname of this file */
33466   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
33467 #if SQLITE_OS_WINCE
33468   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
33469   HANDLE hMutex;          /* Mutex used to control access to shared lock */
33470   HANDLE hShared;         /* Shared memory segment used for locking */
33471   winceLock local;        /* Locks obtained by this instance of winFile */
33472   winceLock *shared;      /* Global shared lock memory for the file  */
33473 #endif
33474 #if SQLITE_MAX_MMAP_SIZE>0
33475   int nFetchOut;                /* Number of outstanding xFetch references */
33476   HANDLE hMap;                  /* Handle for accessing memory mapping */
33477   void *pMapRegion;             /* Area memory mapped */
33478   sqlite3_int64 mmapSize;       /* Usable size of mapped region */
33479   sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
33480   sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
33481 #endif
33482 };
33483 
33484 /*
33485 ** Allowed values for winFile.ctrlFlags
33486 */
33487 #define WINFILE_RDONLY          0x02   /* Connection is read only */
33488 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
33489 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
33490 
33491 /*
33492  * The size of the buffer used by sqlite3_win32_write_debug().
33493  */
33494 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
33495 #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
33496 #endif
33497 
33498 /*
33499  * The value used with sqlite3_win32_set_directory() to specify that
33500  * the data directory should be changed.
33501  */
33502 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
33503 #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
33504 #endif
33505 
33506 /*
33507  * The value used with sqlite3_win32_set_directory() to specify that
33508  * the temporary directory should be changed.
33509  */
33510 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
33511 #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
33512 #endif
33513 
33514 /*
33515  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
33516  * various Win32 API heap functions instead of our own.
33517  */
33518 #ifdef SQLITE_WIN32_MALLOC
33519 
33520 /*
33521  * If this is non-zero, an isolated heap will be created by the native Win32
33522  * allocator subsystem; otherwise, the default process heap will be used.  This
33523  * setting has no effect when compiling for WinRT.  By default, this is enabled
33524  * and an isolated heap will be created to store all allocated data.
33525  *
33526  ******************************************************************************
33527  * WARNING: It is important to note that when this setting is non-zero and the
33528  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
33529  *          function), all data that was allocated using the isolated heap will
33530  *          be freed immediately and any attempt to access any of that freed
33531  *          data will almost certainly result in an immediate access violation.
33532  ******************************************************************************
33533  */
33534 #ifndef SQLITE_WIN32_HEAP_CREATE
33535 #  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
33536 #endif
33537 
33538 /*
33539  * The initial size of the Win32-specific heap.  This value may be zero.
33540  */
33541 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
33542 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
33543                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
33544 #endif
33545 
33546 /*
33547  * The maximum size of the Win32-specific heap.  This value may be zero.
33548  */
33549 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
33550 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
33551 #endif
33552 
33553 /*
33554  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
33555  * zero for the default behavior.
33556  */
33557 #ifndef SQLITE_WIN32_HEAP_FLAGS
33558 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
33559 #endif
33560 
33561 
33562 /*
33563 ** The winMemData structure stores information required by the Win32-specific
33564 ** sqlite3_mem_methods implementation.
33565 */
33566 typedef struct winMemData winMemData;
33567 struct winMemData {
33568 #ifndef NDEBUG
33569   u32 magic1;   /* Magic number to detect structure corruption. */
33570 #endif
33571   HANDLE hHeap; /* The handle to our heap. */
33572   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
33573 #ifndef NDEBUG
33574   u32 magic2;   /* Magic number to detect structure corruption. */
33575 #endif
33576 };
33577 
33578 #ifndef NDEBUG
33579 #define WINMEM_MAGIC1     0x42b2830b
33580 #define WINMEM_MAGIC2     0xbd4d7cf4
33581 #endif
33582 
33583 static struct winMemData win_mem_data = {
33584 #ifndef NDEBUG
33585   WINMEM_MAGIC1,
33586 #endif
33587   NULL, FALSE
33588 #ifndef NDEBUG
33589   ,WINMEM_MAGIC2
33590 #endif
33591 };
33592 
33593 #ifndef NDEBUG
33594 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
33595 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
33596 #define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
33597 #else
33598 #define winMemAssertMagic()
33599 #endif
33600 
33601 #define winMemGetDataPtr()  &win_mem_data
33602 #define winMemGetHeap()     win_mem_data.hHeap
33603 #define winMemGetOwned()    win_mem_data.bOwned
33604 
33605 static void *winMemMalloc(int nBytes);
33606 static void winMemFree(void *pPrior);
33607 static void *winMemRealloc(void *pPrior, int nBytes);
33608 static int winMemSize(void *p);
33609 static int winMemRoundup(int n);
33610 static int winMemInit(void *pAppData);
33611 static void winMemShutdown(void *pAppData);
33612 
33613 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
33614 #endif /* SQLITE_WIN32_MALLOC */
33615 
33616 /*
33617 ** The following variable is (normally) set once and never changes
33618 ** thereafter.  It records whether the operating system is Win9x
33619 ** or WinNT.
33620 **
33621 ** 0:   Operating system unknown.
33622 ** 1:   Operating system is Win9x.
33623 ** 2:   Operating system is WinNT.
33624 **
33625 ** In order to facilitate testing on a WinNT system, the test fixture
33626 ** can manually set this value to 1 to emulate Win98 behavior.
33627 */
33628 #ifdef SQLITE_TEST
33629 SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
33630 #else
33631 static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
33632 #endif
33633 
33634 #ifndef SYSCALL
33635 #  define SYSCALL sqlite3_syscall_ptr
33636 #endif
33637 
33638 /*
33639 ** This function is not available on Windows CE or WinRT.
33640  */
33641 
33642 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
33643 #  define osAreFileApisANSI()       1
33644 #endif
33645 
33646 /*
33647 ** Many system calls are accessed through pointer-to-functions so that
33648 ** they may be overridden at runtime to facilitate fault injection during
33649 ** testing and sandboxing.  The following array holds the names and pointers
33650 ** to all overrideable system calls.
33651 */
33652 static struct win_syscall {
33653   const char *zName;            /* Name of the system call */
33654   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
33655   sqlite3_syscall_ptr pDefault; /* Default value */
33656 } aSyscall[] = {
33657 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33658   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
33659 #else
33660   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
33661 #endif
33662 
33663 #ifndef osAreFileApisANSI
33664 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
33665 #endif
33666 
33667 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
33668   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
33669 #else
33670   { "CharLowerW",              (SYSCALL)0,                       0 },
33671 #endif
33672 
33673 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
33674 
33675 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
33676   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
33677 #else
33678   { "CharUpperW",              (SYSCALL)0,                       0 },
33679 #endif
33680 
33681 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
33682 
33683   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
33684 
33685 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
33686 
33687 #if defined(SQLITE_WIN32_HAS_ANSI)
33688   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
33689 #else
33690   { "CreateFileA",             (SYSCALL)0,                       0 },
33691 #endif
33692 
33693 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
33694         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
33695 
33696 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33697   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
33698 #else
33699   { "CreateFileW",             (SYSCALL)0,                       0 },
33700 #endif
33701 
33702 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
33703         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
33704 
33705 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
33706         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
33707   { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
33708 #else
33709   { "CreateFileMappingA",      (SYSCALL)0,                       0 },
33710 #endif
33711 
33712 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
33713         DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
33714 
33715 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
33716         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
33717   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
33718 #else
33719   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
33720 #endif
33721 
33722 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
33723         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
33724 
33725 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33726   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
33727 #else
33728   { "CreateMutexW",            (SYSCALL)0,                       0 },
33729 #endif
33730 
33731 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
33732         LPCWSTR))aSyscall[8].pCurrent)
33733 
33734 #if defined(SQLITE_WIN32_HAS_ANSI)
33735   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
33736 #else
33737   { "DeleteFileA",             (SYSCALL)0,                       0 },
33738 #endif
33739 
33740 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
33741 
33742 #if defined(SQLITE_WIN32_HAS_WIDE)
33743   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
33744 #else
33745   { "DeleteFileW",             (SYSCALL)0,                       0 },
33746 #endif
33747 
33748 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
33749 
33750 #if SQLITE_OS_WINCE
33751   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
33752 #else
33753   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
33754 #endif
33755 
33756 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
33757         LPFILETIME))aSyscall[11].pCurrent)
33758 
33759 #if SQLITE_OS_WINCE
33760   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
33761 #else
33762   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
33763 #endif
33764 
33765 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
33766         LPSYSTEMTIME))aSyscall[12].pCurrent)
33767 
33768   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
33769 
33770 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
33771 
33772 #if defined(SQLITE_WIN32_HAS_ANSI)
33773   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
33774 #else
33775   { "FormatMessageA",          (SYSCALL)0,                       0 },
33776 #endif
33777 
33778 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
33779         DWORD,va_list*))aSyscall[14].pCurrent)
33780 
33781 #if defined(SQLITE_WIN32_HAS_WIDE)
33782   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
33783 #else
33784   { "FormatMessageW",          (SYSCALL)0,                       0 },
33785 #endif
33786 
33787 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
33788         DWORD,va_list*))aSyscall[15].pCurrent)
33789 
33790 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
33791   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
33792 #else
33793   { "FreeLibrary",             (SYSCALL)0,                       0 },
33794 #endif
33795 
33796 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
33797 
33798   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
33799 
33800 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
33801 
33802 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
33803   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
33804 #else
33805   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
33806 #endif
33807 
33808 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
33809         LPDWORD))aSyscall[18].pCurrent)
33810 
33811 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33812   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
33813 #else
33814   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
33815 #endif
33816 
33817 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
33818         LPDWORD))aSyscall[19].pCurrent)
33819 
33820 #if defined(SQLITE_WIN32_HAS_ANSI)
33821   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
33822 #else
33823   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
33824 #endif
33825 
33826 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
33827 
33828 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33829   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
33830 #else
33831   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
33832 #endif
33833 
33834 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
33835 
33836 #if defined(SQLITE_WIN32_HAS_WIDE)
33837   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
33838 #else
33839   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
33840 #endif
33841 
33842 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
33843         LPVOID))aSyscall[22].pCurrent)
33844 
33845 #if !SQLITE_OS_WINRT
33846   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
33847 #else
33848   { "GetFileSize",             (SYSCALL)0,                       0 },
33849 #endif
33850 
33851 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
33852 
33853 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
33854   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
33855 #else
33856   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
33857 #endif
33858 
33859 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
33860         LPSTR*))aSyscall[24].pCurrent)
33861 
33862 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33863   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
33864 #else
33865   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
33866 #endif
33867 
33868 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
33869         LPWSTR*))aSyscall[25].pCurrent)
33870 
33871   { "GetLastError",            (SYSCALL)GetLastError,            0 },
33872 
33873 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
33874 
33875 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
33876 #if SQLITE_OS_WINCE
33877   /* The GetProcAddressA() routine is only available on Windows CE. */
33878   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
33879 #else
33880   /* All other Windows platforms expect GetProcAddress() to take
33881   ** an ANSI string regardless of the _UNICODE setting */
33882   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
33883 #endif
33884 #else
33885   { "GetProcAddressA",         (SYSCALL)0,                       0 },
33886 #endif
33887 
33888 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
33889         LPCSTR))aSyscall[27].pCurrent)
33890 
33891 #if !SQLITE_OS_WINRT
33892   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
33893 #else
33894   { "GetSystemInfo",           (SYSCALL)0,                       0 },
33895 #endif
33896 
33897 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
33898 
33899   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
33900 
33901 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
33902 
33903 #if !SQLITE_OS_WINCE
33904   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
33905 #else
33906   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
33907 #endif
33908 
33909 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
33910         LPFILETIME))aSyscall[30].pCurrent)
33911 
33912 #if defined(SQLITE_WIN32_HAS_ANSI)
33913   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
33914 #else
33915   { "GetTempPathA",            (SYSCALL)0,                       0 },
33916 #endif
33917 
33918 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
33919 
33920 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33921   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
33922 #else
33923   { "GetTempPathW",            (SYSCALL)0,                       0 },
33924 #endif
33925 
33926 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
33927 
33928 #if !SQLITE_OS_WINRT
33929   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
33930 #else
33931   { "GetTickCount",            (SYSCALL)0,                       0 },
33932 #endif
33933 
33934 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
33935 
33936 #if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
33937         SQLITE_WIN32_GETVERSIONEX
33938   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
33939 #else
33940   { "GetVersionExA",           (SYSCALL)0,                       0 },
33941 #endif
33942 
33943 #define osGetVersionExA ((BOOL(WINAPI*)( \
33944         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
33945 
33946 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
33947         defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
33948   { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
33949 #else
33950   { "GetVersionExW",           (SYSCALL)0,                       0 },
33951 #endif
33952 
33953 #define osGetVersionExW ((BOOL(WINAPI*)( \
33954         LPOSVERSIONINFOW))aSyscall[35].pCurrent)
33955 
33956   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
33957 
33958 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
33959         SIZE_T))aSyscall[36].pCurrent)
33960 
33961 #if !SQLITE_OS_WINRT
33962   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
33963 #else
33964   { "HeapCreate",              (SYSCALL)0,                       0 },
33965 #endif
33966 
33967 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
33968         SIZE_T))aSyscall[37].pCurrent)
33969 
33970 #if !SQLITE_OS_WINRT
33971   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
33972 #else
33973   { "HeapDestroy",             (SYSCALL)0,                       0 },
33974 #endif
33975 
33976 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
33977 
33978   { "HeapFree",                (SYSCALL)HeapFree,                0 },
33979 
33980 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
33981 
33982   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
33983 
33984 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
33985         SIZE_T))aSyscall[40].pCurrent)
33986 
33987   { "HeapSize",                (SYSCALL)HeapSize,                0 },
33988 
33989 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
33990         LPCVOID))aSyscall[41].pCurrent)
33991 
33992 #if !SQLITE_OS_WINRT
33993   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
33994 #else
33995   { "HeapValidate",            (SYSCALL)0,                       0 },
33996 #endif
33997 
33998 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
33999         LPCVOID))aSyscall[42].pCurrent)
34000 
34001 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
34002   { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
34003 #else
34004   { "HeapCompact",             (SYSCALL)0,                       0 },
34005 #endif
34006 
34007 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
34008 
34009 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
34010   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
34011 #else
34012   { "LoadLibraryA",            (SYSCALL)0,                       0 },
34013 #endif
34014 
34015 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
34016 
34017 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
34018         !defined(SQLITE_OMIT_LOAD_EXTENSION)
34019   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
34020 #else
34021   { "LoadLibraryW",            (SYSCALL)0,                       0 },
34022 #endif
34023 
34024 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
34025 
34026 #if !SQLITE_OS_WINRT
34027   { "LocalFree",               (SYSCALL)LocalFree,               0 },
34028 #else
34029   { "LocalFree",               (SYSCALL)0,                       0 },
34030 #endif
34031 
34032 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
34033 
34034 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
34035   { "LockFile",                (SYSCALL)LockFile,                0 },
34036 #else
34037   { "LockFile",                (SYSCALL)0,                       0 },
34038 #endif
34039 
34040 #ifndef osLockFile
34041 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
34042         DWORD))aSyscall[47].pCurrent)
34043 #endif
34044 
34045 #if !SQLITE_OS_WINCE
34046   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
34047 #else
34048   { "LockFileEx",              (SYSCALL)0,                       0 },
34049 #endif
34050 
34051 #ifndef osLockFileEx
34052 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
34053         LPOVERLAPPED))aSyscall[48].pCurrent)
34054 #endif
34055 
34056 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
34057         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
34058   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
34059 #else
34060   { "MapViewOfFile",           (SYSCALL)0,                       0 },
34061 #endif
34062 
34063 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
34064         SIZE_T))aSyscall[49].pCurrent)
34065 
34066   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
34067 
34068 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
34069         int))aSyscall[50].pCurrent)
34070 
34071   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
34072 
34073 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
34074         LARGE_INTEGER*))aSyscall[51].pCurrent)
34075 
34076   { "ReadFile",                (SYSCALL)ReadFile,                0 },
34077 
34078 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
34079         LPOVERLAPPED))aSyscall[52].pCurrent)
34080 
34081   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
34082 
34083 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
34084 
34085 #if !SQLITE_OS_WINRT
34086   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
34087 #else
34088   { "SetFilePointer",          (SYSCALL)0,                       0 },
34089 #endif
34090 
34091 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
34092         DWORD))aSyscall[54].pCurrent)
34093 
34094 #if !SQLITE_OS_WINRT
34095   { "Sleep",                   (SYSCALL)Sleep,                   0 },
34096 #else
34097   { "Sleep",                   (SYSCALL)0,                       0 },
34098 #endif
34099 
34100 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
34101 
34102   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
34103 
34104 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
34105         LPFILETIME))aSyscall[56].pCurrent)
34106 
34107 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
34108   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
34109 #else
34110   { "UnlockFile",              (SYSCALL)0,                       0 },
34111 #endif
34112 
34113 #ifndef osUnlockFile
34114 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
34115         DWORD))aSyscall[57].pCurrent)
34116 #endif
34117 
34118 #if !SQLITE_OS_WINCE
34119   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
34120 #else
34121   { "UnlockFileEx",            (SYSCALL)0,                       0 },
34122 #endif
34123 
34124 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
34125         LPOVERLAPPED))aSyscall[58].pCurrent)
34126 
34127 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
34128   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
34129 #else
34130   { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
34131 #endif
34132 
34133 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
34134 
34135   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
34136 
34137 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
34138         LPCSTR,LPBOOL))aSyscall[60].pCurrent)
34139 
34140   { "WriteFile",               (SYSCALL)WriteFile,               0 },
34141 
34142 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
34143         LPOVERLAPPED))aSyscall[61].pCurrent)
34144 
34145 #if SQLITE_OS_WINRT
34146   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
34147 #else
34148   { "CreateEventExW",          (SYSCALL)0,                       0 },
34149 #endif
34150 
34151 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
34152         DWORD,DWORD))aSyscall[62].pCurrent)
34153 
34154 #if !SQLITE_OS_WINRT
34155   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
34156 #else
34157   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
34158 #endif
34159 
34160 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
34161         DWORD))aSyscall[63].pCurrent)
34162 
34163 #if !SQLITE_OS_WINCE
34164   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
34165 #else
34166   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
34167 #endif
34168 
34169 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
34170         BOOL))aSyscall[64].pCurrent)
34171 
34172 #if SQLITE_OS_WINRT
34173   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
34174 #else
34175   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
34176 #endif
34177 
34178 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
34179         PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
34180 
34181 #if SQLITE_OS_WINRT
34182   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
34183 #else
34184   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
34185 #endif
34186 
34187 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
34188         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
34189 
34190 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
34191   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
34192 #else
34193   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
34194 #endif
34195 
34196 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
34197         SIZE_T))aSyscall[67].pCurrent)
34198 
34199 #if SQLITE_OS_WINRT
34200   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
34201 #else
34202   { "CreateFile2",             (SYSCALL)0,                       0 },
34203 #endif
34204 
34205 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
34206         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
34207 
34208 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
34209   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
34210 #else
34211   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
34212 #endif
34213 
34214 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
34215         DWORD))aSyscall[69].pCurrent)
34216 
34217 #if SQLITE_OS_WINRT
34218   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
34219 #else
34220   { "GetTickCount64",          (SYSCALL)0,                       0 },
34221 #endif
34222 
34223 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
34224 
34225 #if SQLITE_OS_WINRT
34226   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
34227 #else
34228   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
34229 #endif
34230 
34231 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
34232         LPSYSTEM_INFO))aSyscall[71].pCurrent)
34233 
34234 #if defined(SQLITE_WIN32_HAS_ANSI)
34235   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
34236 #else
34237   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
34238 #endif
34239 
34240 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
34241 
34242 #if defined(SQLITE_WIN32_HAS_WIDE)
34243   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
34244 #else
34245   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
34246 #endif
34247 
34248 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
34249 
34250   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
34251 
34252 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
34253 
34254 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
34255   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
34256 #else
34257   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
34258 #endif
34259 
34260 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
34261         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
34262 
34263 /*
34264 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
34265 **       is really just a macro that uses a compiler intrinsic (e.g. x64).
34266 **       So do not try to make this is into a redefinable interface.
34267 */
34268 #if defined(InterlockedCompareExchange)
34269   { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
34270 
34271 #define osInterlockedCompareExchange InterlockedCompareExchange
34272 #else
34273   { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
34274 
34275 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
34276         SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
34277 #endif /* defined(InterlockedCompareExchange) */
34278 
34279 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
34280   { "UuidCreate",               (SYSCALL)UuidCreate,             0 },
34281 #else
34282   { "UuidCreate",               (SYSCALL)0,                      0 },
34283 #endif
34284 
34285 #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
34286 
34287 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
34288   { "UuidCreateSequential",     (SYSCALL)UuidCreateSequential,   0 },
34289 #else
34290   { "UuidCreateSequential",     (SYSCALL)0,                      0 },
34291 #endif
34292 
34293 #define osUuidCreateSequential \
34294         ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
34295 
34296 #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
34297   { "FlushViewOfFile",          (SYSCALL)FlushViewOfFile,        0 },
34298 #else
34299   { "FlushViewOfFile",          (SYSCALL)0,                      0 },
34300 #endif
34301 
34302 #define osFlushViewOfFile \
34303         ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
34304 
34305 }; /* End of the overrideable system calls */
34306 
34307 /*
34308 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
34309 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
34310 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
34311 ** system call named zName.
34312 */
34313 static int winSetSystemCall(
34314   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
34315   const char *zName,            /* Name of system call to override */
34316   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
34317 ){
34318   unsigned int i;
34319   int rc = SQLITE_NOTFOUND;
34320 
34321   UNUSED_PARAMETER(pNotUsed);
34322   if( zName==0 ){
34323     /* If no zName is given, restore all system calls to their default
34324     ** settings and return NULL
34325     */
34326     rc = SQLITE_OK;
34327     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
34328       if( aSyscall[i].pDefault ){
34329         aSyscall[i].pCurrent = aSyscall[i].pDefault;
34330       }
34331     }
34332   }else{
34333     /* If zName is specified, operate on only the one system call
34334     ** specified.
34335     */
34336     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
34337       if( strcmp(zName, aSyscall[i].zName)==0 ){
34338         if( aSyscall[i].pDefault==0 ){
34339           aSyscall[i].pDefault = aSyscall[i].pCurrent;
34340         }
34341         rc = SQLITE_OK;
34342         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
34343         aSyscall[i].pCurrent = pNewFunc;
34344         break;
34345       }
34346     }
34347   }
34348   return rc;
34349 }
34350 
34351 /*
34352 ** Return the value of a system call.  Return NULL if zName is not a
34353 ** recognized system call name.  NULL is also returned if the system call
34354 ** is currently undefined.
34355 */
34356 static sqlite3_syscall_ptr winGetSystemCall(
34357   sqlite3_vfs *pNotUsed,
34358   const char *zName
34359 ){
34360   unsigned int i;
34361 
34362   UNUSED_PARAMETER(pNotUsed);
34363   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
34364     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
34365   }
34366   return 0;
34367 }
34368 
34369 /*
34370 ** Return the name of the first system call after zName.  If zName==NULL
34371 ** then return the name of the first system call.  Return NULL if zName
34372 ** is the last system call or if zName is not the name of a valid
34373 ** system call.
34374 */
34375 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
34376   int i = -1;
34377 
34378   UNUSED_PARAMETER(p);
34379   if( zName ){
34380     for(i=0; i<ArraySize(aSyscall)-1; i++){
34381       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
34382     }
34383   }
34384   for(i++; i<ArraySize(aSyscall); i++){
34385     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
34386   }
34387   return 0;
34388 }
34389 
34390 #ifdef SQLITE_WIN32_MALLOC
34391 /*
34392 ** If a Win32 native heap has been configured, this function will attempt to
34393 ** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
34394 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
34395 ** "pnLargest" argument, if non-zero, will be used to return the size of the
34396 ** largest committed free block in the heap, in bytes.
34397 */
34398 SQLITE_API int SQLITE_STDCALL sqlite3_win32_compact_heap(LPUINT pnLargest){
34399   int rc = SQLITE_OK;
34400   UINT nLargest = 0;
34401   HANDLE hHeap;
34402 
34403   winMemAssertMagic();
34404   hHeap = winMemGetHeap();
34405   assert( hHeap!=0 );
34406   assert( hHeap!=INVALID_HANDLE_VALUE );
34407 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34408   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34409 #endif
34410 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
34411   if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
34412     DWORD lastErrno = osGetLastError();
34413     if( lastErrno==NO_ERROR ){
34414       sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
34415                   (void*)hHeap);
34416       rc = SQLITE_NOMEM;
34417     }else{
34418       sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
34419                   osGetLastError(), (void*)hHeap);
34420       rc = SQLITE_ERROR;
34421     }
34422   }
34423 #else
34424   sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
34425               (void*)hHeap);
34426   rc = SQLITE_NOTFOUND;
34427 #endif
34428   if( pnLargest ) *pnLargest = nLargest;
34429   return rc;
34430 }
34431 
34432 /*
34433 ** If a Win32 native heap has been configured, this function will attempt to
34434 ** destroy and recreate it.  If the Win32 native heap is not isolated and/or
34435 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
34436 ** be returned and no changes will be made to the Win32 native heap.
34437 */
34438 SQLITE_API int SQLITE_STDCALL sqlite3_win32_reset_heap(){
34439   int rc;
34440   MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
34441   MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
34442   MUTEX_LOGIC( pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); )
34443   MUTEX_LOGIC( pMem = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM); )
34444   sqlite3_mutex_enter(pMaster);
34445   sqlite3_mutex_enter(pMem);
34446   winMemAssertMagic();
34447   if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
34448     /*
34449     ** At this point, there should be no outstanding memory allocations on
34450     ** the heap.  Also, since both the master and memsys locks are currently
34451     ** being held by us, no other function (i.e. from another thread) should
34452     ** be able to even access the heap.  Attempt to destroy and recreate our
34453     ** isolated Win32 native heap now.
34454     */
34455     assert( winMemGetHeap()!=NULL );
34456     assert( winMemGetOwned() );
34457     assert( sqlite3_memory_used()==0 );
34458     winMemShutdown(winMemGetDataPtr());
34459     assert( winMemGetHeap()==NULL );
34460     assert( !winMemGetOwned() );
34461     assert( sqlite3_memory_used()==0 );
34462     rc = winMemInit(winMemGetDataPtr());
34463     assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
34464     assert( rc!=SQLITE_OK || winMemGetOwned() );
34465     assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
34466   }else{
34467     /*
34468     ** The Win32 native heap cannot be modified because it may be in use.
34469     */
34470     rc = SQLITE_BUSY;
34471   }
34472   sqlite3_mutex_leave(pMem);
34473   sqlite3_mutex_leave(pMaster);
34474   return rc;
34475 }
34476 #endif /* SQLITE_WIN32_MALLOC */
34477 
34478 /*
34479 ** This function outputs the specified (ANSI) string to the Win32 debugger
34480 ** (if available).
34481 */
34482 
34483 SQLITE_API void SQLITE_STDCALL sqlite3_win32_write_debug(const char *zBuf, int nBuf){
34484   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
34485   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
34486   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
34487   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
34488 #if defined(SQLITE_WIN32_HAS_ANSI)
34489   if( nMin>0 ){
34490     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
34491     memcpy(zDbgBuf, zBuf, nMin);
34492     osOutputDebugStringA(zDbgBuf);
34493   }else{
34494     osOutputDebugStringA(zBuf);
34495   }
34496 #elif defined(SQLITE_WIN32_HAS_WIDE)
34497   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
34498   if ( osMultiByteToWideChar(
34499           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
34500           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
34501     return;
34502   }
34503   osOutputDebugStringW((LPCWSTR)zDbgBuf);
34504 #else
34505   if( nMin>0 ){
34506     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
34507     memcpy(zDbgBuf, zBuf, nMin);
34508     fprintf(stderr, "%s", zDbgBuf);
34509   }else{
34510     fprintf(stderr, "%s", zBuf);
34511   }
34512 #endif
34513 }
34514 
34515 /*
34516 ** The following routine suspends the current thread for at least ms
34517 ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
34518 */
34519 #if SQLITE_OS_WINRT
34520 static HANDLE sleepObj = NULL;
34521 #endif
34522 
34523 SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds){
34524 #if SQLITE_OS_WINRT
34525   if ( sleepObj==NULL ){
34526     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
34527                                 SYNCHRONIZE);
34528   }
34529   assert( sleepObj!=NULL );
34530   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
34531 #else
34532   osSleep(milliseconds);
34533 #endif
34534 }
34535 
34536 #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
34537         SQLITE_THREADSAFE>0
34538 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
34539   DWORD rc;
34540   while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
34541                                        TRUE))==WAIT_IO_COMPLETION ){}
34542   return rc;
34543 }
34544 #endif
34545 
34546 /*
34547 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
34548 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
34549 **
34550 ** Here is an interesting observation:  Win95, Win98, and WinME lack
34551 ** the LockFileEx() API.  But we can still statically link against that
34552 ** API as long as we don't call it when running Win95/98/ME.  A call to
34553 ** this routine is used to determine if the host is Win95/98/ME or
34554 ** WinNT/2K/XP so that we will know whether or not we can safely call
34555 ** the LockFileEx() API.
34556 */
34557 
34558 #if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
34559 # define osIsNT()  (1)
34560 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
34561 # define osIsNT()  (1)
34562 #elif !defined(SQLITE_WIN32_HAS_WIDE)
34563 # define osIsNT()  (0)
34564 #else
34565 # define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
34566 #endif
34567 
34568 /*
34569 ** This function determines if the machine is running a version of Windows
34570 ** based on the NT kernel.
34571 */
34572 SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void){
34573 #if SQLITE_OS_WINRT
34574   /*
34575   ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
34576   **       kernel.
34577   */
34578   return 1;
34579 #elif defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
34580   if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
34581 #if defined(SQLITE_WIN32_HAS_ANSI)
34582     OSVERSIONINFOA sInfo;
34583     sInfo.dwOSVersionInfoSize = sizeof(sInfo);
34584     osGetVersionExA(&sInfo);
34585     osInterlockedCompareExchange(&sqlite3_os_type,
34586         (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
34587 #elif defined(SQLITE_WIN32_HAS_WIDE)
34588     OSVERSIONINFOW sInfo;
34589     sInfo.dwOSVersionInfoSize = sizeof(sInfo);
34590     osGetVersionExW(&sInfo);
34591     osInterlockedCompareExchange(&sqlite3_os_type,
34592         (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
34593 #endif
34594   }
34595   return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
34596 #elif SQLITE_TEST
34597   return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
34598 #else
34599   /*
34600   ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
34601   **       deprecated are always assumed to be based on the NT kernel.
34602   */
34603   return 1;
34604 #endif
34605 }
34606 
34607 #ifdef SQLITE_WIN32_MALLOC
34608 /*
34609 ** Allocate nBytes of memory.
34610 */
34611 static void *winMemMalloc(int nBytes){
34612   HANDLE hHeap;
34613   void *p;
34614 
34615   winMemAssertMagic();
34616   hHeap = winMemGetHeap();
34617   assert( hHeap!=0 );
34618   assert( hHeap!=INVALID_HANDLE_VALUE );
34619 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34620   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34621 #endif
34622   assert( nBytes>=0 );
34623   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
34624   if( !p ){
34625     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
34626                 nBytes, osGetLastError(), (void*)hHeap);
34627   }
34628   return p;
34629 }
34630 
34631 /*
34632 ** Free memory.
34633 */
34634 static void winMemFree(void *pPrior){
34635   HANDLE hHeap;
34636 
34637   winMemAssertMagic();
34638   hHeap = winMemGetHeap();
34639   assert( hHeap!=0 );
34640   assert( hHeap!=INVALID_HANDLE_VALUE );
34641 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34642   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
34643 #endif
34644   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
34645   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
34646     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
34647                 pPrior, osGetLastError(), (void*)hHeap);
34648   }
34649 }
34650 
34651 /*
34652 ** Change the size of an existing memory allocation
34653 */
34654 static void *winMemRealloc(void *pPrior, int nBytes){
34655   HANDLE hHeap;
34656   void *p;
34657 
34658   winMemAssertMagic();
34659   hHeap = winMemGetHeap();
34660   assert( hHeap!=0 );
34661   assert( hHeap!=INVALID_HANDLE_VALUE );
34662 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34663   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
34664 #endif
34665   assert( nBytes>=0 );
34666   if( !pPrior ){
34667     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
34668   }else{
34669     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
34670   }
34671   if( !p ){
34672     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
34673                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
34674                 (void*)hHeap);
34675   }
34676   return p;
34677 }
34678 
34679 /*
34680 ** Return the size of an outstanding allocation, in bytes.
34681 */
34682 static int winMemSize(void *p){
34683   HANDLE hHeap;
34684   SIZE_T n;
34685 
34686   winMemAssertMagic();
34687   hHeap = winMemGetHeap();
34688   assert( hHeap!=0 );
34689   assert( hHeap!=INVALID_HANDLE_VALUE );
34690 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34691   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
34692 #endif
34693   if( !p ) return 0;
34694   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
34695   if( n==(SIZE_T)-1 ){
34696     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
34697                 p, osGetLastError(), (void*)hHeap);
34698     return 0;
34699   }
34700   return (int)n;
34701 }
34702 
34703 /*
34704 ** Round up a request size to the next valid allocation size.
34705 */
34706 static int winMemRoundup(int n){
34707   return n;
34708 }
34709 
34710 /*
34711 ** Initialize this module.
34712 */
34713 static int winMemInit(void *pAppData){
34714   winMemData *pWinMemData = (winMemData *)pAppData;
34715 
34716   if( !pWinMemData ) return SQLITE_ERROR;
34717   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
34718   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
34719 
34720 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
34721   if( !pWinMemData->hHeap ){
34722     DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
34723     DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
34724     if( dwMaximumSize==0 ){
34725       dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
34726     }else if( dwInitialSize>dwMaximumSize ){
34727       dwInitialSize = dwMaximumSize;
34728     }
34729     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
34730                                       dwInitialSize, dwMaximumSize);
34731     if( !pWinMemData->hHeap ){
34732       sqlite3_log(SQLITE_NOMEM,
34733           "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
34734           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
34735           dwMaximumSize);
34736       return SQLITE_NOMEM;
34737     }
34738     pWinMemData->bOwned = TRUE;
34739     assert( pWinMemData->bOwned );
34740   }
34741 #else
34742   pWinMemData->hHeap = osGetProcessHeap();
34743   if( !pWinMemData->hHeap ){
34744     sqlite3_log(SQLITE_NOMEM,
34745         "failed to GetProcessHeap (%lu)", osGetLastError());
34746     return SQLITE_NOMEM;
34747   }
34748   pWinMemData->bOwned = FALSE;
34749   assert( !pWinMemData->bOwned );
34750 #endif
34751   assert( pWinMemData->hHeap!=0 );
34752   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
34753 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34754   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34755 #endif
34756   return SQLITE_OK;
34757 }
34758 
34759 /*
34760 ** Deinitialize this module.
34761 */
34762 static void winMemShutdown(void *pAppData){
34763   winMemData *pWinMemData = (winMemData *)pAppData;
34764 
34765   if( !pWinMemData ) return;
34766   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
34767   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
34768 
34769   if( pWinMemData->hHeap ){
34770     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
34771 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34772     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34773 #endif
34774     if( pWinMemData->bOwned ){
34775       if( !osHeapDestroy(pWinMemData->hHeap) ){
34776         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
34777                     osGetLastError(), (void*)pWinMemData->hHeap);
34778       }
34779       pWinMemData->bOwned = FALSE;
34780     }
34781     pWinMemData->hHeap = NULL;
34782   }
34783 }
34784 
34785 /*
34786 ** Populate the low-level memory allocation function pointers in
34787 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
34788 ** arguments specify the block of memory to manage.
34789 **
34790 ** This routine is only called by sqlite3_config(), and therefore
34791 ** is not required to be threadsafe (it is not).
34792 */
34793 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
34794   static const sqlite3_mem_methods winMemMethods = {
34795     winMemMalloc,
34796     winMemFree,
34797     winMemRealloc,
34798     winMemSize,
34799     winMemRoundup,
34800     winMemInit,
34801     winMemShutdown,
34802     &win_mem_data
34803   };
34804   return &winMemMethods;
34805 }
34806 
34807 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
34808   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
34809 }
34810 #endif /* SQLITE_WIN32_MALLOC */
34811 
34812 /*
34813 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
34814 **
34815 ** Space to hold the returned string is obtained from malloc.
34816 */
34817 static LPWSTR winUtf8ToUnicode(const char *zFilename){
34818   int nChar;
34819   LPWSTR zWideFilename;
34820 
34821   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
34822   if( nChar==0 ){
34823     return 0;
34824   }
34825   zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
34826   if( zWideFilename==0 ){
34827     return 0;
34828   }
34829   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
34830                                 nChar);
34831   if( nChar==0 ){
34832     sqlite3_free(zWideFilename);
34833     zWideFilename = 0;
34834   }
34835   return zWideFilename;
34836 }
34837 
34838 /*
34839 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
34840 ** obtained from sqlite3_malloc().
34841 */
34842 static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
34843   int nByte;
34844   char *zFilename;
34845 
34846   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
34847   if( nByte == 0 ){
34848     return 0;
34849   }
34850   zFilename = sqlite3MallocZero( nByte );
34851   if( zFilename==0 ){
34852     return 0;
34853   }
34854   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
34855                                 0, 0);
34856   if( nByte == 0 ){
34857     sqlite3_free(zFilename);
34858     zFilename = 0;
34859   }
34860   return zFilename;
34861 }
34862 
34863 /*
34864 ** Convert an ANSI string to Microsoft Unicode, based on the
34865 ** current codepage settings for file apis.
34866 **
34867 ** Space to hold the returned string is obtained
34868 ** from sqlite3_malloc.
34869 */
34870 static LPWSTR winMbcsToUnicode(const char *zFilename){
34871   int nByte;
34872   LPWSTR zMbcsFilename;
34873   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
34874 
34875   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
34876                                 0)*sizeof(WCHAR);
34877   if( nByte==0 ){
34878     return 0;
34879   }
34880   zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
34881   if( zMbcsFilename==0 ){
34882     return 0;
34883   }
34884   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
34885                                 nByte);
34886   if( nByte==0 ){
34887     sqlite3_free(zMbcsFilename);
34888     zMbcsFilename = 0;
34889   }
34890   return zMbcsFilename;
34891 }
34892 
34893 /*
34894 ** Convert Microsoft Unicode to multi-byte character string, based on the
34895 ** user's ANSI codepage.
34896 **
34897 ** Space to hold the returned string is obtained from
34898 ** sqlite3_malloc().
34899 */
34900 static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
34901   int nByte;
34902   char *zFilename;
34903   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
34904 
34905   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
34906   if( nByte == 0 ){
34907     return 0;
34908   }
34909   zFilename = sqlite3MallocZero( nByte );
34910   if( zFilename==0 ){
34911     return 0;
34912   }
34913   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
34914                                 nByte, 0, 0);
34915   if( nByte == 0 ){
34916     sqlite3_free(zFilename);
34917     zFilename = 0;
34918   }
34919   return zFilename;
34920 }
34921 
34922 /*
34923 ** Convert multibyte character string to UTF-8.  Space to hold the
34924 ** returned string is obtained from sqlite3_malloc().
34925 */
34926 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8(const char *zFilename){
34927   char *zFilenameUtf8;
34928   LPWSTR zTmpWide;
34929 
34930   zTmpWide = winMbcsToUnicode(zFilename);
34931   if( zTmpWide==0 ){
34932     return 0;
34933   }
34934   zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
34935   sqlite3_free(zTmpWide);
34936   return zFilenameUtf8;
34937 }
34938 
34939 /*
34940 ** Convert UTF-8 to multibyte character string.  Space to hold the
34941 ** returned string is obtained from sqlite3_malloc().
34942 */
34943 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs(const char *zFilename){
34944   char *zFilenameMbcs;
34945   LPWSTR zTmpWide;
34946 
34947   zTmpWide = winUtf8ToUnicode(zFilename);
34948   if( zTmpWide==0 ){
34949     return 0;
34950   }
34951   zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
34952   sqlite3_free(zTmpWide);
34953   return zFilenameMbcs;
34954 }
34955 
34956 /*
34957 ** This function sets the data directory or the temporary directory based on
34958 ** the provided arguments.  The type argument must be 1 in order to set the
34959 ** data directory or 2 in order to set the temporary directory.  The zValue
34960 ** argument is the name of the directory to use.  The return value will be
34961 ** SQLITE_OK if successful.
34962 */
34963 SQLITE_API int SQLITE_STDCALL sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
34964   char **ppDirectory = 0;
34965 #ifndef SQLITE_OMIT_AUTOINIT
34966   int rc = sqlite3_initialize();
34967   if( rc ) return rc;
34968 #endif
34969   if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
34970     ppDirectory = &sqlite3_data_directory;
34971   }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
34972     ppDirectory = &sqlite3_temp_directory;
34973   }
34974   assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
34975           || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
34976   );
34977   assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
34978   if( ppDirectory ){
34979     char *zValueUtf8 = 0;
34980     if( zValue && zValue[0] ){
34981       zValueUtf8 = winUnicodeToUtf8(zValue);
34982       if ( zValueUtf8==0 ){
34983         return SQLITE_NOMEM;
34984       }
34985     }
34986     sqlite3_free(*ppDirectory);
34987     *ppDirectory = zValueUtf8;
34988     return SQLITE_OK;
34989   }
34990   return SQLITE_ERROR;
34991 }
34992 
34993 /*
34994 ** The return value of winGetLastErrorMsg
34995 ** is zero if the error message fits in the buffer, or non-zero
34996 ** otherwise (if the message was truncated).
34997 */
34998 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
34999   /* FormatMessage returns 0 on failure.  Otherwise it
35000   ** returns the number of TCHARs written to the output
35001   ** buffer, excluding the terminating null char.
35002   */
35003   DWORD dwLen = 0;
35004   char *zOut = 0;
35005 
35006   if( osIsNT() ){
35007 #if SQLITE_OS_WINRT
35008     WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
35009     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
35010                              FORMAT_MESSAGE_IGNORE_INSERTS,
35011                              NULL,
35012                              lastErrno,
35013                              0,
35014                              zTempWide,
35015                              SQLITE_WIN32_MAX_ERRMSG_CHARS,
35016                              0);
35017 #else
35018     LPWSTR zTempWide = NULL;
35019     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
35020                              FORMAT_MESSAGE_FROM_SYSTEM |
35021                              FORMAT_MESSAGE_IGNORE_INSERTS,
35022                              NULL,
35023                              lastErrno,
35024                              0,
35025                              (LPWSTR) &zTempWide,
35026                              0,
35027                              0);
35028 #endif
35029     if( dwLen > 0 ){
35030       /* allocate a buffer and convert to UTF8 */
35031       sqlite3BeginBenignMalloc();
35032       zOut = winUnicodeToUtf8(zTempWide);
35033       sqlite3EndBenignMalloc();
35034 #if !SQLITE_OS_WINRT
35035       /* free the system buffer allocated by FormatMessage */
35036       osLocalFree(zTempWide);
35037 #endif
35038     }
35039   }
35040 #ifdef SQLITE_WIN32_HAS_ANSI
35041   else{
35042     char *zTemp = NULL;
35043     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
35044                              FORMAT_MESSAGE_FROM_SYSTEM |
35045                              FORMAT_MESSAGE_IGNORE_INSERTS,
35046                              NULL,
35047                              lastErrno,
35048                              0,
35049                              (LPSTR) &zTemp,
35050                              0,
35051                              0);
35052     if( dwLen > 0 ){
35053       /* allocate a buffer and convert to UTF8 */
35054       sqlite3BeginBenignMalloc();
35055       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
35056       sqlite3EndBenignMalloc();
35057       /* free the system buffer allocated by FormatMessage */
35058       osLocalFree(zTemp);
35059     }
35060   }
35061 #endif
35062   if( 0 == dwLen ){
35063     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
35064   }else{
35065     /* copy a maximum of nBuf chars to output buffer */
35066     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
35067     /* free the UTF8 buffer */
35068     sqlite3_free(zOut);
35069   }
35070   return 0;
35071 }
35072 
35073 /*
35074 **
35075 ** This function - winLogErrorAtLine() - is only ever called via the macro
35076 ** winLogError().
35077 **
35078 ** This routine is invoked after an error occurs in an OS function.
35079 ** It logs a message using sqlite3_log() containing the current value of
35080 ** error code and, if possible, the human-readable equivalent from
35081 ** FormatMessage.
35082 **
35083 ** The first argument passed to the macro should be the error code that
35084 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
35085 ** The two subsequent arguments should be the name of the OS function that
35086 ** failed and the associated file-system path, if any.
35087 */
35088 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
35089 static int winLogErrorAtLine(
35090   int errcode,                    /* SQLite error code */
35091   DWORD lastErrno,                /* Win32 last error */
35092   const char *zFunc,              /* Name of OS function that failed */
35093   const char *zPath,              /* File path associated with error */
35094   int iLine                       /* Source line number where error occurred */
35095 ){
35096   char zMsg[500];                 /* Human readable error text */
35097   int i;                          /* Loop counter */
35098 
35099   zMsg[0] = 0;
35100   winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
35101   assert( errcode!=SQLITE_OK );
35102   if( zPath==0 ) zPath = "";
35103   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
35104   zMsg[i] = 0;
35105   sqlite3_log(errcode,
35106       "os_win.c:%d: (%lu) %s(%s) - %s",
35107       iLine, lastErrno, zFunc, zPath, zMsg
35108   );
35109 
35110   return errcode;
35111 }
35112 
35113 /*
35114 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
35115 ** will be retried following a locking error - probably caused by
35116 ** antivirus software.  Also the initial delay before the first retry.
35117 ** The delay increases linearly with each retry.
35118 */
35119 #ifndef SQLITE_WIN32_IOERR_RETRY
35120 # define SQLITE_WIN32_IOERR_RETRY 10
35121 #endif
35122 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
35123 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
35124 #endif
35125 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
35126 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
35127 
35128 /*
35129 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
35130 ** error code obtained via GetLastError() is eligible to be retried.  It
35131 ** must accept the error code DWORD as its only argument and should return
35132 ** non-zero if the error code is transient in nature and the operation
35133 ** responsible for generating the original error might succeed upon being
35134 ** retried.  The argument to this macro should be a variable.
35135 **
35136 ** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
35137 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
35138 ** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
35139 ** may be used to include additional error codes in the set that should
35140 ** result in the failing I/O operation being retried by the caller.  If
35141 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
35142 ** identical to those of the "winIoerrCanRetry1" macro.
35143 */
35144 #if !defined(winIoerrCanRetry1)
35145 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
35146                               ((a)==ERROR_SHARING_VIOLATION)    || \
35147                               ((a)==ERROR_LOCK_VIOLATION)       || \
35148                               ((a)==ERROR_DEV_NOT_EXIST)        || \
35149                               ((a)==ERROR_NETNAME_DELETED)      || \
35150                               ((a)==ERROR_SEM_TIMEOUT)          || \
35151                               ((a)==ERROR_NETWORK_UNREACHABLE))
35152 #endif
35153 
35154 /*
35155 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
35156 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
35157 ** to give up with an error.
35158 */
35159 static int winRetryIoerr(int *pnRetry, DWORD *pError){
35160   DWORD e = osGetLastError();
35161   if( *pnRetry>=winIoerrRetry ){
35162     if( pError ){
35163       *pError = e;
35164     }
35165     return 0;
35166   }
35167   if( winIoerrCanRetry1(e) ){
35168     sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
35169     ++*pnRetry;
35170     return 1;
35171   }
35172 #if defined(winIoerrCanRetry2)
35173   else if( winIoerrCanRetry2(e) ){
35174     sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
35175     ++*pnRetry;
35176     return 1;
35177   }
35178 #endif
35179   if( pError ){
35180     *pError = e;
35181   }
35182   return 0;
35183 }
35184 
35185 /*
35186 ** Log a I/O error retry episode.
35187 */
35188 static void winLogIoerr(int nRetry, int lineno){
35189   if( nRetry ){
35190     sqlite3_log(SQLITE_NOTICE,
35191       "delayed %dms for lock/sharing conflict at line %d",
35192       winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
35193     );
35194   }
35195 }
35196 
35197 #if SQLITE_OS_WINCE
35198 /*************************************************************************
35199 ** This section contains code for WinCE only.
35200 */
35201 #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
35202 /*
35203 ** The MSVC CRT on Windows CE may not have a localtime() function.  So
35204 ** create a substitute.
35205 */
35206 /* #include <time.h> */
35207 struct tm *__cdecl localtime(const time_t *t)
35208 {
35209   static struct tm y;
35210   FILETIME uTm, lTm;
35211   SYSTEMTIME pTm;
35212   sqlite3_int64 t64;
35213   t64 = *t;
35214   t64 = (t64 + 11644473600)*10000000;
35215   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
35216   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
35217   osFileTimeToLocalFileTime(&uTm,&lTm);
35218   osFileTimeToSystemTime(&lTm,&pTm);
35219   y.tm_year = pTm.wYear - 1900;
35220   y.tm_mon = pTm.wMonth - 1;
35221   y.tm_wday = pTm.wDayOfWeek;
35222   y.tm_mday = pTm.wDay;
35223   y.tm_hour = pTm.wHour;
35224   y.tm_min = pTm.wMinute;
35225   y.tm_sec = pTm.wSecond;
35226   return &y;
35227 }
35228 #endif
35229 
35230 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
35231 
35232 /*
35233 ** Acquire a lock on the handle h
35234 */
35235 static void winceMutexAcquire(HANDLE h){
35236    DWORD dwErr;
35237    do {
35238      dwErr = osWaitForSingleObject(h, INFINITE);
35239    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
35240 }
35241 /*
35242 ** Release a lock acquired by winceMutexAcquire()
35243 */
35244 #define winceMutexRelease(h) ReleaseMutex(h)
35245 
35246 /*
35247 ** Create the mutex and shared memory used for locking in the file
35248 ** descriptor pFile
35249 */
35250 static int winceCreateLock(const char *zFilename, winFile *pFile){
35251   LPWSTR zTok;
35252   LPWSTR zName;
35253   DWORD lastErrno;
35254   BOOL bLogged = FALSE;
35255   BOOL bInit = TRUE;
35256 
35257   zName = winUtf8ToUnicode(zFilename);
35258   if( zName==0 ){
35259     /* out of memory */
35260     return SQLITE_IOERR_NOMEM;
35261   }
35262 
35263   /* Initialize the local lockdata */
35264   memset(&pFile->local, 0, sizeof(pFile->local));
35265 
35266   /* Replace the backslashes from the filename and lowercase it
35267   ** to derive a mutex name. */
35268   zTok = osCharLowerW(zName);
35269   for (;*zTok;zTok++){
35270     if (*zTok == '\\') *zTok = '_';
35271   }
35272 
35273   /* Create/open the named mutex */
35274   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
35275   if (!pFile->hMutex){
35276     pFile->lastErrno = osGetLastError();
35277     sqlite3_free(zName);
35278     return winLogError(SQLITE_IOERR, pFile->lastErrno,
35279                        "winceCreateLock1", zFilename);
35280   }
35281 
35282   /* Acquire the mutex before continuing */
35283   winceMutexAcquire(pFile->hMutex);
35284 
35285   /* Since the names of named mutexes, semaphores, file mappings etc are
35286   ** case-sensitive, take advantage of that by uppercasing the mutex name
35287   ** and using that as the shared filemapping name.
35288   */
35289   osCharUpperW(zName);
35290   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
35291                                         PAGE_READWRITE, 0, sizeof(winceLock),
35292                                         zName);
35293 
35294   /* Set a flag that indicates we're the first to create the memory so it
35295   ** must be zero-initialized */
35296   lastErrno = osGetLastError();
35297   if (lastErrno == ERROR_ALREADY_EXISTS){
35298     bInit = FALSE;
35299   }
35300 
35301   sqlite3_free(zName);
35302 
35303   /* If we succeeded in making the shared memory handle, map it. */
35304   if( pFile->hShared ){
35305     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
35306              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
35307     /* If mapping failed, close the shared memory handle and erase it */
35308     if( !pFile->shared ){
35309       pFile->lastErrno = osGetLastError();
35310       winLogError(SQLITE_IOERR, pFile->lastErrno,
35311                   "winceCreateLock2", zFilename);
35312       bLogged = TRUE;
35313       osCloseHandle(pFile->hShared);
35314       pFile->hShared = NULL;
35315     }
35316   }
35317 
35318   /* If shared memory could not be created, then close the mutex and fail */
35319   if( pFile->hShared==NULL ){
35320     if( !bLogged ){
35321       pFile->lastErrno = lastErrno;
35322       winLogError(SQLITE_IOERR, pFile->lastErrno,
35323                   "winceCreateLock3", zFilename);
35324       bLogged = TRUE;
35325     }
35326     winceMutexRelease(pFile->hMutex);
35327     osCloseHandle(pFile->hMutex);
35328     pFile->hMutex = NULL;
35329     return SQLITE_IOERR;
35330   }
35331 
35332   /* Initialize the shared memory if we're supposed to */
35333   if( bInit ){
35334     memset(pFile->shared, 0, sizeof(winceLock));
35335   }
35336 
35337   winceMutexRelease(pFile->hMutex);
35338   return SQLITE_OK;
35339 }
35340 
35341 /*
35342 ** Destroy the part of winFile that deals with wince locks
35343 */
35344 static void winceDestroyLock(winFile *pFile){
35345   if (pFile->hMutex){
35346     /* Acquire the mutex */
35347     winceMutexAcquire(pFile->hMutex);
35348 
35349     /* The following blocks should probably assert in debug mode, but they
35350        are to cleanup in case any locks remained open */
35351     if (pFile->local.nReaders){
35352       pFile->shared->nReaders --;
35353     }
35354     if (pFile->local.bReserved){
35355       pFile->shared->bReserved = FALSE;
35356     }
35357     if (pFile->local.bPending){
35358       pFile->shared->bPending = FALSE;
35359     }
35360     if (pFile->local.bExclusive){
35361       pFile->shared->bExclusive = FALSE;
35362     }
35363 
35364     /* De-reference and close our copy of the shared memory handle */
35365     osUnmapViewOfFile(pFile->shared);
35366     osCloseHandle(pFile->hShared);
35367 
35368     /* Done with the mutex */
35369     winceMutexRelease(pFile->hMutex);
35370     osCloseHandle(pFile->hMutex);
35371     pFile->hMutex = NULL;
35372   }
35373 }
35374 
35375 /*
35376 ** An implementation of the LockFile() API of Windows for CE
35377 */
35378 static BOOL winceLockFile(
35379   LPHANDLE phFile,
35380   DWORD dwFileOffsetLow,
35381   DWORD dwFileOffsetHigh,
35382   DWORD nNumberOfBytesToLockLow,
35383   DWORD nNumberOfBytesToLockHigh
35384 ){
35385   winFile *pFile = HANDLE_TO_WINFILE(phFile);
35386   BOOL bReturn = FALSE;
35387 
35388   UNUSED_PARAMETER(dwFileOffsetHigh);
35389   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
35390 
35391   if (!pFile->hMutex) return TRUE;
35392   winceMutexAcquire(pFile->hMutex);
35393 
35394   /* Wanting an exclusive lock? */
35395   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
35396        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
35397     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
35398        pFile->shared->bExclusive = TRUE;
35399        pFile->local.bExclusive = TRUE;
35400        bReturn = TRUE;
35401     }
35402   }
35403 
35404   /* Want a read-only lock? */
35405   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
35406            nNumberOfBytesToLockLow == 1){
35407     if (pFile->shared->bExclusive == 0){
35408       pFile->local.nReaders ++;
35409       if (pFile->local.nReaders == 1){
35410         pFile->shared->nReaders ++;
35411       }
35412       bReturn = TRUE;
35413     }
35414   }
35415 
35416   /* Want a pending lock? */
35417   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
35418            && nNumberOfBytesToLockLow == 1){
35419     /* If no pending lock has been acquired, then acquire it */
35420     if (pFile->shared->bPending == 0) {
35421       pFile->shared->bPending = TRUE;
35422       pFile->local.bPending = TRUE;
35423       bReturn = TRUE;
35424     }
35425   }
35426 
35427   /* Want a reserved lock? */
35428   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
35429            && nNumberOfBytesToLockLow == 1){
35430     if (pFile->shared->bReserved == 0) {
35431       pFile->shared->bReserved = TRUE;
35432       pFile->local.bReserved = TRUE;
35433       bReturn = TRUE;
35434     }
35435   }
35436 
35437   winceMutexRelease(pFile->hMutex);
35438   return bReturn;
35439 }
35440 
35441 /*
35442 ** An implementation of the UnlockFile API of Windows for CE
35443 */
35444 static BOOL winceUnlockFile(
35445   LPHANDLE phFile,
35446   DWORD dwFileOffsetLow,
35447   DWORD dwFileOffsetHigh,
35448   DWORD nNumberOfBytesToUnlockLow,
35449   DWORD nNumberOfBytesToUnlockHigh
35450 ){
35451   winFile *pFile = HANDLE_TO_WINFILE(phFile);
35452   BOOL bReturn = FALSE;
35453 
35454   UNUSED_PARAMETER(dwFileOffsetHigh);
35455   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
35456 
35457   if (!pFile->hMutex) return TRUE;
35458   winceMutexAcquire(pFile->hMutex);
35459 
35460   /* Releasing a reader lock or an exclusive lock */
35461   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
35462     /* Did we have an exclusive lock? */
35463     if (pFile->local.bExclusive){
35464       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
35465       pFile->local.bExclusive = FALSE;
35466       pFile->shared->bExclusive = FALSE;
35467       bReturn = TRUE;
35468     }
35469 
35470     /* Did we just have a reader lock? */
35471     else if (pFile->local.nReaders){
35472       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
35473              || nNumberOfBytesToUnlockLow == 1);
35474       pFile->local.nReaders --;
35475       if (pFile->local.nReaders == 0)
35476       {
35477         pFile->shared->nReaders --;
35478       }
35479       bReturn = TRUE;
35480     }
35481   }
35482 
35483   /* Releasing a pending lock */
35484   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
35485            && nNumberOfBytesToUnlockLow == 1){
35486     if (pFile->local.bPending){
35487       pFile->local.bPending = FALSE;
35488       pFile->shared->bPending = FALSE;
35489       bReturn = TRUE;
35490     }
35491   }
35492   /* Releasing a reserved lock */
35493   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
35494            && nNumberOfBytesToUnlockLow == 1){
35495     if (pFile->local.bReserved) {
35496       pFile->local.bReserved = FALSE;
35497       pFile->shared->bReserved = FALSE;
35498       bReturn = TRUE;
35499     }
35500   }
35501 
35502   winceMutexRelease(pFile->hMutex);
35503   return bReturn;
35504 }
35505 /*
35506 ** End of the special code for wince
35507 *****************************************************************************/
35508 #endif /* SQLITE_OS_WINCE */
35509 
35510 /*
35511 ** Lock a file region.
35512 */
35513 static BOOL winLockFile(
35514   LPHANDLE phFile,
35515   DWORD flags,
35516   DWORD offsetLow,
35517   DWORD offsetHigh,
35518   DWORD numBytesLow,
35519   DWORD numBytesHigh
35520 ){
35521 #if SQLITE_OS_WINCE
35522   /*
35523   ** NOTE: Windows CE is handled differently here due its lack of the Win32
35524   **       API LockFile.
35525   */
35526   return winceLockFile(phFile, offsetLow, offsetHigh,
35527                        numBytesLow, numBytesHigh);
35528 #else
35529   if( osIsNT() ){
35530     OVERLAPPED ovlp;
35531     memset(&ovlp, 0, sizeof(OVERLAPPED));
35532     ovlp.Offset = offsetLow;
35533     ovlp.OffsetHigh = offsetHigh;
35534     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
35535   }else{
35536     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
35537                       numBytesHigh);
35538   }
35539 #endif
35540 }
35541 
35542 /*
35543 ** Unlock a file region.
35544  */
35545 static BOOL winUnlockFile(
35546   LPHANDLE phFile,
35547   DWORD offsetLow,
35548   DWORD offsetHigh,
35549   DWORD numBytesLow,
35550   DWORD numBytesHigh
35551 ){
35552 #if SQLITE_OS_WINCE
35553   /*
35554   ** NOTE: Windows CE is handled differently here due its lack of the Win32
35555   **       API UnlockFile.
35556   */
35557   return winceUnlockFile(phFile, offsetLow, offsetHigh,
35558                          numBytesLow, numBytesHigh);
35559 #else
35560   if( osIsNT() ){
35561     OVERLAPPED ovlp;
35562     memset(&ovlp, 0, sizeof(OVERLAPPED));
35563     ovlp.Offset = offsetLow;
35564     ovlp.OffsetHigh = offsetHigh;
35565     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
35566   }else{
35567     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
35568                         numBytesHigh);
35569   }
35570 #endif
35571 }
35572 
35573 /*****************************************************************************
35574 ** The next group of routines implement the I/O methods specified
35575 ** by the sqlite3_io_methods object.
35576 ******************************************************************************/
35577 
35578 /*
35579 ** Some Microsoft compilers lack this definition.
35580 */
35581 #ifndef INVALID_SET_FILE_POINTER
35582 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
35583 #endif
35584 
35585 /*
35586 ** Move the current position of the file handle passed as the first
35587 ** argument to offset iOffset within the file. If successful, return 0.
35588 ** Otherwise, set pFile->lastErrno and return non-zero.
35589 */
35590 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
35591 #if !SQLITE_OS_WINRT
35592   LONG upperBits;                 /* Most sig. 32 bits of new offset */
35593   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
35594   DWORD dwRet;                    /* Value returned by SetFilePointer() */
35595   DWORD lastErrno;                /* Value returned by GetLastError() */
35596 
35597   OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
35598 
35599   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
35600   lowerBits = (LONG)(iOffset & 0xffffffff);
35601 
35602   /* API oddity: If successful, SetFilePointer() returns a dword
35603   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
35604   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
35605   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
35606   ** whether an error has actually occurred, it is also necessary to call
35607   ** GetLastError().
35608   */
35609   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
35610 
35611   if( (dwRet==INVALID_SET_FILE_POINTER
35612       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
35613     pFile->lastErrno = lastErrno;
35614     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
35615                 "winSeekFile", pFile->zPath);
35616     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
35617     return 1;
35618   }
35619 
35620   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
35621   return 0;
35622 #else
35623   /*
35624   ** Same as above, except that this implementation works for WinRT.
35625   */
35626 
35627   LARGE_INTEGER x;                /* The new offset */
35628   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
35629 
35630   x.QuadPart = iOffset;
35631   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
35632 
35633   if(!bRet){
35634     pFile->lastErrno = osGetLastError();
35635     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
35636                 "winSeekFile", pFile->zPath);
35637     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
35638     return 1;
35639   }
35640 
35641   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
35642   return 0;
35643 #endif
35644 }
35645 
35646 #if SQLITE_MAX_MMAP_SIZE>0
35647 /* Forward references to VFS helper methods used for memory mapped files */
35648 static int winMapfile(winFile*, sqlite3_int64);
35649 static int winUnmapfile(winFile*);
35650 #endif
35651 
35652 /*
35653 ** Close a file.
35654 **
35655 ** It is reported that an attempt to close a handle might sometimes
35656 ** fail.  This is a very unreasonable result, but Windows is notorious
35657 ** for being unreasonable so I do not doubt that it might happen.  If
35658 ** the close fails, we pause for 100 milliseconds and try again.  As
35659 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
35660 ** giving up and returning an error.
35661 */
35662 #define MX_CLOSE_ATTEMPT 3
35663 static int winClose(sqlite3_file *id){
35664   int rc, cnt = 0;
35665   winFile *pFile = (winFile*)id;
35666 
35667   assert( id!=0 );
35668 #ifndef SQLITE_OMIT_WAL
35669   assert( pFile->pShm==0 );
35670 #endif
35671   assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
35672   OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
35673            osGetCurrentProcessId(), pFile, pFile->h));
35674 
35675 #if SQLITE_MAX_MMAP_SIZE>0
35676   winUnmapfile(pFile);
35677 #endif
35678 
35679   do{
35680     rc = osCloseHandle(pFile->h);
35681     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
35682   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
35683 #if SQLITE_OS_WINCE
35684 #define WINCE_DELETION_ATTEMPTS 3
35685   winceDestroyLock(pFile);
35686   if( pFile->zDeleteOnClose ){
35687     int cnt = 0;
35688     while(
35689            osDeleteFileW(pFile->zDeleteOnClose)==0
35690         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
35691         && cnt++ < WINCE_DELETION_ATTEMPTS
35692     ){
35693        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
35694     }
35695     sqlite3_free(pFile->zDeleteOnClose);
35696   }
35697 #endif
35698   if( rc ){
35699     pFile->h = NULL;
35700   }
35701   OpenCounter(-1);
35702   OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
35703            osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
35704   return rc ? SQLITE_OK
35705             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
35706                           "winClose", pFile->zPath);
35707 }
35708 
35709 /*
35710 ** Read data from a file into a buffer.  Return SQLITE_OK if all
35711 ** bytes were read successfully and SQLITE_IOERR if anything goes
35712 ** wrong.
35713 */
35714 static int winRead(
35715   sqlite3_file *id,          /* File to read from */
35716   void *pBuf,                /* Write content into this buffer */
35717   int amt,                   /* Number of bytes to read */
35718   sqlite3_int64 offset       /* Begin reading at this offset */
35719 ){
35720 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
35721   OVERLAPPED overlapped;          /* The offset for ReadFile. */
35722 #endif
35723   winFile *pFile = (winFile*)id;  /* file handle */
35724   DWORD nRead;                    /* Number of bytes actually read from file */
35725   int nRetry = 0;                 /* Number of retrys */
35726 
35727   assert( id!=0 );
35728   assert( amt>0 );
35729   assert( offset>=0 );
35730   SimulateIOError(return SQLITE_IOERR_READ);
35731   OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
35732            "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
35733            pFile->h, pBuf, amt, offset, pFile->locktype));
35734 
35735 #if SQLITE_MAX_MMAP_SIZE>0
35736   /* Deal with as much of this read request as possible by transfering
35737   ** data from the memory mapping using memcpy().  */
35738   if( offset<pFile->mmapSize ){
35739     if( offset+amt <= pFile->mmapSize ){
35740       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
35741       OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
35742                osGetCurrentProcessId(), pFile, pFile->h));
35743       return SQLITE_OK;
35744     }else{
35745       int nCopy = (int)(pFile->mmapSize - offset);
35746       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
35747       pBuf = &((u8 *)pBuf)[nCopy];
35748       amt -= nCopy;
35749       offset += nCopy;
35750     }
35751   }
35752 #endif
35753 
35754 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
35755   if( winSeekFile(pFile, offset) ){
35756     OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
35757              osGetCurrentProcessId(), pFile, pFile->h));
35758     return SQLITE_FULL;
35759   }
35760   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
35761 #else
35762   memset(&overlapped, 0, sizeof(OVERLAPPED));
35763   overlapped.Offset = (LONG)(offset & 0xffffffff);
35764   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
35765   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
35766          osGetLastError()!=ERROR_HANDLE_EOF ){
35767 #endif
35768     DWORD lastErrno;
35769     if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
35770     pFile->lastErrno = lastErrno;
35771     OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
35772              osGetCurrentProcessId(), pFile, pFile->h));
35773     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
35774                        "winRead", pFile->zPath);
35775   }
35776   winLogIoerr(nRetry, __LINE__);
35777   if( nRead<(DWORD)amt ){
35778     /* Unread parts of the buffer must be zero-filled */
35779     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
35780     OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
35781              osGetCurrentProcessId(), pFile, pFile->h));
35782     return SQLITE_IOERR_SHORT_READ;
35783   }
35784 
35785   OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
35786            osGetCurrentProcessId(), pFile, pFile->h));
35787   return SQLITE_OK;
35788 }
35789 
35790 /*
35791 ** Write data from a buffer into a file.  Return SQLITE_OK on success
35792 ** or some other error code on failure.
35793 */
35794 static int winWrite(
35795   sqlite3_file *id,               /* File to write into */
35796   const void *pBuf,               /* The bytes to be written */
35797   int amt,                        /* Number of bytes to write */
35798   sqlite3_int64 offset            /* Offset into the file to begin writing at */
35799 ){
35800   int rc = 0;                     /* True if error has occurred, else false */
35801   winFile *pFile = (winFile*)id;  /* File handle */
35802   int nRetry = 0;                 /* Number of retries */
35803 
35804   assert( amt>0 );
35805   assert( pFile );
35806   SimulateIOError(return SQLITE_IOERR_WRITE);
35807   SimulateDiskfullError(return SQLITE_FULL);
35808 
35809   OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
35810            "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
35811            pFile->h, pBuf, amt, offset, pFile->locktype));
35812 
35813 #if SQLITE_MAX_MMAP_SIZE>0
35814   /* Deal with as much of this write request as possible by transfering
35815   ** data from the memory mapping using memcpy().  */
35816   if( offset<pFile->mmapSize ){
35817     if( offset+amt <= pFile->mmapSize ){
35818       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
35819       OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
35820                osGetCurrentProcessId(), pFile, pFile->h));
35821       return SQLITE_OK;
35822     }else{
35823       int nCopy = (int)(pFile->mmapSize - offset);
35824       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
35825       pBuf = &((u8 *)pBuf)[nCopy];
35826       amt -= nCopy;
35827       offset += nCopy;
35828     }
35829   }
35830 #endif
35831 
35832 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
35833   rc = winSeekFile(pFile, offset);
35834   if( rc==0 ){
35835 #else
35836   {
35837 #endif
35838 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
35839     OVERLAPPED overlapped;        /* The offset for WriteFile. */
35840 #endif
35841     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
35842     int nRem = amt;               /* Number of bytes yet to be written */
35843     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
35844     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
35845 
35846 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
35847     memset(&overlapped, 0, sizeof(OVERLAPPED));
35848     overlapped.Offset = (LONG)(offset & 0xffffffff);
35849     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
35850 #endif
35851 
35852     while( nRem>0 ){
35853 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
35854       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
35855 #else
35856       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
35857 #endif
35858         if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
35859         break;
35860       }
35861       assert( nWrite==0 || nWrite<=(DWORD)nRem );
35862       if( nWrite==0 || nWrite>(DWORD)nRem ){
35863         lastErrno = osGetLastError();
35864         break;
35865       }
35866 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
35867       offset += nWrite;
35868       overlapped.Offset = (LONG)(offset & 0xffffffff);
35869       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
35870 #endif
35871       aRem += nWrite;
35872       nRem -= nWrite;
35873     }
35874     if( nRem>0 ){
35875       pFile->lastErrno = lastErrno;
35876       rc = 1;
35877     }
35878   }
35879 
35880   if( rc ){
35881     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
35882        || ( pFile->lastErrno==ERROR_DISK_FULL )){
35883       OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
35884                osGetCurrentProcessId(), pFile, pFile->h));
35885       return winLogError(SQLITE_FULL, pFile->lastErrno,
35886                          "winWrite1", pFile->zPath);
35887     }
35888     OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
35889              osGetCurrentProcessId(), pFile, pFile->h));
35890     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
35891                        "winWrite2", pFile->zPath);
35892   }else{
35893     winLogIoerr(nRetry, __LINE__);
35894   }
35895   OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
35896            osGetCurrentProcessId(), pFile, pFile->h));
35897   return SQLITE_OK;
35898 }
35899 
35900 /*
35901 ** Truncate an open file to a specified size
35902 */
35903 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
35904   winFile *pFile = (winFile*)id;  /* File handle object */
35905   int rc = SQLITE_OK;             /* Return code for this function */
35906   DWORD lastErrno;
35907 
35908   assert( pFile );
35909   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
35910   OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
35911            osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
35912 
35913   /* If the user has configured a chunk-size for this file, truncate the
35914   ** file so that it consists of an integer number of chunks (i.e. the
35915   ** actual file size after the operation may be larger than the requested
35916   ** size).
35917   */
35918   if( pFile->szChunk>0 ){
35919     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
35920   }
35921 
35922   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
35923   if( winSeekFile(pFile, nByte) ){
35924     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
35925                      "winTruncate1", pFile->zPath);
35926   }else if( 0==osSetEndOfFile(pFile->h) &&
35927             ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
35928     pFile->lastErrno = lastErrno;
35929     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
35930                      "winTruncate2", pFile->zPath);
35931   }
35932 
35933 #if SQLITE_MAX_MMAP_SIZE>0
35934   /* If the file was truncated to a size smaller than the currently
35935   ** mapped region, reduce the effective mapping size as well. SQLite will
35936   ** use read() and write() to access data beyond this point from now on.
35937   */
35938   if( pFile->pMapRegion && nByte<pFile->mmapSize ){
35939     pFile->mmapSize = nByte;
35940   }
35941 #endif
35942 
35943   OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
35944            osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
35945   return rc;
35946 }
35947 
35948 #ifdef SQLITE_TEST
35949 /*
35950 ** Count the number of fullsyncs and normal syncs.  This is used to test
35951 ** that syncs and fullsyncs are occuring at the right times.
35952 */
35953 SQLITE_API int sqlite3_sync_count = 0;
35954 SQLITE_API int sqlite3_fullsync_count = 0;
35955 #endif
35956 
35957 /*
35958 ** Make sure all writes to a particular file are committed to disk.
35959 */
35960 static int winSync(sqlite3_file *id, int flags){
35961 #ifndef SQLITE_NO_SYNC
35962   /*
35963   ** Used only when SQLITE_NO_SYNC is not defined.
35964    */
35965   BOOL rc;
35966 #endif
35967 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
35968     defined(SQLITE_HAVE_OS_TRACE)
35969   /*
35970   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
35971   ** OSTRACE() macros.
35972    */
35973   winFile *pFile = (winFile*)id;
35974 #else
35975   UNUSED_PARAMETER(id);
35976 #endif
35977 
35978   assert( pFile );
35979   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
35980   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
35981       || (flags&0x0F)==SQLITE_SYNC_FULL
35982   );
35983 
35984   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
35985   ** line is to test that doing so does not cause any problems.
35986   */
35987   SimulateDiskfullError( return SQLITE_FULL );
35988 
35989   OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
35990            osGetCurrentProcessId(), pFile, pFile->h, flags,
35991            pFile->locktype));
35992 
35993 #ifndef SQLITE_TEST
35994   UNUSED_PARAMETER(flags);
35995 #else
35996   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
35997     sqlite3_fullsync_count++;
35998   }
35999   sqlite3_sync_count++;
36000 #endif
36001 
36002   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
36003   ** no-op
36004   */
36005 #ifdef SQLITE_NO_SYNC
36006   OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
36007            osGetCurrentProcessId(), pFile, pFile->h));
36008   return SQLITE_OK;
36009 #else
36010 #if SQLITE_MAX_MMAP_SIZE>0
36011   if( pFile->pMapRegion ){
36012     if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
36013       OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
36014                "rc=SQLITE_OK\n", osGetCurrentProcessId(),
36015                pFile, pFile->pMapRegion));
36016     }else{
36017       pFile->lastErrno = osGetLastError();
36018       OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
36019                "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
36020                pFile, pFile->pMapRegion));
36021       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
36022                          "winSync1", pFile->zPath);
36023     }
36024   }
36025 #endif
36026   rc = osFlushFileBuffers(pFile->h);
36027   SimulateIOError( rc=FALSE );
36028   if( rc ){
36029     OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
36030              osGetCurrentProcessId(), pFile, pFile->h));
36031     return SQLITE_OK;
36032   }else{
36033     pFile->lastErrno = osGetLastError();
36034     OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
36035              osGetCurrentProcessId(), pFile, pFile->h));
36036     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
36037                        "winSync2", pFile->zPath);
36038   }
36039 #endif
36040 }
36041 
36042 /*
36043 ** Determine the current size of a file in bytes
36044 */
36045 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
36046   winFile *pFile = (winFile*)id;
36047   int rc = SQLITE_OK;
36048 
36049   assert( id!=0 );
36050   assert( pSize!=0 );
36051   SimulateIOError(return SQLITE_IOERR_FSTAT);
36052   OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
36053 
36054 #if SQLITE_OS_WINRT
36055   {
36056     FILE_STANDARD_INFO info;
36057     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
36058                                      &info, sizeof(info)) ){
36059       *pSize = info.EndOfFile.QuadPart;
36060     }else{
36061       pFile->lastErrno = osGetLastError();
36062       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
36063                        "winFileSize", pFile->zPath);
36064     }
36065   }
36066 #else
36067   {
36068     DWORD upperBits;
36069     DWORD lowerBits;
36070     DWORD lastErrno;
36071 
36072     lowerBits = osGetFileSize(pFile->h, &upperBits);
36073     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
36074     if(   (lowerBits == INVALID_FILE_SIZE)
36075        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
36076       pFile->lastErrno = lastErrno;
36077       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
36078                        "winFileSize", pFile->zPath);
36079     }
36080   }
36081 #endif
36082   OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
36083            pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
36084   return rc;
36085 }
36086 
36087 /*
36088 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
36089 */
36090 #ifndef LOCKFILE_FAIL_IMMEDIATELY
36091 # define LOCKFILE_FAIL_IMMEDIATELY 1
36092 #endif
36093 
36094 #ifndef LOCKFILE_EXCLUSIVE_LOCK
36095 # define LOCKFILE_EXCLUSIVE_LOCK 2
36096 #endif
36097 
36098 /*
36099 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
36100 ** When the LockFile function was used, it was always expected to fail
36101 ** immediately if the lock could not be obtained.  Also, it always expected to
36102 ** obtain an exclusive lock.  These flags are used with the LockFileEx function
36103 ** and reflect those expectations; therefore, they should not be changed.
36104 */
36105 #ifndef SQLITE_LOCKFILE_FLAGS
36106 # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
36107                                   LOCKFILE_EXCLUSIVE_LOCK)
36108 #endif
36109 
36110 /*
36111 ** Currently, SQLite never calls the LockFileEx function without wanting the
36112 ** call to fail immediately if the lock cannot be obtained.
36113 */
36114 #ifndef SQLITE_LOCKFILEEX_FLAGS
36115 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
36116 #endif
36117 
36118 /*
36119 ** Acquire a reader lock.
36120 ** Different API routines are called depending on whether or not this
36121 ** is Win9x or WinNT.
36122 */
36123 static int winGetReadLock(winFile *pFile){
36124   int res;
36125   OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
36126   if( osIsNT() ){
36127 #if SQLITE_OS_WINCE
36128     /*
36129     ** NOTE: Windows CE is handled differently here due its lack of the Win32
36130     **       API LockFileEx.
36131     */
36132     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
36133 #else
36134     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
36135                       SHARED_SIZE, 0);
36136 #endif
36137   }
36138 #ifdef SQLITE_WIN32_HAS_ANSI
36139   else{
36140     int lk;
36141     sqlite3_randomness(sizeof(lk), &lk);
36142     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
36143     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
36144                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
36145   }
36146 #endif
36147   if( res == 0 ){
36148     pFile->lastErrno = osGetLastError();
36149     /* No need to log a failure to lock */
36150   }
36151   OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
36152   return res;
36153 }
36154 
36155 /*
36156 ** Undo a readlock
36157 */
36158 static int winUnlockReadLock(winFile *pFile){
36159   int res;
36160   DWORD lastErrno;
36161   OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
36162   if( osIsNT() ){
36163     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
36164   }
36165 #ifdef SQLITE_WIN32_HAS_ANSI
36166   else{
36167     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
36168   }
36169 #endif
36170   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
36171     pFile->lastErrno = lastErrno;
36172     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
36173                 "winUnlockReadLock", pFile->zPath);
36174   }
36175   OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
36176   return res;
36177 }
36178 
36179 /*
36180 ** Lock the file with the lock specified by parameter locktype - one
36181 ** of the following:
36182 **
36183 **     (1) SHARED_LOCK
36184 **     (2) RESERVED_LOCK
36185 **     (3) PENDING_LOCK
36186 **     (4) EXCLUSIVE_LOCK
36187 **
36188 ** Sometimes when requesting one lock state, additional lock states
36189 ** are inserted in between.  The locking might fail on one of the later
36190 ** transitions leaving the lock state different from what it started but
36191 ** still short of its goal.  The following chart shows the allowed
36192 ** transitions and the inserted intermediate states:
36193 **
36194 **    UNLOCKED -> SHARED
36195 **    SHARED -> RESERVED
36196 **    SHARED -> (PENDING) -> EXCLUSIVE
36197 **    RESERVED -> (PENDING) -> EXCLUSIVE
36198 **    PENDING -> EXCLUSIVE
36199 **
36200 ** This routine will only increase a lock.  The winUnlock() routine
36201 ** erases all locks at once and returns us immediately to locking level 0.
36202 ** It is not possible to lower the locking level one step at a time.  You
36203 ** must go straight to locking level 0.
36204 */
36205 static int winLock(sqlite3_file *id, int locktype){
36206   int rc = SQLITE_OK;    /* Return code from subroutines */
36207   int res = 1;           /* Result of a Windows lock call */
36208   int newLocktype;       /* Set pFile->locktype to this value before exiting */
36209   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
36210   winFile *pFile = (winFile*)id;
36211   DWORD lastErrno = NO_ERROR;
36212 
36213   assert( id!=0 );
36214   OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
36215            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
36216 
36217   /* If there is already a lock of this type or more restrictive on the
36218   ** OsFile, do nothing. Don't use the end_lock: exit path, as
36219   ** sqlite3OsEnterMutex() hasn't been called yet.
36220   */
36221   if( pFile->locktype>=locktype ){
36222     OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
36223     return SQLITE_OK;
36224   }
36225 
36226   /* Make sure the locking sequence is correct
36227   */
36228   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
36229   assert( locktype!=PENDING_LOCK );
36230   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
36231 
36232   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
36233   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
36234   ** the PENDING_LOCK byte is temporary.
36235   */
36236   newLocktype = pFile->locktype;
36237   if(   (pFile->locktype==NO_LOCK)
36238      || (   (locktype==EXCLUSIVE_LOCK)
36239          && (pFile->locktype==RESERVED_LOCK))
36240   ){
36241     int cnt = 3;
36242     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
36243                                          PENDING_BYTE, 0, 1, 0))==0 ){
36244       /* Try 3 times to get the pending lock.  This is needed to work
36245       ** around problems caused by indexing and/or anti-virus software on
36246       ** Windows systems.
36247       ** If you are using this code as a model for alternative VFSes, do not
36248       ** copy this retry logic.  It is a hack intended for Windows only.
36249       */
36250       lastErrno = osGetLastError();
36251       OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
36252                pFile->h, cnt, res));
36253       if( lastErrno==ERROR_INVALID_HANDLE ){
36254         pFile->lastErrno = lastErrno;
36255         rc = SQLITE_IOERR_LOCK;
36256         OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
36257                  pFile->h, cnt, sqlite3ErrName(rc)));
36258         return rc;
36259       }
36260       if( cnt ) sqlite3_win32_sleep(1);
36261     }
36262     gotPendingLock = res;
36263     if( !res ){
36264       lastErrno = osGetLastError();
36265     }
36266   }
36267 
36268   /* Acquire a shared lock
36269   */
36270   if( locktype==SHARED_LOCK && res ){
36271     assert( pFile->locktype==NO_LOCK );
36272     res = winGetReadLock(pFile);
36273     if( res ){
36274       newLocktype = SHARED_LOCK;
36275     }else{
36276       lastErrno = osGetLastError();
36277     }
36278   }
36279 
36280   /* Acquire a RESERVED lock
36281   */
36282   if( locktype==RESERVED_LOCK && res ){
36283     assert( pFile->locktype==SHARED_LOCK );
36284     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
36285     if( res ){
36286       newLocktype = RESERVED_LOCK;
36287     }else{
36288       lastErrno = osGetLastError();
36289     }
36290   }
36291 
36292   /* Acquire a PENDING lock
36293   */
36294   if( locktype==EXCLUSIVE_LOCK && res ){
36295     newLocktype = PENDING_LOCK;
36296     gotPendingLock = 0;
36297   }
36298 
36299   /* Acquire an EXCLUSIVE lock
36300   */
36301   if( locktype==EXCLUSIVE_LOCK && res ){
36302     assert( pFile->locktype>=SHARED_LOCK );
36303     res = winUnlockReadLock(pFile);
36304     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
36305                       SHARED_SIZE, 0);
36306     if( res ){
36307       newLocktype = EXCLUSIVE_LOCK;
36308     }else{
36309       lastErrno = osGetLastError();
36310       winGetReadLock(pFile);
36311     }
36312   }
36313 
36314   /* If we are holding a PENDING lock that ought to be released, then
36315   ** release it now.
36316   */
36317   if( gotPendingLock && locktype==SHARED_LOCK ){
36318     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
36319   }
36320 
36321   /* Update the state of the lock has held in the file descriptor then
36322   ** return the appropriate result code.
36323   */
36324   if( res ){
36325     rc = SQLITE_OK;
36326   }else{
36327     pFile->lastErrno = lastErrno;
36328     rc = SQLITE_BUSY;
36329     OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
36330              pFile->h, locktype, newLocktype));
36331   }
36332   pFile->locktype = (u8)newLocktype;
36333   OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
36334            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
36335   return rc;
36336 }
36337 
36338 /*
36339 ** This routine checks if there is a RESERVED lock held on the specified
36340 ** file by this or any other process. If such a lock is held, return
36341 ** non-zero, otherwise zero.
36342 */
36343 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
36344   int res;
36345   winFile *pFile = (winFile*)id;
36346 
36347   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
36348   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
36349 
36350   assert( id!=0 );
36351   if( pFile->locktype>=RESERVED_LOCK ){
36352     res = 1;
36353     OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
36354   }else{
36355     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
36356     if( res ){
36357       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
36358     }
36359     res = !res;
36360     OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
36361   }
36362   *pResOut = res;
36363   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
36364            pFile->h, pResOut, *pResOut));
36365   return SQLITE_OK;
36366 }
36367 
36368 /*
36369 ** Lower the locking level on file descriptor id to locktype.  locktype
36370 ** must be either NO_LOCK or SHARED_LOCK.
36371 **
36372 ** If the locking level of the file descriptor is already at or below
36373 ** the requested locking level, this routine is a no-op.
36374 **
36375 ** It is not possible for this routine to fail if the second argument
36376 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
36377 ** might return SQLITE_IOERR;
36378 */
36379 static int winUnlock(sqlite3_file *id, int locktype){
36380   int type;
36381   winFile *pFile = (winFile*)id;
36382   int rc = SQLITE_OK;
36383   assert( pFile!=0 );
36384   assert( locktype<=SHARED_LOCK );
36385   OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
36386            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
36387   type = pFile->locktype;
36388   if( type>=EXCLUSIVE_LOCK ){
36389     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
36390     if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
36391       /* This should never happen.  We should always be able to
36392       ** reacquire the read lock */
36393       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
36394                        "winUnlock", pFile->zPath);
36395     }
36396   }
36397   if( type>=RESERVED_LOCK ){
36398     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
36399   }
36400   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
36401     winUnlockReadLock(pFile);
36402   }
36403   if( type>=PENDING_LOCK ){
36404     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
36405   }
36406   pFile->locktype = (u8)locktype;
36407   OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
36408            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
36409   return rc;
36410 }
36411 
36412 /*
36413 ** If *pArg is initially negative then this is a query.  Set *pArg to
36414 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
36415 **
36416 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
36417 */
36418 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
36419   if( *pArg<0 ){
36420     *pArg = (pFile->ctrlFlags & mask)!=0;
36421   }else if( (*pArg)==0 ){
36422     pFile->ctrlFlags &= ~mask;
36423   }else{
36424     pFile->ctrlFlags |= mask;
36425   }
36426 }
36427 
36428 /* Forward references to VFS helper methods used for temporary files */
36429 static int winGetTempname(sqlite3_vfs *, char **);
36430 static int winIsDir(const void *);
36431 static BOOL winIsDriveLetterAndColon(const char *);
36432 
36433 /*
36434 ** Control and query of the open file handle.
36435 */
36436 static int winFileControl(sqlite3_file *id, int op, void *pArg){
36437   winFile *pFile = (winFile*)id;
36438   OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
36439   switch( op ){
36440     case SQLITE_FCNTL_LOCKSTATE: {
36441       *(int*)pArg = pFile->locktype;
36442       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36443       return SQLITE_OK;
36444     }
36445     case SQLITE_LAST_ERRNO: {
36446       *(int*)pArg = (int)pFile->lastErrno;
36447       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36448       return SQLITE_OK;
36449     }
36450     case SQLITE_FCNTL_CHUNK_SIZE: {
36451       pFile->szChunk = *(int *)pArg;
36452       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36453       return SQLITE_OK;
36454     }
36455     case SQLITE_FCNTL_SIZE_HINT: {
36456       if( pFile->szChunk>0 ){
36457         sqlite3_int64 oldSz;
36458         int rc = winFileSize(id, &oldSz);
36459         if( rc==SQLITE_OK ){
36460           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
36461           if( newSz>oldSz ){
36462             SimulateIOErrorBenign(1);
36463             rc = winTruncate(id, newSz);
36464             SimulateIOErrorBenign(0);
36465           }
36466         }
36467         OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
36468         return rc;
36469       }
36470       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36471       return SQLITE_OK;
36472     }
36473     case SQLITE_FCNTL_PERSIST_WAL: {
36474       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
36475       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36476       return SQLITE_OK;
36477     }
36478     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
36479       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
36480       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36481       return SQLITE_OK;
36482     }
36483     case SQLITE_FCNTL_VFSNAME: {
36484       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
36485       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36486       return SQLITE_OK;
36487     }
36488     case SQLITE_FCNTL_WIN32_AV_RETRY: {
36489       int *a = (int*)pArg;
36490       if( a[0]>0 ){
36491         winIoerrRetry = a[0];
36492       }else{
36493         a[0] = winIoerrRetry;
36494       }
36495       if( a[1]>0 ){
36496         winIoerrRetryDelay = a[1];
36497       }else{
36498         a[1] = winIoerrRetryDelay;
36499       }
36500       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36501       return SQLITE_OK;
36502     }
36503 #ifdef SQLITE_TEST
36504     case SQLITE_FCNTL_WIN32_SET_HANDLE: {
36505       LPHANDLE phFile = (LPHANDLE)pArg;
36506       HANDLE hOldFile = pFile->h;
36507       pFile->h = *phFile;
36508       *phFile = hOldFile;
36509       OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
36510                hOldFile, pFile->h));
36511       return SQLITE_OK;
36512     }
36513 #endif
36514     case SQLITE_FCNTL_TEMPFILENAME: {
36515       char *zTFile = 0;
36516       int rc = winGetTempname(pFile->pVfs, &zTFile);
36517       if( rc==SQLITE_OK ){
36518         *(char**)pArg = zTFile;
36519       }
36520       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
36521       return rc;
36522     }
36523 #if SQLITE_MAX_MMAP_SIZE>0
36524     case SQLITE_FCNTL_MMAP_SIZE: {
36525       i64 newLimit = *(i64*)pArg;
36526       int rc = SQLITE_OK;
36527       if( newLimit>sqlite3GlobalConfig.mxMmap ){
36528         newLimit = sqlite3GlobalConfig.mxMmap;
36529       }
36530       *(i64*)pArg = pFile->mmapSizeMax;
36531       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
36532         pFile->mmapSizeMax = newLimit;
36533         if( pFile->mmapSize>0 ){
36534           winUnmapfile(pFile);
36535           rc = winMapfile(pFile, -1);
36536         }
36537       }
36538       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
36539       return rc;
36540     }
36541 #endif
36542   }
36543   OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
36544   return SQLITE_NOTFOUND;
36545 }
36546 
36547 /*
36548 ** Return the sector size in bytes of the underlying block device for
36549 ** the specified file. This is almost always 512 bytes, but may be
36550 ** larger for some devices.
36551 **
36552 ** SQLite code assumes this function cannot fail. It also assumes that
36553 ** if two files are created in the same file-system directory (i.e.
36554 ** a database and its journal file) that the sector size will be the
36555 ** same for both.
36556 */
36557 static int winSectorSize(sqlite3_file *id){
36558   (void)id;
36559   return SQLITE_DEFAULT_SECTOR_SIZE;
36560 }
36561 
36562 /*
36563 ** Return a vector of device characteristics.
36564 */
36565 static int winDeviceCharacteristics(sqlite3_file *id){
36566   winFile *p = (winFile*)id;
36567   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
36568          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
36569 }
36570 
36571 /*
36572 ** Windows will only let you create file view mappings
36573 ** on allocation size granularity boundaries.
36574 ** During sqlite3_os_init() we do a GetSystemInfo()
36575 ** to get the granularity size.
36576 */
36577 static SYSTEM_INFO winSysInfo;
36578 
36579 #ifndef SQLITE_OMIT_WAL
36580 
36581 /*
36582 ** Helper functions to obtain and relinquish the global mutex. The
36583 ** global mutex is used to protect the winLockInfo objects used by
36584 ** this file, all of which may be shared by multiple threads.
36585 **
36586 ** Function winShmMutexHeld() is used to assert() that the global mutex
36587 ** is held when required. This function is only used as part of assert()
36588 ** statements. e.g.
36589 **
36590 **   winShmEnterMutex()
36591 **     assert( winShmMutexHeld() );
36592 **   winShmLeaveMutex()
36593 */
36594 static void winShmEnterMutex(void){
36595   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
36596 }
36597 static void winShmLeaveMutex(void){
36598   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
36599 }
36600 #ifndef NDEBUG
36601 static int winShmMutexHeld(void) {
36602   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
36603 }
36604 #endif
36605 
36606 /*
36607 ** Object used to represent a single file opened and mmapped to provide
36608 ** shared memory.  When multiple threads all reference the same
36609 ** log-summary, each thread has its own winFile object, but they all
36610 ** point to a single instance of this object.  In other words, each
36611 ** log-summary is opened only once per process.
36612 **
36613 ** winShmMutexHeld() must be true when creating or destroying
36614 ** this object or while reading or writing the following fields:
36615 **
36616 **      nRef
36617 **      pNext
36618 **
36619 ** The following fields are read-only after the object is created:
36620 **
36621 **      fid
36622 **      zFilename
36623 **
36624 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
36625 ** winShmMutexHeld() is true when reading or writing any other field
36626 ** in this structure.
36627 **
36628 */
36629 struct winShmNode {
36630   sqlite3_mutex *mutex;      /* Mutex to access this object */
36631   char *zFilename;           /* Name of the file */
36632   winFile hFile;             /* File handle from winOpen */
36633 
36634   int szRegion;              /* Size of shared-memory regions */
36635   int nRegion;               /* Size of array apRegion */
36636   struct ShmRegion {
36637     HANDLE hMap;             /* File handle from CreateFileMapping */
36638     void *pMap;
36639   } *aRegion;
36640   DWORD lastErrno;           /* The Windows errno from the last I/O error */
36641 
36642   int nRef;                  /* Number of winShm objects pointing to this */
36643   winShm *pFirst;            /* All winShm objects pointing to this */
36644   winShmNode *pNext;         /* Next in list of all winShmNode objects */
36645 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
36646   u8 nextShmId;              /* Next available winShm.id value */
36647 #endif
36648 };
36649 
36650 /*
36651 ** A global array of all winShmNode objects.
36652 **
36653 ** The winShmMutexHeld() must be true while reading or writing this list.
36654 */
36655 static winShmNode *winShmNodeList = 0;
36656 
36657 /*
36658 ** Structure used internally by this VFS to record the state of an
36659 ** open shared memory connection.
36660 **
36661 ** The following fields are initialized when this object is created and
36662 ** are read-only thereafter:
36663 **
36664 **    winShm.pShmNode
36665 **    winShm.id
36666 **
36667 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
36668 ** while accessing any read/write fields.
36669 */
36670 struct winShm {
36671   winShmNode *pShmNode;      /* The underlying winShmNode object */
36672   winShm *pNext;             /* Next winShm with the same winShmNode */
36673   u8 hasMutex;               /* True if holding the winShmNode mutex */
36674   u16 sharedMask;            /* Mask of shared locks held */
36675   u16 exclMask;              /* Mask of exclusive locks held */
36676 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
36677   u8 id;                     /* Id of this connection with its winShmNode */
36678 #endif
36679 };
36680 
36681 /*
36682 ** Constants used for locking
36683 */
36684 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
36685 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
36686 
36687 /*
36688 ** Apply advisory locks for all n bytes beginning at ofst.
36689 */
36690 #define _SHM_UNLCK  1
36691 #define _SHM_RDLCK  2
36692 #define _SHM_WRLCK  3
36693 static int winShmSystemLock(
36694   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
36695   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
36696   int ofst,             /* Offset to first byte to be locked/unlocked */
36697   int nByte             /* Number of bytes to lock or unlock */
36698 ){
36699   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
36700 
36701   /* Access to the winShmNode object is serialized by the caller */
36702   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
36703 
36704   OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
36705            pFile->hFile.h, lockType, ofst, nByte));
36706 
36707   /* Release/Acquire the system-level lock */
36708   if( lockType==_SHM_UNLCK ){
36709     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
36710   }else{
36711     /* Initialize the locking parameters */
36712     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
36713     if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
36714     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
36715   }
36716 
36717   if( rc!= 0 ){
36718     rc = SQLITE_OK;
36719   }else{
36720     pFile->lastErrno =  osGetLastError();
36721     rc = SQLITE_BUSY;
36722   }
36723 
36724   OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
36725            pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
36726            "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
36727 
36728   return rc;
36729 }
36730 
36731 /* Forward references to VFS methods */
36732 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
36733 static int winDelete(sqlite3_vfs *,const char*,int);
36734 
36735 /*
36736 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
36737 **
36738 ** This is not a VFS shared-memory method; it is a utility function called
36739 ** by VFS shared-memory methods.
36740 */
36741 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
36742   winShmNode **pp;
36743   winShmNode *p;
36744   assert( winShmMutexHeld() );
36745   OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
36746            osGetCurrentProcessId(), deleteFlag));
36747   pp = &winShmNodeList;
36748   while( (p = *pp)!=0 ){
36749     if( p->nRef==0 ){
36750       int i;
36751       if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
36752       for(i=0; i<p->nRegion; i++){
36753         BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
36754         OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
36755                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
36756         UNUSED_VARIABLE_VALUE(bRc);
36757         bRc = osCloseHandle(p->aRegion[i].hMap);
36758         OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
36759                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
36760         UNUSED_VARIABLE_VALUE(bRc);
36761       }
36762       if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
36763         SimulateIOErrorBenign(1);
36764         winClose((sqlite3_file *)&p->hFile);
36765         SimulateIOErrorBenign(0);
36766       }
36767       if( deleteFlag ){
36768         SimulateIOErrorBenign(1);
36769         sqlite3BeginBenignMalloc();
36770         winDelete(pVfs, p->zFilename, 0);
36771         sqlite3EndBenignMalloc();
36772         SimulateIOErrorBenign(0);
36773       }
36774       *pp = p->pNext;
36775       sqlite3_free(p->aRegion);
36776       sqlite3_free(p);
36777     }else{
36778       pp = &p->pNext;
36779     }
36780   }
36781 }
36782 
36783 /*
36784 ** Open the shared-memory area associated with database file pDbFd.
36785 **
36786 ** When opening a new shared-memory file, if no other instances of that
36787 ** file are currently open, in this process or in other processes, then
36788 ** the file must be truncated to zero length or have its header cleared.
36789 */
36790 static int winOpenSharedMemory(winFile *pDbFd){
36791   struct winShm *p;                  /* The connection to be opened */
36792   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
36793   int rc;                            /* Result code */
36794   struct winShmNode *pNew;           /* Newly allocated winShmNode */
36795   int nName;                         /* Size of zName in bytes */
36796 
36797   assert( pDbFd->pShm==0 );    /* Not previously opened */
36798 
36799   /* Allocate space for the new sqlite3_shm object.  Also speculatively
36800   ** allocate space for a new winShmNode and filename.
36801   */
36802   p = sqlite3MallocZero( sizeof(*p) );
36803   if( p==0 ) return SQLITE_IOERR_NOMEM;
36804   nName = sqlite3Strlen30(pDbFd->zPath);
36805   pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
36806   if( pNew==0 ){
36807     sqlite3_free(p);
36808     return SQLITE_IOERR_NOMEM;
36809   }
36810   pNew->zFilename = (char*)&pNew[1];
36811   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
36812   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
36813 
36814   /* Look to see if there is an existing winShmNode that can be used.
36815   ** If no matching winShmNode currently exists, create a new one.
36816   */
36817   winShmEnterMutex();
36818   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
36819     /* TBD need to come up with better match here.  Perhaps
36820     ** use FILE_ID_BOTH_DIR_INFO Structure.
36821     */
36822     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
36823   }
36824   if( pShmNode ){
36825     sqlite3_free(pNew);
36826   }else{
36827     pShmNode = pNew;
36828     pNew = 0;
36829     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
36830     pShmNode->pNext = winShmNodeList;
36831     winShmNodeList = pShmNode;
36832 
36833     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
36834     if( pShmNode->mutex==0 ){
36835       rc = SQLITE_IOERR_NOMEM;
36836       goto shm_open_err;
36837     }
36838 
36839     rc = winOpen(pDbFd->pVfs,
36840                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
36841                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
36842                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
36843                  0);
36844     if( SQLITE_OK!=rc ){
36845       goto shm_open_err;
36846     }
36847 
36848     /* Check to see if another process is holding the dead-man switch.
36849     ** If not, truncate the file to zero length.
36850     */
36851     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
36852       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
36853       if( rc!=SQLITE_OK ){
36854         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
36855                          "winOpenShm", pDbFd->zPath);
36856       }
36857     }
36858     if( rc==SQLITE_OK ){
36859       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
36860       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
36861     }
36862     if( rc ) goto shm_open_err;
36863   }
36864 
36865   /* Make the new connection a child of the winShmNode */
36866   p->pShmNode = pShmNode;
36867 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
36868   p->id = pShmNode->nextShmId++;
36869 #endif
36870   pShmNode->nRef++;
36871   pDbFd->pShm = p;
36872   winShmLeaveMutex();
36873 
36874   /* The reference count on pShmNode has already been incremented under
36875   ** the cover of the winShmEnterMutex() mutex and the pointer from the
36876   ** new (struct winShm) object to the pShmNode has been set. All that is
36877   ** left to do is to link the new object into the linked list starting
36878   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
36879   ** mutex.
36880   */
36881   sqlite3_mutex_enter(pShmNode->mutex);
36882   p->pNext = pShmNode->pFirst;
36883   pShmNode->pFirst = p;
36884   sqlite3_mutex_leave(pShmNode->mutex);
36885   return SQLITE_OK;
36886 
36887   /* Jump here on any error */
36888 shm_open_err:
36889   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
36890   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
36891   sqlite3_free(p);
36892   sqlite3_free(pNew);
36893   winShmLeaveMutex();
36894   return rc;
36895 }
36896 
36897 /*
36898 ** Close a connection to shared-memory.  Delete the underlying
36899 ** storage if deleteFlag is true.
36900 */
36901 static int winShmUnmap(
36902   sqlite3_file *fd,          /* Database holding shared memory */
36903   int deleteFlag             /* Delete after closing if true */
36904 ){
36905   winFile *pDbFd;       /* Database holding shared-memory */
36906   winShm *p;            /* The connection to be closed */
36907   winShmNode *pShmNode; /* The underlying shared-memory file */
36908   winShm **pp;          /* For looping over sibling connections */
36909 
36910   pDbFd = (winFile*)fd;
36911   p = pDbFd->pShm;
36912   if( p==0 ) return SQLITE_OK;
36913   pShmNode = p->pShmNode;
36914 
36915   /* Remove connection p from the set of connections associated
36916   ** with pShmNode */
36917   sqlite3_mutex_enter(pShmNode->mutex);
36918   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
36919   *pp = p->pNext;
36920 
36921   /* Free the connection p */
36922   sqlite3_free(p);
36923   pDbFd->pShm = 0;
36924   sqlite3_mutex_leave(pShmNode->mutex);
36925 
36926   /* If pShmNode->nRef has reached 0, then close the underlying
36927   ** shared-memory file, too */
36928   winShmEnterMutex();
36929   assert( pShmNode->nRef>0 );
36930   pShmNode->nRef--;
36931   if( pShmNode->nRef==0 ){
36932     winShmPurge(pDbFd->pVfs, deleteFlag);
36933   }
36934   winShmLeaveMutex();
36935 
36936   return SQLITE_OK;
36937 }
36938 
36939 /*
36940 ** Change the lock state for a shared-memory segment.
36941 */
36942 static int winShmLock(
36943   sqlite3_file *fd,          /* Database file holding the shared memory */
36944   int ofst,                  /* First lock to acquire or release */
36945   int n,                     /* Number of locks to acquire or release */
36946   int flags                  /* What to do with the lock */
36947 ){
36948   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
36949   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
36950   winShm *pX;                           /* For looping over all siblings */
36951   winShmNode *pShmNode = p->pShmNode;
36952   int rc = SQLITE_OK;                   /* Result code */
36953   u16 mask;                             /* Mask of locks to take or release */
36954 
36955   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
36956   assert( n>=1 );
36957   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
36958        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
36959        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
36960        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
36961   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
36962 
36963   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
36964   assert( n>1 || mask==(1<<ofst) );
36965   sqlite3_mutex_enter(pShmNode->mutex);
36966   if( flags & SQLITE_SHM_UNLOCK ){
36967     u16 allMask = 0; /* Mask of locks held by siblings */
36968 
36969     /* See if any siblings hold this same lock */
36970     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
36971       if( pX==p ) continue;
36972       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
36973       allMask |= pX->sharedMask;
36974     }
36975 
36976     /* Unlock the system-level locks */
36977     if( (mask & allMask)==0 ){
36978       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
36979     }else{
36980       rc = SQLITE_OK;
36981     }
36982 
36983     /* Undo the local locks */
36984     if( rc==SQLITE_OK ){
36985       p->exclMask &= ~mask;
36986       p->sharedMask &= ~mask;
36987     }
36988   }else if( flags & SQLITE_SHM_SHARED ){
36989     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
36990 
36991     /* Find out which shared locks are already held by sibling connections.
36992     ** If any sibling already holds an exclusive lock, go ahead and return
36993     ** SQLITE_BUSY.
36994     */
36995     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
36996       if( (pX->exclMask & mask)!=0 ){
36997         rc = SQLITE_BUSY;
36998         break;
36999       }
37000       allShared |= pX->sharedMask;
37001     }
37002 
37003     /* Get shared locks at the system level, if necessary */
37004     if( rc==SQLITE_OK ){
37005       if( (allShared & mask)==0 ){
37006         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
37007       }else{
37008         rc = SQLITE_OK;
37009       }
37010     }
37011 
37012     /* Get the local shared locks */
37013     if( rc==SQLITE_OK ){
37014       p->sharedMask |= mask;
37015     }
37016   }else{
37017     /* Make sure no sibling connections hold locks that will block this
37018     ** lock.  If any do, return SQLITE_BUSY right away.
37019     */
37020     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
37021       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
37022         rc = SQLITE_BUSY;
37023         break;
37024       }
37025     }
37026 
37027     /* Get the exclusive locks at the system level.  Then if successful
37028     ** also mark the local connection as being locked.
37029     */
37030     if( rc==SQLITE_OK ){
37031       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
37032       if( rc==SQLITE_OK ){
37033         assert( (p->sharedMask & mask)==0 );
37034         p->exclMask |= mask;
37035       }
37036     }
37037   }
37038   sqlite3_mutex_leave(pShmNode->mutex);
37039   OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
37040            osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
37041            sqlite3ErrName(rc)));
37042   return rc;
37043 }
37044 
37045 /*
37046 ** Implement a memory barrier or memory fence on shared memory.
37047 **
37048 ** All loads and stores begun before the barrier must complete before
37049 ** any load or store begun after the barrier.
37050 */
37051 static void winShmBarrier(
37052   sqlite3_file *fd          /* Database holding the shared memory */
37053 ){
37054   UNUSED_PARAMETER(fd);
37055   /* MemoryBarrier(); // does not work -- do not know why not */
37056   winShmEnterMutex();
37057   winShmLeaveMutex();
37058 }
37059 
37060 /*
37061 ** This function is called to obtain a pointer to region iRegion of the
37062 ** shared-memory associated with the database file fd. Shared-memory regions
37063 ** are numbered starting from zero. Each shared-memory region is szRegion
37064 ** bytes in size.
37065 **
37066 ** If an error occurs, an error code is returned and *pp is set to NULL.
37067 **
37068 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
37069 ** region has not been allocated (by any client, including one running in a
37070 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
37071 ** isWrite is non-zero and the requested shared-memory region has not yet
37072 ** been allocated, it is allocated by this function.
37073 **
37074 ** If the shared-memory region has already been allocated or is allocated by
37075 ** this call as described above, then it is mapped into this processes
37076 ** address space (if it is not already), *pp is set to point to the mapped
37077 ** memory and SQLITE_OK returned.
37078 */
37079 static int winShmMap(
37080   sqlite3_file *fd,               /* Handle open on database file */
37081   int iRegion,                    /* Region to retrieve */
37082   int szRegion,                   /* Size of regions */
37083   int isWrite,                    /* True to extend file if necessary */
37084   void volatile **pp              /* OUT: Mapped memory */
37085 ){
37086   winFile *pDbFd = (winFile*)fd;
37087   winShm *pShm = pDbFd->pShm;
37088   winShmNode *pShmNode;
37089   int rc = SQLITE_OK;
37090 
37091   if( !pShm ){
37092     rc = winOpenSharedMemory(pDbFd);
37093     if( rc!=SQLITE_OK ) return rc;
37094     pShm = pDbFd->pShm;
37095   }
37096   pShmNode = pShm->pShmNode;
37097 
37098   sqlite3_mutex_enter(pShmNode->mutex);
37099   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
37100 
37101   if( pShmNode->nRegion<=iRegion ){
37102     struct ShmRegion *apNew;           /* New aRegion[] array */
37103     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
37104     sqlite3_int64 sz;                  /* Current size of wal-index file */
37105 
37106     pShmNode->szRegion = szRegion;
37107 
37108     /* The requested region is not mapped into this processes address space.
37109     ** Check to see if it has been allocated (i.e. if the wal-index file is
37110     ** large enough to contain the requested region).
37111     */
37112     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
37113     if( rc!=SQLITE_OK ){
37114       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
37115                        "winShmMap1", pDbFd->zPath);
37116       goto shmpage_out;
37117     }
37118 
37119     if( sz<nByte ){
37120       /* The requested memory region does not exist. If isWrite is set to
37121       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
37122       **
37123       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
37124       ** the requested memory region.
37125       */
37126       if( !isWrite ) goto shmpage_out;
37127       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
37128       if( rc!=SQLITE_OK ){
37129         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
37130                          "winShmMap2", pDbFd->zPath);
37131         goto shmpage_out;
37132       }
37133     }
37134 
37135     /* Map the requested memory region into this processes address space. */
37136     apNew = (struct ShmRegion *)sqlite3_realloc64(
37137         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
37138     );
37139     if( !apNew ){
37140       rc = SQLITE_IOERR_NOMEM;
37141       goto shmpage_out;
37142     }
37143     pShmNode->aRegion = apNew;
37144 
37145     while( pShmNode->nRegion<=iRegion ){
37146       HANDLE hMap = NULL;         /* file-mapping handle */
37147       void *pMap = 0;             /* Mapped memory region */
37148 
37149 #if SQLITE_OS_WINRT
37150       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
37151           NULL, PAGE_READWRITE, nByte, NULL
37152       );
37153 #elif defined(SQLITE_WIN32_HAS_WIDE)
37154       hMap = osCreateFileMappingW(pShmNode->hFile.h,
37155           NULL, PAGE_READWRITE, 0, nByte, NULL
37156       );
37157 #elif defined(SQLITE_WIN32_HAS_ANSI)
37158       hMap = osCreateFileMappingA(pShmNode->hFile.h,
37159           NULL, PAGE_READWRITE, 0, nByte, NULL
37160       );
37161 #endif
37162       OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
37163                osGetCurrentProcessId(), pShmNode->nRegion, nByte,
37164                hMap ? "ok" : "failed"));
37165       if( hMap ){
37166         int iOffset = pShmNode->nRegion*szRegion;
37167         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
37168 #if SQLITE_OS_WINRT
37169         pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
37170             iOffset - iOffsetShift, szRegion + iOffsetShift
37171         );
37172 #else
37173         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
37174             0, iOffset - iOffsetShift, szRegion + iOffsetShift
37175         );
37176 #endif
37177         OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
37178                  osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
37179                  szRegion, pMap ? "ok" : "failed"));
37180       }
37181       if( !pMap ){
37182         pShmNode->lastErrno = osGetLastError();
37183         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
37184                          "winShmMap3", pDbFd->zPath);
37185         if( hMap ) osCloseHandle(hMap);
37186         goto shmpage_out;
37187       }
37188 
37189       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
37190       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
37191       pShmNode->nRegion++;
37192     }
37193   }
37194 
37195 shmpage_out:
37196   if( pShmNode->nRegion>iRegion ){
37197     int iOffset = iRegion*szRegion;
37198     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
37199     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
37200     *pp = (void *)&p[iOffsetShift];
37201   }else{
37202     *pp = 0;
37203   }
37204   sqlite3_mutex_leave(pShmNode->mutex);
37205   return rc;
37206 }
37207 
37208 #else
37209 # define winShmMap     0
37210 # define winShmLock    0
37211 # define winShmBarrier 0
37212 # define winShmUnmap   0
37213 #endif /* #ifndef SQLITE_OMIT_WAL */
37214 
37215 /*
37216 ** Cleans up the mapped region of the specified file, if any.
37217 */
37218 #if SQLITE_MAX_MMAP_SIZE>0
37219 static int winUnmapfile(winFile *pFile){
37220   assert( pFile!=0 );
37221   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
37222            "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
37223            osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
37224            pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
37225   if( pFile->pMapRegion ){
37226     if( !osUnmapViewOfFile(pFile->pMapRegion) ){
37227       pFile->lastErrno = osGetLastError();
37228       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
37229                "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
37230                pFile->pMapRegion));
37231       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
37232                          "winUnmapfile1", pFile->zPath);
37233     }
37234     pFile->pMapRegion = 0;
37235     pFile->mmapSize = 0;
37236     pFile->mmapSizeActual = 0;
37237   }
37238   if( pFile->hMap!=NULL ){
37239     if( !osCloseHandle(pFile->hMap) ){
37240       pFile->lastErrno = osGetLastError();
37241       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
37242                osGetCurrentProcessId(), pFile, pFile->hMap));
37243       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
37244                          "winUnmapfile2", pFile->zPath);
37245     }
37246     pFile->hMap = NULL;
37247   }
37248   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
37249            osGetCurrentProcessId(), pFile));
37250   return SQLITE_OK;
37251 }
37252 
37253 /*
37254 ** Memory map or remap the file opened by file-descriptor pFd (if the file
37255 ** is already mapped, the existing mapping is replaced by the new). Or, if
37256 ** there already exists a mapping for this file, and there are still
37257 ** outstanding xFetch() references to it, this function is a no-op.
37258 **
37259 ** If parameter nByte is non-negative, then it is the requested size of
37260 ** the mapping to create. Otherwise, if nByte is less than zero, then the
37261 ** requested size is the size of the file on disk. The actual size of the
37262 ** created mapping is either the requested size or the value configured
37263 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
37264 **
37265 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
37266 ** recreated as a result of outstanding references) or an SQLite error
37267 ** code otherwise.
37268 */
37269 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
37270   sqlite3_int64 nMap = nByte;
37271   int rc;
37272 
37273   assert( nMap>=0 || pFd->nFetchOut==0 );
37274   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
37275            osGetCurrentProcessId(), pFd, nByte));
37276 
37277   if( pFd->nFetchOut>0 ) return SQLITE_OK;
37278 
37279   if( nMap<0 ){
37280     rc = winFileSize((sqlite3_file*)pFd, &nMap);
37281     if( rc ){
37282       OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
37283                osGetCurrentProcessId(), pFd));
37284       return SQLITE_IOERR_FSTAT;
37285     }
37286   }
37287   if( nMap>pFd->mmapSizeMax ){
37288     nMap = pFd->mmapSizeMax;
37289   }
37290   nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
37291 
37292   if( nMap==0 && pFd->mmapSize>0 ){
37293     winUnmapfile(pFd);
37294   }
37295   if( nMap!=pFd->mmapSize ){
37296     void *pNew = 0;
37297     DWORD protect = PAGE_READONLY;
37298     DWORD flags = FILE_MAP_READ;
37299 
37300     winUnmapfile(pFd);
37301     if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
37302       protect = PAGE_READWRITE;
37303       flags |= FILE_MAP_WRITE;
37304     }
37305 #if SQLITE_OS_WINRT
37306     pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
37307 #elif defined(SQLITE_WIN32_HAS_WIDE)
37308     pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
37309                                 (DWORD)((nMap>>32) & 0xffffffff),
37310                                 (DWORD)(nMap & 0xffffffff), NULL);
37311 #elif defined(SQLITE_WIN32_HAS_ANSI)
37312     pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
37313                                 (DWORD)((nMap>>32) & 0xffffffff),
37314                                 (DWORD)(nMap & 0xffffffff), NULL);
37315 #endif
37316     if( pFd->hMap==NULL ){
37317       pFd->lastErrno = osGetLastError();
37318       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
37319                        "winMapfile1", pFd->zPath);
37320       /* Log the error, but continue normal operation using xRead/xWrite */
37321       OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
37322                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
37323       return SQLITE_OK;
37324     }
37325     assert( (nMap % winSysInfo.dwPageSize)==0 );
37326     assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
37327 #if SQLITE_OS_WINRT
37328     pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
37329 #else
37330     pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
37331 #endif
37332     if( pNew==NULL ){
37333       osCloseHandle(pFd->hMap);
37334       pFd->hMap = NULL;
37335       pFd->lastErrno = osGetLastError();
37336       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
37337                        "winMapfile2", pFd->zPath);
37338       /* Log the error, but continue normal operation using xRead/xWrite */
37339       OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
37340                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
37341       return SQLITE_OK;
37342     }
37343     pFd->pMapRegion = pNew;
37344     pFd->mmapSize = nMap;
37345     pFd->mmapSizeActual = nMap;
37346   }
37347 
37348   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
37349            osGetCurrentProcessId(), pFd));
37350   return SQLITE_OK;
37351 }
37352 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
37353 
37354 /*
37355 ** If possible, return a pointer to a mapping of file fd starting at offset
37356 ** iOff. The mapping must be valid for at least nAmt bytes.
37357 **
37358 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
37359 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
37360 ** Finally, if an error does occur, return an SQLite error code. The final
37361 ** value of *pp is undefined in this case.
37362 **
37363 ** If this function does return a pointer, the caller must eventually
37364 ** release the reference by calling winUnfetch().
37365 */
37366 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
37367 #if SQLITE_MAX_MMAP_SIZE>0
37368   winFile *pFd = (winFile*)fd;   /* The underlying database file */
37369 #endif
37370   *pp = 0;
37371 
37372   OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
37373            osGetCurrentProcessId(), fd, iOff, nAmt, pp));
37374 
37375 #if SQLITE_MAX_MMAP_SIZE>0
37376   if( pFd->mmapSizeMax>0 ){
37377     if( pFd->pMapRegion==0 ){
37378       int rc = winMapfile(pFd, -1);
37379       if( rc!=SQLITE_OK ){
37380         OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
37381                  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
37382         return rc;
37383       }
37384     }
37385     if( pFd->mmapSize >= iOff+nAmt ){
37386       *pp = &((u8 *)pFd->pMapRegion)[iOff];
37387       pFd->nFetchOut++;
37388     }
37389   }
37390 #endif
37391 
37392   OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
37393            osGetCurrentProcessId(), fd, pp, *pp));
37394   return SQLITE_OK;
37395 }
37396 
37397 /*
37398 ** If the third argument is non-NULL, then this function releases a
37399 ** reference obtained by an earlier call to winFetch(). The second
37400 ** argument passed to this function must be the same as the corresponding
37401 ** argument that was passed to the winFetch() invocation.
37402 **
37403 ** Or, if the third argument is NULL, then this function is being called
37404 ** to inform the VFS layer that, according to POSIX, any existing mapping
37405 ** may now be invalid and should be unmapped.
37406 */
37407 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
37408 #if SQLITE_MAX_MMAP_SIZE>0
37409   winFile *pFd = (winFile*)fd;   /* The underlying database file */
37410 
37411   /* If p==0 (unmap the entire file) then there must be no outstanding
37412   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
37413   ** then there must be at least one outstanding.  */
37414   assert( (p==0)==(pFd->nFetchOut==0) );
37415 
37416   /* If p!=0, it must match the iOff value. */
37417   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
37418 
37419   OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
37420            osGetCurrentProcessId(), pFd, iOff, p));
37421 
37422   if( p ){
37423     pFd->nFetchOut--;
37424   }else{
37425     /* FIXME:  If Windows truly always prevents truncating or deleting a
37426     ** file while a mapping is held, then the following winUnmapfile() call
37427     ** is unnecessary can be omitted - potentially improving
37428     ** performance.  */
37429     winUnmapfile(pFd);
37430   }
37431 
37432   assert( pFd->nFetchOut>=0 );
37433 #endif
37434 
37435   OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
37436            osGetCurrentProcessId(), fd));
37437   return SQLITE_OK;
37438 }
37439 
37440 /*
37441 ** Here ends the implementation of all sqlite3_file methods.
37442 **
37443 ********************** End sqlite3_file Methods *******************************
37444 ******************************************************************************/
37445 
37446 /*
37447 ** This vector defines all the methods that can operate on an
37448 ** sqlite3_file for win32.
37449 */
37450 static const sqlite3_io_methods winIoMethod = {
37451   3,                              /* iVersion */
37452   winClose,                       /* xClose */
37453   winRead,                        /* xRead */
37454   winWrite,                       /* xWrite */
37455   winTruncate,                    /* xTruncate */
37456   winSync,                        /* xSync */
37457   winFileSize,                    /* xFileSize */
37458   winLock,                        /* xLock */
37459   winUnlock,                      /* xUnlock */
37460   winCheckReservedLock,           /* xCheckReservedLock */
37461   winFileControl,                 /* xFileControl */
37462   winSectorSize,                  /* xSectorSize */
37463   winDeviceCharacteristics,       /* xDeviceCharacteristics */
37464   winShmMap,                      /* xShmMap */
37465   winShmLock,                     /* xShmLock */
37466   winShmBarrier,                  /* xShmBarrier */
37467   winShmUnmap,                    /* xShmUnmap */
37468   winFetch,                       /* xFetch */
37469   winUnfetch                      /* xUnfetch */
37470 };
37471 
37472 /****************************************************************************
37473 **************************** sqlite3_vfs methods ****************************
37474 **
37475 ** This division contains the implementation of methods on the
37476 ** sqlite3_vfs object.
37477 */
37478 
37479 #if defined(__CYGWIN__)
37480 /*
37481 ** Convert a filename from whatever the underlying operating system
37482 ** supports for filenames into UTF-8.  Space to hold the result is
37483 ** obtained from malloc and must be freed by the calling function.
37484 */
37485 static char *winConvertToUtf8Filename(const void *zFilename){
37486   char *zConverted = 0;
37487   if( osIsNT() ){
37488     zConverted = winUnicodeToUtf8(zFilename);
37489   }
37490 #ifdef SQLITE_WIN32_HAS_ANSI
37491   else{
37492     zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
37493   }
37494 #endif
37495   /* caller will handle out of memory */
37496   return zConverted;
37497 }
37498 #endif
37499 
37500 /*
37501 ** Convert a UTF-8 filename into whatever form the underlying
37502 ** operating system wants filenames in.  Space to hold the result
37503 ** is obtained from malloc and must be freed by the calling
37504 ** function.
37505 */
37506 static void *winConvertFromUtf8Filename(const char *zFilename){
37507   void *zConverted = 0;
37508   if( osIsNT() ){
37509     zConverted = winUtf8ToUnicode(zFilename);
37510   }
37511 #ifdef SQLITE_WIN32_HAS_ANSI
37512   else{
37513     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
37514   }
37515 #endif
37516   /* caller will handle out of memory */
37517   return zConverted;
37518 }
37519 
37520 /*
37521 ** This function returns non-zero if the specified UTF-8 string buffer
37522 ** ends with a directory separator character or one was successfully
37523 ** added to it.
37524 */
37525 static int winMakeEndInDirSep(int nBuf, char *zBuf){
37526   if( zBuf ){
37527     int nLen = sqlite3Strlen30(zBuf);
37528     if( nLen>0 ){
37529       if( winIsDirSep(zBuf[nLen-1]) ){
37530         return 1;
37531       }else if( nLen+1<nBuf ){
37532         zBuf[nLen] = winGetDirSep();
37533         zBuf[nLen+1] = '\0';
37534         return 1;
37535       }
37536     }
37537   }
37538   return 0;
37539 }
37540 
37541 /*
37542 ** Create a temporary file name and store the resulting pointer into pzBuf.
37543 ** The pointer returned in pzBuf must be freed via sqlite3_free().
37544 */
37545 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
37546   static char zChars[] =
37547     "abcdefghijklmnopqrstuvwxyz"
37548     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
37549     "0123456789";
37550   size_t i, j;
37551   int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
37552   int nMax, nBuf, nDir, nLen;
37553   char *zBuf;
37554 
37555   /* It's odd to simulate an io-error here, but really this is just
37556   ** using the io-error infrastructure to test that SQLite handles this
37557   ** function failing.
37558   */
37559   SimulateIOError( return SQLITE_IOERR );
37560 
37561   /* Allocate a temporary buffer to store the fully qualified file
37562   ** name for the temporary file.  If this fails, we cannot continue.
37563   */
37564   nMax = pVfs->mxPathname; nBuf = nMax + 2;
37565   zBuf = sqlite3MallocZero( nBuf );
37566   if( !zBuf ){
37567     OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37568     return SQLITE_IOERR_NOMEM;
37569   }
37570 
37571   /* Figure out the effective temporary directory.  First, check if one
37572   ** has been explicitly set by the application; otherwise, use the one
37573   ** configured by the operating system.
37574   */
37575   nDir = nMax - (nPre + 15);
37576   assert( nDir>0 );
37577   if( sqlite3_temp_directory ){
37578     int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
37579     if( nDirLen>0 ){
37580       if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
37581         nDirLen++;
37582       }
37583       if( nDirLen>nDir ){
37584         sqlite3_free(zBuf);
37585         OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
37586         return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
37587       }
37588       sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
37589     }
37590   }
37591 #if defined(__CYGWIN__)
37592   else{
37593     static const char *azDirs[] = {
37594        0, /* getenv("SQLITE_TMPDIR") */
37595        0, /* getenv("TMPDIR") */
37596        0, /* getenv("TMP") */
37597        0, /* getenv("TEMP") */
37598        0, /* getenv("USERPROFILE") */
37599        "/var/tmp",
37600        "/usr/tmp",
37601        "/tmp",
37602        ".",
37603        0        /* List terminator */
37604     };
37605     unsigned int i;
37606     const char *zDir = 0;
37607 
37608     if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
37609     if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
37610     if( !azDirs[2] ) azDirs[2] = getenv("TMP");
37611     if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
37612     if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
37613     for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
37614       void *zConverted;
37615       if( zDir==0 ) continue;
37616       /* If the path starts with a drive letter followed by the colon
37617       ** character, assume it is already a native Win32 path; otherwise,
37618       ** it must be converted to a native Win32 path via the Cygwin API
37619       ** prior to using it.
37620       */
37621       if( winIsDriveLetterAndColon(zDir) ){
37622         zConverted = winConvertFromUtf8Filename(zDir);
37623         if( !zConverted ){
37624           sqlite3_free(zBuf);
37625           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37626           return SQLITE_IOERR_NOMEM;
37627         }
37628         if( winIsDir(zConverted) ){
37629           sqlite3_snprintf(nMax, zBuf, "%s", zDir);
37630           sqlite3_free(zConverted);
37631           break;
37632         }
37633         sqlite3_free(zConverted);
37634       }else{
37635         zConverted = sqlite3MallocZero( nMax+1 );
37636         if( !zConverted ){
37637           sqlite3_free(zBuf);
37638           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37639           return SQLITE_IOERR_NOMEM;
37640         }
37641         if( cygwin_conv_path(
37642                 osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
37643                 zConverted, nMax+1)<0 ){
37644           sqlite3_free(zConverted);
37645           sqlite3_free(zBuf);
37646           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
37647           return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
37648                              "winGetTempname2", zDir);
37649         }
37650         if( winIsDir(zConverted) ){
37651           /* At this point, we know the candidate directory exists and should
37652           ** be used.  However, we may need to convert the string containing
37653           ** its name into UTF-8 (i.e. if it is UTF-16 right now).
37654           */
37655           char *zUtf8 = winConvertToUtf8Filename(zConverted);
37656           if( !zUtf8 ){
37657             sqlite3_free(zConverted);
37658             sqlite3_free(zBuf);
37659             OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37660             return SQLITE_IOERR_NOMEM;
37661           }
37662           sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
37663           sqlite3_free(zUtf8);
37664           sqlite3_free(zConverted);
37665           break;
37666         }
37667         sqlite3_free(zConverted);
37668       }
37669     }
37670   }
37671 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
37672   else if( osIsNT() ){
37673     char *zMulti;
37674     LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
37675     if( !zWidePath ){
37676       sqlite3_free(zBuf);
37677       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37678       return SQLITE_IOERR_NOMEM;
37679     }
37680     if( osGetTempPathW(nMax, zWidePath)==0 ){
37681       sqlite3_free(zWidePath);
37682       sqlite3_free(zBuf);
37683       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
37684       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
37685                          "winGetTempname2", 0);
37686     }
37687     zMulti = winUnicodeToUtf8(zWidePath);
37688     if( zMulti ){
37689       sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
37690       sqlite3_free(zMulti);
37691       sqlite3_free(zWidePath);
37692     }else{
37693       sqlite3_free(zWidePath);
37694       sqlite3_free(zBuf);
37695       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37696       return SQLITE_IOERR_NOMEM;
37697     }
37698   }
37699 #ifdef SQLITE_WIN32_HAS_ANSI
37700   else{
37701     char *zUtf8;
37702     char *zMbcsPath = sqlite3MallocZero( nMax );
37703     if( !zMbcsPath ){
37704       sqlite3_free(zBuf);
37705       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37706       return SQLITE_IOERR_NOMEM;
37707     }
37708     if( osGetTempPathA(nMax, zMbcsPath)==0 ){
37709       sqlite3_free(zBuf);
37710       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
37711       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
37712                          "winGetTempname3", 0);
37713     }
37714     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
37715     if( zUtf8 ){
37716       sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
37717       sqlite3_free(zUtf8);
37718     }else{
37719       sqlite3_free(zBuf);
37720       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37721       return SQLITE_IOERR_NOMEM;
37722     }
37723   }
37724 #endif /* SQLITE_WIN32_HAS_ANSI */
37725 #endif /* !SQLITE_OS_WINRT */
37726 
37727   /*
37728   ** Check to make sure the temporary directory ends with an appropriate
37729   ** separator.  If it does not and there is not enough space left to add
37730   ** one, fail.
37731   */
37732   if( !winMakeEndInDirSep(nDir+1, zBuf) ){
37733     sqlite3_free(zBuf);
37734     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
37735     return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
37736   }
37737 
37738   /*
37739   ** Check that the output buffer is large enough for the temporary file
37740   ** name in the following format:
37741   **
37742   **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
37743   **
37744   ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
37745   ** account for the space used by the 15 character random suffix and the
37746   ** two trailing NUL characters.  The final directory separator character
37747   ** has already added if it was not already present.
37748   */
37749   nLen = sqlite3Strlen30(zBuf);
37750   if( (nLen + nPre + 17) > nBuf ){
37751     sqlite3_free(zBuf);
37752     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
37753     return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
37754   }
37755 
37756   sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
37757 
37758   j = sqlite3Strlen30(zBuf);
37759   sqlite3_randomness(15, &zBuf[j]);
37760   for(i=0; i<15; i++, j++){
37761     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
37762   }
37763   zBuf[j] = 0;
37764   zBuf[j+1] = 0;
37765   *pzBuf = zBuf;
37766 
37767   OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
37768   return SQLITE_OK;
37769 }
37770 
37771 /*
37772 ** Return TRUE if the named file is really a directory.  Return false if
37773 ** it is something other than a directory, or if there is any kind of memory
37774 ** allocation failure.
37775 */
37776 static int winIsDir(const void *zConverted){
37777   DWORD attr;
37778   int rc = 0;
37779   DWORD lastErrno;
37780 
37781   if( osIsNT() ){
37782     int cnt = 0;
37783     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
37784     memset(&sAttrData, 0, sizeof(sAttrData));
37785     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
37786                              GetFileExInfoStandard,
37787                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
37788     if( !rc ){
37789       return 0; /* Invalid name? */
37790     }
37791     attr = sAttrData.dwFileAttributes;
37792 #if SQLITE_OS_WINCE==0
37793   }else{
37794     attr = osGetFileAttributesA((char*)zConverted);
37795 #endif
37796   }
37797   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
37798 }
37799 
37800 /*
37801 ** Open a file.
37802 */
37803 static int winOpen(
37804   sqlite3_vfs *pVfs,        /* Used to get maximum path name length */
37805   const char *zName,        /* Name of the file (UTF-8) */
37806   sqlite3_file *id,         /* Write the SQLite file handle here */
37807   int flags,                /* Open mode flags */
37808   int *pOutFlags            /* Status return flags */
37809 ){
37810   HANDLE h;
37811   DWORD lastErrno = 0;
37812   DWORD dwDesiredAccess;
37813   DWORD dwShareMode;
37814   DWORD dwCreationDisposition;
37815   DWORD dwFlagsAndAttributes = 0;
37816 #if SQLITE_OS_WINCE
37817   int isTemp = 0;
37818 #endif
37819   winFile *pFile = (winFile*)id;
37820   void *zConverted;              /* Filename in OS encoding */
37821   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
37822   int cnt = 0;
37823 
37824   /* If argument zPath is a NULL pointer, this function is required to open
37825   ** a temporary file. Use this buffer to store the file name in.
37826   */
37827   char *zTmpname = 0; /* For temporary filename, if necessary. */
37828 
37829   int rc = SQLITE_OK;            /* Function Return Code */
37830 #if !defined(NDEBUG) || SQLITE_OS_WINCE
37831   int eType = flags&0xFFFFFF00;  /* Type of file to open */
37832 #endif
37833 
37834   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
37835   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
37836   int isCreate     = (flags & SQLITE_OPEN_CREATE);
37837   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
37838   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
37839 
37840 #ifndef NDEBUG
37841   int isOpenJournal = (isCreate && (
37842         eType==SQLITE_OPEN_MASTER_JOURNAL
37843      || eType==SQLITE_OPEN_MAIN_JOURNAL
37844      || eType==SQLITE_OPEN_WAL
37845   ));
37846 #endif
37847 
37848   OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
37849            zUtf8Name, id, flags, pOutFlags));
37850 
37851   /* Check the following statements are true:
37852   **
37853   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
37854   **   (b) if CREATE is set, then READWRITE must also be set, and
37855   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
37856   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
37857   */
37858   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
37859   assert(isCreate==0 || isReadWrite);
37860   assert(isExclusive==0 || isCreate);
37861   assert(isDelete==0 || isCreate);
37862 
37863   /* The main DB, main journal, WAL file and master journal are never
37864   ** automatically deleted. Nor are they ever temporary files.  */
37865   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
37866   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
37867   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
37868   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
37869 
37870   /* Assert that the upper layer has set one of the "file-type" flags. */
37871   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
37872        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
37873        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
37874        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
37875   );
37876 
37877   assert( pFile!=0 );
37878   memset(pFile, 0, sizeof(winFile));
37879   pFile->h = INVALID_HANDLE_VALUE;
37880 
37881 #if SQLITE_OS_WINRT
37882   if( !zUtf8Name && !sqlite3_temp_directory ){
37883     sqlite3_log(SQLITE_ERROR,
37884         "sqlite3_temp_directory variable should be set for WinRT");
37885   }
37886 #endif
37887 
37888   /* If the second argument to this function is NULL, generate a
37889   ** temporary file name to use
37890   */
37891   if( !zUtf8Name ){
37892     assert( isDelete && !isOpenJournal );
37893     rc = winGetTempname(pVfs, &zTmpname);
37894     if( rc!=SQLITE_OK ){
37895       OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
37896       return rc;
37897     }
37898     zUtf8Name = zTmpname;
37899   }
37900 
37901   /* Database filenames are double-zero terminated if they are not
37902   ** URIs with parameters.  Hence, they can always be passed into
37903   ** sqlite3_uri_parameter().
37904   */
37905   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
37906        zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
37907 
37908   /* Convert the filename to the system encoding. */
37909   zConverted = winConvertFromUtf8Filename(zUtf8Name);
37910   if( zConverted==0 ){
37911     sqlite3_free(zTmpname);
37912     OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
37913     return SQLITE_IOERR_NOMEM;
37914   }
37915 
37916   if( winIsDir(zConverted) ){
37917     sqlite3_free(zConverted);
37918     sqlite3_free(zTmpname);
37919     OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
37920     return SQLITE_CANTOPEN_ISDIR;
37921   }
37922 
37923   if( isReadWrite ){
37924     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
37925   }else{
37926     dwDesiredAccess = GENERIC_READ;
37927   }
37928 
37929   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
37930   ** created. SQLite doesn't use it to indicate "exclusive access"
37931   ** as it is usually understood.
37932   */
37933   if( isExclusive ){
37934     /* Creates a new file, only if it does not already exist. */
37935     /* If the file exists, it fails. */
37936     dwCreationDisposition = CREATE_NEW;
37937   }else if( isCreate ){
37938     /* Open existing file, or create if it doesn't exist */
37939     dwCreationDisposition = OPEN_ALWAYS;
37940   }else{
37941     /* Opens a file, only if it exists. */
37942     dwCreationDisposition = OPEN_EXISTING;
37943   }
37944 
37945   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
37946 
37947   if( isDelete ){
37948 #if SQLITE_OS_WINCE
37949     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
37950     isTemp = 1;
37951 #else
37952     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
37953                                | FILE_ATTRIBUTE_HIDDEN
37954                                | FILE_FLAG_DELETE_ON_CLOSE;
37955 #endif
37956   }else{
37957     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
37958   }
37959   /* Reports from the internet are that performance is always
37960   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
37961 #if SQLITE_OS_WINCE
37962   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
37963 #endif
37964 
37965   if( osIsNT() ){
37966 #if SQLITE_OS_WINRT
37967     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
37968     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
37969     extendedParameters.dwFileAttributes =
37970             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
37971     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
37972     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
37973     extendedParameters.lpSecurityAttributes = NULL;
37974     extendedParameters.hTemplateFile = NULL;
37975     while( (h = osCreateFile2((LPCWSTR)zConverted,
37976                               dwDesiredAccess,
37977                               dwShareMode,
37978                               dwCreationDisposition,
37979                               &extendedParameters))==INVALID_HANDLE_VALUE &&
37980                               winRetryIoerr(&cnt, &lastErrno) ){
37981                /* Noop */
37982     }
37983 #else
37984     while( (h = osCreateFileW((LPCWSTR)zConverted,
37985                               dwDesiredAccess,
37986                               dwShareMode, NULL,
37987                               dwCreationDisposition,
37988                               dwFlagsAndAttributes,
37989                               NULL))==INVALID_HANDLE_VALUE &&
37990                               winRetryIoerr(&cnt, &lastErrno) ){
37991                /* Noop */
37992     }
37993 #endif
37994   }
37995 #ifdef SQLITE_WIN32_HAS_ANSI
37996   else{
37997     while( (h = osCreateFileA((LPCSTR)zConverted,
37998                               dwDesiredAccess,
37999                               dwShareMode, NULL,
38000                               dwCreationDisposition,
38001                               dwFlagsAndAttributes,
38002                               NULL))==INVALID_HANDLE_VALUE &&
38003                               winRetryIoerr(&cnt, &lastErrno) ){
38004                /* Noop */
38005     }
38006   }
38007 #endif
38008   winLogIoerr(cnt, __LINE__);
38009 
38010   OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
38011            dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
38012 
38013   if( h==INVALID_HANDLE_VALUE ){
38014     pFile->lastErrno = lastErrno;
38015     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
38016     sqlite3_free(zConverted);
38017     sqlite3_free(zTmpname);
38018     if( isReadWrite && !isExclusive ){
38019       return winOpen(pVfs, zName, id,
38020          ((flags|SQLITE_OPEN_READONLY) &
38021                      ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
38022          pOutFlags);
38023     }else{
38024       return SQLITE_CANTOPEN_BKPT;
38025     }
38026   }
38027 
38028   if( pOutFlags ){
38029     if( isReadWrite ){
38030       *pOutFlags = SQLITE_OPEN_READWRITE;
38031     }else{
38032       *pOutFlags = SQLITE_OPEN_READONLY;
38033     }
38034   }
38035 
38036   OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
38037            "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
38038            *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
38039 
38040 #if SQLITE_OS_WINCE
38041   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
38042        && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
38043   ){
38044     osCloseHandle(h);
38045     sqlite3_free(zConverted);
38046     sqlite3_free(zTmpname);
38047     OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
38048     return rc;
38049   }
38050   if( isTemp ){
38051     pFile->zDeleteOnClose = zConverted;
38052   }else
38053 #endif
38054   {
38055     sqlite3_free(zConverted);
38056   }
38057 
38058   sqlite3_free(zTmpname);
38059   pFile->pMethod = &winIoMethod;
38060   pFile->pVfs = pVfs;
38061   pFile->h = h;
38062   if( isReadonly ){
38063     pFile->ctrlFlags |= WINFILE_RDONLY;
38064   }
38065   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
38066     pFile->ctrlFlags |= WINFILE_PSOW;
38067   }
38068   pFile->lastErrno = NO_ERROR;
38069   pFile->zPath = zName;
38070 #if SQLITE_MAX_MMAP_SIZE>0
38071   pFile->hMap = NULL;
38072   pFile->pMapRegion = 0;
38073   pFile->mmapSize = 0;
38074   pFile->mmapSizeActual = 0;
38075   pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
38076 #endif
38077 
38078   OpenCounter(+1);
38079   return rc;
38080 }
38081 
38082 /*
38083 ** Delete the named file.
38084 **
38085 ** Note that Windows does not allow a file to be deleted if some other
38086 ** process has it open.  Sometimes a virus scanner or indexing program
38087 ** will open a journal file shortly after it is created in order to do
38088 ** whatever it does.  While this other process is holding the
38089 ** file open, we will be unable to delete it.  To work around this
38090 ** problem, we delay 100 milliseconds and try to delete again.  Up
38091 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
38092 ** up and returning an error.
38093 */
38094 static int winDelete(
38095   sqlite3_vfs *pVfs,          /* Not used on win32 */
38096   const char *zFilename,      /* Name of file to delete */
38097   int syncDir                 /* Not used on win32 */
38098 ){
38099   int cnt = 0;
38100   int rc;
38101   DWORD attr;
38102   DWORD lastErrno = 0;
38103   void *zConverted;
38104   UNUSED_PARAMETER(pVfs);
38105   UNUSED_PARAMETER(syncDir);
38106 
38107   SimulateIOError(return SQLITE_IOERR_DELETE);
38108   OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
38109 
38110   zConverted = winConvertFromUtf8Filename(zFilename);
38111   if( zConverted==0 ){
38112     OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
38113     return SQLITE_IOERR_NOMEM;
38114   }
38115   if( osIsNT() ){
38116     do {
38117 #if SQLITE_OS_WINRT
38118       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
38119       memset(&sAttrData, 0, sizeof(sAttrData));
38120       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
38121                                   &sAttrData) ){
38122         attr = sAttrData.dwFileAttributes;
38123       }else{
38124         lastErrno = osGetLastError();
38125         if( lastErrno==ERROR_FILE_NOT_FOUND
38126          || lastErrno==ERROR_PATH_NOT_FOUND ){
38127           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
38128         }else{
38129           rc = SQLITE_ERROR;
38130         }
38131         break;
38132       }
38133 #else
38134       attr = osGetFileAttributesW(zConverted);
38135 #endif
38136       if ( attr==INVALID_FILE_ATTRIBUTES ){
38137         lastErrno = osGetLastError();
38138         if( lastErrno==ERROR_FILE_NOT_FOUND
38139          || lastErrno==ERROR_PATH_NOT_FOUND ){
38140           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
38141         }else{
38142           rc = SQLITE_ERROR;
38143         }
38144         break;
38145       }
38146       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
38147         rc = SQLITE_ERROR; /* Files only. */
38148         break;
38149       }
38150       if ( osDeleteFileW(zConverted) ){
38151         rc = SQLITE_OK; /* Deleted OK. */
38152         break;
38153       }
38154       if ( !winRetryIoerr(&cnt, &lastErrno) ){
38155         rc = SQLITE_ERROR; /* No more retries. */
38156         break;
38157       }
38158     } while(1);
38159   }
38160 #ifdef SQLITE_WIN32_HAS_ANSI
38161   else{
38162     do {
38163       attr = osGetFileAttributesA(zConverted);
38164       if ( attr==INVALID_FILE_ATTRIBUTES ){
38165         lastErrno = osGetLastError();
38166         if( lastErrno==ERROR_FILE_NOT_FOUND
38167          || lastErrno==ERROR_PATH_NOT_FOUND ){
38168           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
38169         }else{
38170           rc = SQLITE_ERROR;
38171         }
38172         break;
38173       }
38174       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
38175         rc = SQLITE_ERROR; /* Files only. */
38176         break;
38177       }
38178       if ( osDeleteFileA(zConverted) ){
38179         rc = SQLITE_OK; /* Deleted OK. */
38180         break;
38181       }
38182       if ( !winRetryIoerr(&cnt, &lastErrno) ){
38183         rc = SQLITE_ERROR; /* No more retries. */
38184         break;
38185       }
38186     } while(1);
38187   }
38188 #endif
38189   if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
38190     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
38191   }else{
38192     winLogIoerr(cnt, __LINE__);
38193   }
38194   sqlite3_free(zConverted);
38195   OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
38196   return rc;
38197 }
38198 
38199 /*
38200 ** Check the existence and status of a file.
38201 */
38202 static int winAccess(
38203   sqlite3_vfs *pVfs,         /* Not used on win32 */
38204   const char *zFilename,     /* Name of file to check */
38205   int flags,                 /* Type of test to make on this file */
38206   int *pResOut               /* OUT: Result */
38207 ){
38208   DWORD attr;
38209   int rc = 0;
38210   DWORD lastErrno = 0;
38211   void *zConverted;
38212   UNUSED_PARAMETER(pVfs);
38213 
38214   SimulateIOError( return SQLITE_IOERR_ACCESS; );
38215   OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
38216            zFilename, flags, pResOut));
38217 
38218   zConverted = winConvertFromUtf8Filename(zFilename);
38219   if( zConverted==0 ){
38220     OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
38221     return SQLITE_IOERR_NOMEM;
38222   }
38223   if( osIsNT() ){
38224     int cnt = 0;
38225     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
38226     memset(&sAttrData, 0, sizeof(sAttrData));
38227     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
38228                              GetFileExInfoStandard,
38229                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
38230     if( rc ){
38231       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
38232       ** as if it does not exist.
38233       */
38234       if(    flags==SQLITE_ACCESS_EXISTS
38235           && sAttrData.nFileSizeHigh==0
38236           && sAttrData.nFileSizeLow==0 ){
38237         attr = INVALID_FILE_ATTRIBUTES;
38238       }else{
38239         attr = sAttrData.dwFileAttributes;
38240       }
38241     }else{
38242       winLogIoerr(cnt, __LINE__);
38243       if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
38244         sqlite3_free(zConverted);
38245         return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
38246                            zFilename);
38247       }else{
38248         attr = INVALID_FILE_ATTRIBUTES;
38249       }
38250     }
38251   }
38252 #ifdef SQLITE_WIN32_HAS_ANSI
38253   else{
38254     attr = osGetFileAttributesA((char*)zConverted);
38255   }
38256 #endif
38257   sqlite3_free(zConverted);
38258   switch( flags ){
38259     case SQLITE_ACCESS_READ:
38260     case SQLITE_ACCESS_EXISTS:
38261       rc = attr!=INVALID_FILE_ATTRIBUTES;
38262       break;
38263     case SQLITE_ACCESS_READWRITE:
38264       rc = attr!=INVALID_FILE_ATTRIBUTES &&
38265              (attr & FILE_ATTRIBUTE_READONLY)==0;
38266       break;
38267     default:
38268       assert(!"Invalid flags argument");
38269   }
38270   *pResOut = rc;
38271   OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
38272            zFilename, pResOut, *pResOut));
38273   return SQLITE_OK;
38274 }
38275 
38276 /*
38277 ** Returns non-zero if the specified path name starts with a drive letter
38278 ** followed by a colon character.
38279 */
38280 static BOOL winIsDriveLetterAndColon(
38281   const char *zPathname
38282 ){
38283   return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
38284 }
38285 
38286 /*
38287 ** Returns non-zero if the specified path name should be used verbatim.  If
38288 ** non-zero is returned from this function, the calling function must simply
38289 ** use the provided path name verbatim -OR- resolve it into a full path name
38290 ** using the GetFullPathName Win32 API function (if available).
38291 */
38292 static BOOL winIsVerbatimPathname(
38293   const char *zPathname
38294 ){
38295   /*
38296   ** If the path name starts with a forward slash or a backslash, it is either
38297   ** a legal UNC name, a volume relative path, or an absolute path name in the
38298   ** "Unix" format on Windows.  There is no easy way to differentiate between
38299   ** the final two cases; therefore, we return the safer return value of TRUE
38300   ** so that callers of this function will simply use it verbatim.
38301   */
38302   if ( winIsDirSep(zPathname[0]) ){
38303     return TRUE;
38304   }
38305 
38306   /*
38307   ** If the path name starts with a letter and a colon it is either a volume
38308   ** relative path or an absolute path.  Callers of this function must not
38309   ** attempt to treat it as a relative path name (i.e. they should simply use
38310   ** it verbatim).
38311   */
38312   if ( winIsDriveLetterAndColon(zPathname) ){
38313     return TRUE;
38314   }
38315 
38316   /*
38317   ** If we get to this point, the path name should almost certainly be a purely
38318   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
38319   */
38320   return FALSE;
38321 }
38322 
38323 /*
38324 ** Turn a relative pathname into a full pathname.  Write the full
38325 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
38326 ** bytes in size.
38327 */
38328 static int winFullPathname(
38329   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
38330   const char *zRelative,        /* Possibly relative input path */
38331   int nFull,                    /* Size of output buffer in bytes */
38332   char *zFull                   /* Output buffer */
38333 ){
38334 
38335 #if defined(__CYGWIN__)
38336   SimulateIOError( return SQLITE_ERROR );
38337   UNUSED_PARAMETER(nFull);
38338   assert( nFull>=pVfs->mxPathname );
38339   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
38340     /*
38341     ** NOTE: We are dealing with a relative path name and the data
38342     **       directory has been set.  Therefore, use it as the basis
38343     **       for converting the relative path name to an absolute
38344     **       one by prepending the data directory and a slash.
38345     */
38346     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
38347     if( !zOut ){
38348       return SQLITE_IOERR_NOMEM;
38349     }
38350     if( cygwin_conv_path(
38351             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
38352             CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
38353       sqlite3_free(zOut);
38354       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
38355                          "winFullPathname1", zRelative);
38356     }else{
38357       char *zUtf8 = winConvertToUtf8Filename(zOut);
38358       if( !zUtf8 ){
38359         sqlite3_free(zOut);
38360         return SQLITE_IOERR_NOMEM;
38361       }
38362       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
38363                        sqlite3_data_directory, winGetDirSep(), zUtf8);
38364       sqlite3_free(zUtf8);
38365       sqlite3_free(zOut);
38366     }
38367   }else{
38368     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
38369     if( !zOut ){
38370       return SQLITE_IOERR_NOMEM;
38371     }
38372     if( cygwin_conv_path(
38373             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
38374             zRelative, zOut, pVfs->mxPathname+1)<0 ){
38375       sqlite3_free(zOut);
38376       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
38377                          "winFullPathname2", zRelative);
38378     }else{
38379       char *zUtf8 = winConvertToUtf8Filename(zOut);
38380       if( !zUtf8 ){
38381         sqlite3_free(zOut);
38382         return SQLITE_IOERR_NOMEM;
38383       }
38384       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
38385       sqlite3_free(zUtf8);
38386       sqlite3_free(zOut);
38387     }
38388   }
38389   return SQLITE_OK;
38390 #endif
38391 
38392 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
38393   SimulateIOError( return SQLITE_ERROR );
38394   /* WinCE has no concept of a relative pathname, or so I am told. */
38395   /* WinRT has no way to convert a relative path to an absolute one. */
38396   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
38397     /*
38398     ** NOTE: We are dealing with a relative path name and the data
38399     **       directory has been set.  Therefore, use it as the basis
38400     **       for converting the relative path name to an absolute
38401     **       one by prepending the data directory and a backslash.
38402     */
38403     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
38404                      sqlite3_data_directory, winGetDirSep(), zRelative);
38405   }else{
38406     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
38407   }
38408   return SQLITE_OK;
38409 #endif
38410 
38411 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
38412   DWORD nByte;
38413   void *zConverted;
38414   char *zOut;
38415 
38416   /* If this path name begins with "/X:", where "X" is any alphabetic
38417   ** character, discard the initial "/" from the pathname.
38418   */
38419   if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
38420     zRelative++;
38421   }
38422 
38423   /* It's odd to simulate an io-error here, but really this is just
38424   ** using the io-error infrastructure to test that SQLite handles this
38425   ** function failing. This function could fail if, for example, the
38426   ** current working directory has been unlinked.
38427   */
38428   SimulateIOError( return SQLITE_ERROR );
38429   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
38430     /*
38431     ** NOTE: We are dealing with a relative path name and the data
38432     **       directory has been set.  Therefore, use it as the basis
38433     **       for converting the relative path name to an absolute
38434     **       one by prepending the data directory and a backslash.
38435     */
38436     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
38437                      sqlite3_data_directory, winGetDirSep(), zRelative);
38438     return SQLITE_OK;
38439   }
38440   zConverted = winConvertFromUtf8Filename(zRelative);
38441   if( zConverted==0 ){
38442     return SQLITE_IOERR_NOMEM;
38443   }
38444   if( osIsNT() ){
38445     LPWSTR zTemp;
38446     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
38447     if( nByte==0 ){
38448       sqlite3_free(zConverted);
38449       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
38450                          "winFullPathname1", zRelative);
38451     }
38452     nByte += 3;
38453     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
38454     if( zTemp==0 ){
38455       sqlite3_free(zConverted);
38456       return SQLITE_IOERR_NOMEM;
38457     }
38458     nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
38459     if( nByte==0 ){
38460       sqlite3_free(zConverted);
38461       sqlite3_free(zTemp);
38462       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
38463                          "winFullPathname2", zRelative);
38464     }
38465     sqlite3_free(zConverted);
38466     zOut = winUnicodeToUtf8(zTemp);
38467     sqlite3_free(zTemp);
38468   }
38469 #ifdef SQLITE_WIN32_HAS_ANSI
38470   else{
38471     char *zTemp;
38472     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
38473     if( nByte==0 ){
38474       sqlite3_free(zConverted);
38475       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
38476                          "winFullPathname3", zRelative);
38477     }
38478     nByte += 3;
38479     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
38480     if( zTemp==0 ){
38481       sqlite3_free(zConverted);
38482       return SQLITE_IOERR_NOMEM;
38483     }
38484     nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
38485     if( nByte==0 ){
38486       sqlite3_free(zConverted);
38487       sqlite3_free(zTemp);
38488       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
38489                          "winFullPathname4", zRelative);
38490     }
38491     sqlite3_free(zConverted);
38492     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
38493     sqlite3_free(zTemp);
38494   }
38495 #endif
38496   if( zOut ){
38497     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
38498     sqlite3_free(zOut);
38499     return SQLITE_OK;
38500   }else{
38501     return SQLITE_IOERR_NOMEM;
38502   }
38503 #endif
38504 }
38505 
38506 #ifndef SQLITE_OMIT_LOAD_EXTENSION
38507 /*
38508 ** Interfaces for opening a shared library, finding entry points
38509 ** within the shared library, and closing the shared library.
38510 */
38511 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
38512   HANDLE h;
38513 #if defined(__CYGWIN__)
38514   int nFull = pVfs->mxPathname+1;
38515   char *zFull = sqlite3MallocZero( nFull );
38516   void *zConverted = 0;
38517   if( zFull==0 ){
38518     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
38519     return 0;
38520   }
38521   if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
38522     sqlite3_free(zFull);
38523     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
38524     return 0;
38525   }
38526   zConverted = winConvertFromUtf8Filename(zFull);
38527   sqlite3_free(zFull);
38528 #else
38529   void *zConverted = winConvertFromUtf8Filename(zFilename);
38530   UNUSED_PARAMETER(pVfs);
38531 #endif
38532   if( zConverted==0 ){
38533     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
38534     return 0;
38535   }
38536   if( osIsNT() ){
38537 #if SQLITE_OS_WINRT
38538     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
38539 #else
38540     h = osLoadLibraryW((LPCWSTR)zConverted);
38541 #endif
38542   }
38543 #ifdef SQLITE_WIN32_HAS_ANSI
38544   else{
38545     h = osLoadLibraryA((char*)zConverted);
38546   }
38547 #endif
38548   OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
38549   sqlite3_free(zConverted);
38550   return (void*)h;
38551 }
38552 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
38553   UNUSED_PARAMETER(pVfs);
38554   winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
38555 }
38556 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
38557   FARPROC proc;
38558   UNUSED_PARAMETER(pVfs);
38559   proc = osGetProcAddressA((HANDLE)pH, zSym);
38560   OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
38561            (void*)pH, zSym, (void*)proc));
38562   return (void(*)(void))proc;
38563 }
38564 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
38565   UNUSED_PARAMETER(pVfs);
38566   osFreeLibrary((HANDLE)pHandle);
38567   OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
38568 }
38569 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
38570   #define winDlOpen  0
38571   #define winDlError 0
38572   #define winDlSym   0
38573   #define winDlClose 0
38574 #endif
38575 
38576 
38577 /*
38578 ** Write up to nBuf bytes of randomness into zBuf.
38579 */
38580 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
38581   int n = 0;
38582   UNUSED_PARAMETER(pVfs);
38583 #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
38584   n = nBuf;
38585   memset(zBuf, 0, nBuf);
38586 #else
38587   if( sizeof(SYSTEMTIME)<=nBuf-n ){
38588     SYSTEMTIME x;
38589     osGetSystemTime(&x);
38590     memcpy(&zBuf[n], &x, sizeof(x));
38591     n += sizeof(x);
38592   }
38593   if( sizeof(DWORD)<=nBuf-n ){
38594     DWORD pid = osGetCurrentProcessId();
38595     memcpy(&zBuf[n], &pid, sizeof(pid));
38596     n += sizeof(pid);
38597   }
38598 #if SQLITE_OS_WINRT
38599   if( sizeof(ULONGLONG)<=nBuf-n ){
38600     ULONGLONG cnt = osGetTickCount64();
38601     memcpy(&zBuf[n], &cnt, sizeof(cnt));
38602     n += sizeof(cnt);
38603   }
38604 #else
38605   if( sizeof(DWORD)<=nBuf-n ){
38606     DWORD cnt = osGetTickCount();
38607     memcpy(&zBuf[n], &cnt, sizeof(cnt));
38608     n += sizeof(cnt);
38609   }
38610 #endif
38611   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
38612     LARGE_INTEGER i;
38613     osQueryPerformanceCounter(&i);
38614     memcpy(&zBuf[n], &i, sizeof(i));
38615     n += sizeof(i);
38616   }
38617 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
38618   if( sizeof(UUID)<=nBuf-n ){
38619     UUID id;
38620     memset(&id, 0, sizeof(UUID));
38621     osUuidCreate(&id);
38622     memcpy(zBuf, &id, sizeof(UUID));
38623     n += sizeof(UUID);
38624   }
38625   if( sizeof(UUID)<=nBuf-n ){
38626     UUID id;
38627     memset(&id, 0, sizeof(UUID));
38628     osUuidCreateSequential(&id);
38629     memcpy(zBuf, &id, sizeof(UUID));
38630     n += sizeof(UUID);
38631   }
38632 #endif
38633 #endif /* defined(SQLITE_TEST) || defined(SQLITE_ZERO_PRNG_SEED) */
38634   return n;
38635 }
38636 
38637 
38638 /*
38639 ** Sleep for a little while.  Return the amount of time slept.
38640 */
38641 static int winSleep(sqlite3_vfs *pVfs, int microsec){
38642   sqlite3_win32_sleep((microsec+999)/1000);
38643   UNUSED_PARAMETER(pVfs);
38644   return ((microsec+999)/1000)*1000;
38645 }
38646 
38647 /*
38648 ** The following variable, if set to a non-zero value, is interpreted as
38649 ** the number of seconds since 1970 and is used to set the result of
38650 ** sqlite3OsCurrentTime() during testing.
38651 */
38652 #ifdef SQLITE_TEST
38653 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
38654 #endif
38655 
38656 /*
38657 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
38658 ** the current time and date as a Julian Day number times 86_400_000.  In
38659 ** other words, write into *piNow the number of milliseconds since the Julian
38660 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
38661 ** proleptic Gregorian calendar.
38662 **
38663 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
38664 ** cannot be found.
38665 */
38666 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
38667   /* FILETIME structure is a 64-bit value representing the number of
38668      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
38669   */
38670   FILETIME ft;
38671   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
38672 #ifdef SQLITE_TEST
38673   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
38674 #endif
38675   /* 2^32 - to avoid use of LL and warnings in gcc */
38676   static const sqlite3_int64 max32BitValue =
38677       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
38678       (sqlite3_int64)294967296;
38679 
38680 #if SQLITE_OS_WINCE
38681   SYSTEMTIME time;
38682   osGetSystemTime(&time);
38683   /* if SystemTimeToFileTime() fails, it returns zero. */
38684   if (!osSystemTimeToFileTime(&time,&ft)){
38685     return SQLITE_ERROR;
38686   }
38687 #else
38688   osGetSystemTimeAsFileTime( &ft );
38689 #endif
38690 
38691   *piNow = winFiletimeEpoch +
38692             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
38693                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
38694 
38695 #ifdef SQLITE_TEST
38696   if( sqlite3_current_time ){
38697     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
38698   }
38699 #endif
38700   UNUSED_PARAMETER(pVfs);
38701   return SQLITE_OK;
38702 }
38703 
38704 /*
38705 ** Find the current time (in Universal Coordinated Time).  Write the
38706 ** current time and date as a Julian Day number into *prNow and
38707 ** return 0.  Return 1 if the time and date cannot be found.
38708 */
38709 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
38710   int rc;
38711   sqlite3_int64 i;
38712   rc = winCurrentTimeInt64(pVfs, &i);
38713   if( !rc ){
38714     *prNow = i/86400000.0;
38715   }
38716   return rc;
38717 }
38718 
38719 /*
38720 ** The idea is that this function works like a combination of
38721 ** GetLastError() and FormatMessage() on Windows (or errno and
38722 ** strerror_r() on Unix). After an error is returned by an OS
38723 ** function, SQLite calls this function with zBuf pointing to
38724 ** a buffer of nBuf bytes. The OS layer should populate the
38725 ** buffer with a nul-terminated UTF-8 encoded error message
38726 ** describing the last IO error to have occurred within the calling
38727 ** thread.
38728 **
38729 ** If the error message is too large for the supplied buffer,
38730 ** it should be truncated. The return value of xGetLastError
38731 ** is zero if the error message fits in the buffer, or non-zero
38732 ** otherwise (if the message was truncated). If non-zero is returned,
38733 ** then it is not necessary to include the nul-terminator character
38734 ** in the output buffer.
38735 **
38736 ** Not supplying an error message will have no adverse effect
38737 ** on SQLite. It is fine to have an implementation that never
38738 ** returns an error message:
38739 **
38740 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
38741 **     assert(zBuf[0]=='\0');
38742 **     return 0;
38743 **   }
38744 **
38745 ** However if an error message is supplied, it will be incorporated
38746 ** by sqlite into the error message available to the user using
38747 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
38748 */
38749 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
38750   UNUSED_PARAMETER(pVfs);
38751   return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
38752 }
38753 
38754 /*
38755 ** Initialize and deinitialize the operating system interface.
38756 */
38757 SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
38758   static sqlite3_vfs winVfs = {
38759     3,                   /* iVersion */
38760     sizeof(winFile),     /* szOsFile */
38761     SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
38762     0,                   /* pNext */
38763     "win32",             /* zName */
38764     0,                   /* pAppData */
38765     winOpen,             /* xOpen */
38766     winDelete,           /* xDelete */
38767     winAccess,           /* xAccess */
38768     winFullPathname,     /* xFullPathname */
38769     winDlOpen,           /* xDlOpen */
38770     winDlError,          /* xDlError */
38771     winDlSym,            /* xDlSym */
38772     winDlClose,          /* xDlClose */
38773     winRandomness,       /* xRandomness */
38774     winSleep,            /* xSleep */
38775     winCurrentTime,      /* xCurrentTime */
38776     winGetLastError,     /* xGetLastError */
38777     winCurrentTimeInt64, /* xCurrentTimeInt64 */
38778     winSetSystemCall,    /* xSetSystemCall */
38779     winGetSystemCall,    /* xGetSystemCall */
38780     winNextSystemCall,   /* xNextSystemCall */
38781   };
38782 #if defined(SQLITE_WIN32_HAS_WIDE)
38783   static sqlite3_vfs winLongPathVfs = {
38784     3,                   /* iVersion */
38785     sizeof(winFile),     /* szOsFile */
38786     SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
38787     0,                   /* pNext */
38788     "win32-longpath",    /* zName */
38789     0,                   /* pAppData */
38790     winOpen,             /* xOpen */
38791     winDelete,           /* xDelete */
38792     winAccess,           /* xAccess */
38793     winFullPathname,     /* xFullPathname */
38794     winDlOpen,           /* xDlOpen */
38795     winDlError,          /* xDlError */
38796     winDlSym,            /* xDlSym */
38797     winDlClose,          /* xDlClose */
38798     winRandomness,       /* xRandomness */
38799     winSleep,            /* xSleep */
38800     winCurrentTime,      /* xCurrentTime */
38801     winGetLastError,     /* xGetLastError */
38802     winCurrentTimeInt64, /* xCurrentTimeInt64 */
38803     winSetSystemCall,    /* xSetSystemCall */
38804     winGetSystemCall,    /* xGetSystemCall */
38805     winNextSystemCall,   /* xNextSystemCall */
38806   };
38807 #endif
38808 
38809   /* Double-check that the aSyscall[] array has been constructed
38810   ** correctly.  See ticket [bb3a86e890c8e96ab] */
38811   assert( ArraySize(aSyscall)==80 );
38812 
38813   /* get memory map allocation granularity */
38814   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
38815 #if SQLITE_OS_WINRT
38816   osGetNativeSystemInfo(&winSysInfo);
38817 #else
38818   osGetSystemInfo(&winSysInfo);
38819 #endif
38820   assert( winSysInfo.dwAllocationGranularity>0 );
38821   assert( winSysInfo.dwPageSize>0 );
38822 
38823   sqlite3_vfs_register(&winVfs, 1);
38824 
38825 #if defined(SQLITE_WIN32_HAS_WIDE)
38826   sqlite3_vfs_register(&winLongPathVfs, 0);
38827 #endif
38828 
38829   return SQLITE_OK;
38830 }
38831 
38832 SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
38833 #if SQLITE_OS_WINRT
38834   if( sleepObj!=NULL ){
38835     osCloseHandle(sleepObj);
38836     sleepObj = NULL;
38837   }
38838 #endif
38839   return SQLITE_OK;
38840 }
38841 
38842 #endif /* SQLITE_OS_WIN */
38843 
38844 /************** End of os_win.c **********************************************/
38845 /************** Begin file bitvec.c ******************************************/
38846 /*
38847 ** 2008 February 16
38848 **
38849 ** The author disclaims copyright to this source code.  In place of
38850 ** a legal notice, here is a blessing:
38851 **
38852 **    May you do good and not evil.
38853 **    May you find forgiveness for yourself and forgive others.
38854 **    May you share freely, never taking more than you give.
38855 **
38856 *************************************************************************
38857 ** This file implements an object that represents a fixed-length
38858 ** bitmap.  Bits are numbered starting with 1.
38859 **
38860 ** A bitmap is used to record which pages of a database file have been
38861 ** journalled during a transaction, or which pages have the "dont-write"
38862 ** property.  Usually only a few pages are meet either condition.
38863 ** So the bitmap is usually sparse and has low cardinality.
38864 ** But sometimes (for example when during a DROP of a large table) most
38865 ** or all of the pages in a database can get journalled.  In those cases,
38866 ** the bitmap becomes dense with high cardinality.  The algorithm needs
38867 ** to handle both cases well.
38868 **
38869 ** The size of the bitmap is fixed when the object is created.
38870 **
38871 ** All bits are clear when the bitmap is created.  Individual bits
38872 ** may be set or cleared one at a time.
38873 **
38874 ** Test operations are about 100 times more common that set operations.
38875 ** Clear operations are exceedingly rare.  There are usually between
38876 ** 5 and 500 set operations per Bitvec object, though the number of sets can
38877 ** sometimes grow into tens of thousands or larger.  The size of the
38878 ** Bitvec object is the number of pages in the database file at the
38879 ** start of a transaction, and is thus usually less than a few thousand,
38880 ** but can be as large as 2 billion for a really big database.
38881 */
38882 
38883 /* Size of the Bitvec structure in bytes. */
38884 #define BITVEC_SZ        512
38885 
38886 /* Round the union size down to the nearest pointer boundary, since that's how
38887 ** it will be aligned within the Bitvec struct. */
38888 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
38889 
38890 /* Type of the array "element" for the bitmap representation.
38891 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
38892 ** Setting this to the "natural word" size of your CPU may improve
38893 ** performance. */
38894 #define BITVEC_TELEM     u8
38895 /* Size, in bits, of the bitmap element. */
38896 #define BITVEC_SZELEM    8
38897 /* Number of elements in a bitmap array. */
38898 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
38899 /* Number of bits in the bitmap array. */
38900 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
38901 
38902 /* Number of u32 values in hash table. */
38903 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
38904 /* Maximum number of entries in hash table before
38905 ** sub-dividing and re-hashing. */
38906 #define BITVEC_MXHASH    (BITVEC_NINT/2)
38907 /* Hashing function for the aHash representation.
38908 ** Empirical testing showed that the *37 multiplier
38909 ** (an arbitrary prime)in the hash function provided
38910 ** no fewer collisions than the no-op *1. */
38911 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
38912 
38913 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
38914 
38915 
38916 /*
38917 ** A bitmap is an instance of the following structure.
38918 **
38919 ** This bitmap records the existence of zero or more bits
38920 ** with values between 1 and iSize, inclusive.
38921 **
38922 ** There are three possible representations of the bitmap.
38923 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
38924 ** bitmap.  The least significant bit is bit 1.
38925 **
38926 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
38927 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
38928 **
38929 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
38930 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
38931 ** handles up to iDivisor separate values of i.  apSub[0] holds
38932 ** values between 1 and iDivisor.  apSub[1] holds values between
38933 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
38934 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
38935 ** to hold deal with values between 1 and iDivisor.
38936 */
38937 struct Bitvec {
38938   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
38939   u32 nSet;       /* Number of bits that are set - only valid for aHash
38940                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
38941                   ** this would be 125. */
38942   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
38943                   /* Should >=0 for apSub element. */
38944                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
38945                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
38946   union {
38947     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
38948     u32 aHash[BITVEC_NINT];      /* Hash table representation */
38949     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
38950   } u;
38951 };
38952 
38953 /*
38954 ** Create a new bitmap object able to handle bits between 0 and iSize,
38955 ** inclusive.  Return a pointer to the new object.  Return NULL if
38956 ** malloc fails.
38957 */
38958 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
38959   Bitvec *p;
38960   assert( sizeof(*p)==BITVEC_SZ );
38961   p = sqlite3MallocZero( sizeof(*p) );
38962   if( p ){
38963     p->iSize = iSize;
38964   }
38965   return p;
38966 }
38967 
38968 /*
38969 ** Check to see if the i-th bit is set.  Return true or false.
38970 ** If p is NULL (if the bitmap has not been created) or if
38971 ** i is out of range, then return false.
38972 */
38973 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
38974   if( p==0 ) return 0;
38975   if( i>p->iSize || i==0 ) return 0;
38976   i--;
38977   while( p->iDivisor ){
38978     u32 bin = i/p->iDivisor;
38979     i = i%p->iDivisor;
38980     p = p->u.apSub[bin];
38981     if (!p) {
38982       return 0;
38983     }
38984   }
38985   if( p->iSize<=BITVEC_NBIT ){
38986     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
38987   } else{
38988     u32 h = BITVEC_HASH(i++);
38989     while( p->u.aHash[h] ){
38990       if( p->u.aHash[h]==i ) return 1;
38991       h = (h+1) % BITVEC_NINT;
38992     }
38993     return 0;
38994   }
38995 }
38996 
38997 /*
38998 ** Set the i-th bit.  Return 0 on success and an error code if
38999 ** anything goes wrong.
39000 **
39001 ** This routine might cause sub-bitmaps to be allocated.  Failing
39002 ** to get the memory needed to hold the sub-bitmap is the only
39003 ** that can go wrong with an insert, assuming p and i are valid.
39004 **
39005 ** The calling function must ensure that p is a valid Bitvec object
39006 ** and that the value for "i" is within range of the Bitvec object.
39007 ** Otherwise the behavior is undefined.
39008 */
39009 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
39010   u32 h;
39011   if( p==0 ) return SQLITE_OK;
39012   assert( i>0 );
39013   assert( i<=p->iSize );
39014   i--;
39015   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
39016     u32 bin = i/p->iDivisor;
39017     i = i%p->iDivisor;
39018     if( p->u.apSub[bin]==0 ){
39019       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
39020       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
39021     }
39022     p = p->u.apSub[bin];
39023   }
39024   if( p->iSize<=BITVEC_NBIT ){
39025     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
39026     return SQLITE_OK;
39027   }
39028   h = BITVEC_HASH(i++);
39029   /* if there wasn't a hash collision, and this doesn't */
39030   /* completely fill the hash, then just add it without */
39031   /* worring about sub-dividing and re-hashing. */
39032   if( !p->u.aHash[h] ){
39033     if (p->nSet<(BITVEC_NINT-1)) {
39034       goto bitvec_set_end;
39035     } else {
39036       goto bitvec_set_rehash;
39037     }
39038   }
39039   /* there was a collision, check to see if it's already */
39040   /* in hash, if not, try to find a spot for it */
39041   do {
39042     if( p->u.aHash[h]==i ) return SQLITE_OK;
39043     h++;
39044     if( h>=BITVEC_NINT ) h = 0;
39045   } while( p->u.aHash[h] );
39046   /* we didn't find it in the hash.  h points to the first */
39047   /* available free spot. check to see if this is going to */
39048   /* make our hash too "full".  */
39049 bitvec_set_rehash:
39050   if( p->nSet>=BITVEC_MXHASH ){
39051     unsigned int j;
39052     int rc;
39053     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
39054     if( aiValues==0 ){
39055       return SQLITE_NOMEM;
39056     }else{
39057       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
39058       memset(p->u.apSub, 0, sizeof(p->u.apSub));
39059       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
39060       rc = sqlite3BitvecSet(p, i);
39061       for(j=0; j<BITVEC_NINT; j++){
39062         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
39063       }
39064       sqlite3StackFree(0, aiValues);
39065       return rc;
39066     }
39067   }
39068 bitvec_set_end:
39069   p->nSet++;
39070   p->u.aHash[h] = i;
39071   return SQLITE_OK;
39072 }
39073 
39074 /*
39075 ** Clear the i-th bit.
39076 **
39077 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
39078 ** that BitvecClear can use to rebuilt its hash table.
39079 */
39080 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
39081   if( p==0 ) return;
39082   assert( i>0 );
39083   i--;
39084   while( p->iDivisor ){
39085     u32 bin = i/p->iDivisor;
39086     i = i%p->iDivisor;
39087     p = p->u.apSub[bin];
39088     if (!p) {
39089       return;
39090     }
39091   }
39092   if( p->iSize<=BITVEC_NBIT ){
39093     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
39094   }else{
39095     unsigned int j;
39096     u32 *aiValues = pBuf;
39097     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
39098     memset(p->u.aHash, 0, sizeof(p->u.aHash));
39099     p->nSet = 0;
39100     for(j=0; j<BITVEC_NINT; j++){
39101       if( aiValues[j] && aiValues[j]!=(i+1) ){
39102         u32 h = BITVEC_HASH(aiValues[j]-1);
39103         p->nSet++;
39104         while( p->u.aHash[h] ){
39105           h++;
39106           if( h>=BITVEC_NINT ) h = 0;
39107         }
39108         p->u.aHash[h] = aiValues[j];
39109       }
39110     }
39111   }
39112 }
39113 
39114 /*
39115 ** Destroy a bitmap object.  Reclaim all memory used.
39116 */
39117 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
39118   if( p==0 ) return;
39119   if( p->iDivisor ){
39120     unsigned int i;
39121     for(i=0; i<BITVEC_NPTR; i++){
39122       sqlite3BitvecDestroy(p->u.apSub[i]);
39123     }
39124   }
39125   sqlite3_free(p);
39126 }
39127 
39128 /*
39129 ** Return the value of the iSize parameter specified when Bitvec *p
39130 ** was created.
39131 */
39132 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
39133   return p->iSize;
39134 }
39135 
39136 #ifndef SQLITE_OMIT_BUILTIN_TEST
39137 /*
39138 ** Let V[] be an array of unsigned characters sufficient to hold
39139 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
39140 ** Then the following macros can be used to set, clear, or test
39141 ** individual bits within V.
39142 */
39143 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
39144 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
39145 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
39146 
39147 /*
39148 ** This routine runs an extensive test of the Bitvec code.
39149 **
39150 ** The input is an array of integers that acts as a program
39151 ** to test the Bitvec.  The integers are opcodes followed
39152 ** by 0, 1, or 3 operands, depending on the opcode.  Another
39153 ** opcode follows immediately after the last operand.
39154 **
39155 ** There are 6 opcodes numbered from 0 through 5.  0 is the
39156 ** "halt" opcode and causes the test to end.
39157 **
39158 **    0          Halt and return the number of errors
39159 **    1 N S X    Set N bits beginning with S and incrementing by X
39160 **    2 N S X    Clear N bits beginning with S and incrementing by X
39161 **    3 N        Set N randomly chosen bits
39162 **    4 N        Clear N randomly chosen bits
39163 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
39164 **
39165 ** The opcodes 1 through 4 perform set and clear operations are performed
39166 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
39167 ** Opcode 5 works on the linear array only, not on the Bitvec.
39168 ** Opcode 5 is used to deliberately induce a fault in order to
39169 ** confirm that error detection works.
39170 **
39171 ** At the conclusion of the test the linear array is compared
39172 ** against the Bitvec object.  If there are any differences,
39173 ** an error is returned.  If they are the same, zero is returned.
39174 **
39175 ** If a memory allocation error occurs, return -1.
39176 */
39177 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
39178   Bitvec *pBitvec = 0;
39179   unsigned char *pV = 0;
39180   int rc = -1;
39181   int i, nx, pc, op;
39182   void *pTmpSpace;
39183 
39184   /* Allocate the Bitvec to be tested and a linear array of
39185   ** bits to act as the reference */
39186   pBitvec = sqlite3BitvecCreate( sz );
39187   pV = sqlite3MallocZero( (sz+7)/8 + 1 );
39188   pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
39189   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
39190 
39191   /* NULL pBitvec tests */
39192   sqlite3BitvecSet(0, 1);
39193   sqlite3BitvecClear(0, 1, pTmpSpace);
39194 
39195   /* Run the program */
39196   pc = 0;
39197   while( (op = aOp[pc])!=0 ){
39198     switch( op ){
39199       case 1:
39200       case 2:
39201       case 5: {
39202         nx = 4;
39203         i = aOp[pc+2] - 1;
39204         aOp[pc+2] += aOp[pc+3];
39205         break;
39206       }
39207       case 3:
39208       case 4:
39209       default: {
39210         nx = 2;
39211         sqlite3_randomness(sizeof(i), &i);
39212         break;
39213       }
39214     }
39215     if( (--aOp[pc+1]) > 0 ) nx = 0;
39216     pc += nx;
39217     i = (i & 0x7fffffff)%sz;
39218     if( (op & 1)!=0 ){
39219       SETBIT(pV, (i+1));
39220       if( op!=5 ){
39221         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
39222       }
39223     }else{
39224       CLEARBIT(pV, (i+1));
39225       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
39226     }
39227   }
39228 
39229   /* Test to make sure the linear array exactly matches the
39230   ** Bitvec object.  Start with the assumption that they do
39231   ** match (rc==0).  Change rc to non-zero if a discrepancy
39232   ** is found.
39233   */
39234   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
39235           + sqlite3BitvecTest(pBitvec, 0)
39236           + (sqlite3BitvecSize(pBitvec) - sz);
39237   for(i=1; i<=sz; i++){
39238     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
39239       rc = i;
39240       break;
39241     }
39242   }
39243 
39244   /* Free allocated structure */
39245 bitvec_end:
39246   sqlite3_free(pTmpSpace);
39247   sqlite3_free(pV);
39248   sqlite3BitvecDestroy(pBitvec);
39249   return rc;
39250 }
39251 #endif /* SQLITE_OMIT_BUILTIN_TEST */
39252 
39253 /************** End of bitvec.c **********************************************/
39254 /************** Begin file pcache.c ******************************************/
39255 /*
39256 ** 2008 August 05
39257 **
39258 ** The author disclaims copyright to this source code.  In place of
39259 ** a legal notice, here is a blessing:
39260 **
39261 **    May you do good and not evil.
39262 **    May you find forgiveness for yourself and forgive others.
39263 **    May you share freely, never taking more than you give.
39264 **
39265 *************************************************************************
39266 ** This file implements that page cache.
39267 */
39268 
39269 /*
39270 ** A complete page cache is an instance of this structure.
39271 */
39272 struct PCache {
39273   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
39274   PgHdr *pSynced;                     /* Last synced page in dirty page list */
39275   int nRef;                           /* Number of referenced pages */
39276   int szCache;                        /* Configured cache size */
39277   int szPage;                         /* Size of every page in this cache */
39278   int szExtra;                        /* Size of extra space for each page */
39279   u8 bPurgeable;                      /* True if pages are on backing store */
39280   u8 eCreate;                         /* eCreate value for for xFetch() */
39281   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
39282   void *pStress;                      /* Argument to xStress */
39283   sqlite3_pcache *pCache;             /* Pluggable cache module */
39284   PgHdr *pPage1;                      /* Reference to page 1 */
39285 };
39286 
39287 /********************************** Linked List Management ********************/
39288 
39289 /* Allowed values for second argument to pcacheManageDirtyList() */
39290 #define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */
39291 #define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */
39292 #define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */
39293 
39294 /*
39295 ** Manage pPage's participation on the dirty list.  Bits of the addRemove
39296 ** argument determines what operation to do.  The 0x01 bit means first
39297 ** remove pPage from the dirty list.  The 0x02 means add pPage back to
39298 ** the dirty list.  Doing both moves pPage to the front of the dirty list.
39299 */
39300 static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
39301   PCache *p = pPage->pCache;
39302 
39303   if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
39304     assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
39305     assert( pPage->pDirtyPrev || pPage==p->pDirty );
39306 
39307     /* Update the PCache1.pSynced variable if necessary. */
39308     if( p->pSynced==pPage ){
39309       PgHdr *pSynced = pPage->pDirtyPrev;
39310       while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
39311         pSynced = pSynced->pDirtyPrev;
39312       }
39313       p->pSynced = pSynced;
39314     }
39315 
39316     if( pPage->pDirtyNext ){
39317       pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
39318     }else{
39319       assert( pPage==p->pDirtyTail );
39320       p->pDirtyTail = pPage->pDirtyPrev;
39321     }
39322     if( pPage->pDirtyPrev ){
39323       pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
39324     }else{
39325       assert( pPage==p->pDirty );
39326       p->pDirty = pPage->pDirtyNext;
39327       if( p->pDirty==0 && p->bPurgeable ){
39328         assert( p->eCreate==1 );
39329         p->eCreate = 2;
39330       }
39331     }
39332     pPage->pDirtyNext = 0;
39333     pPage->pDirtyPrev = 0;
39334   }
39335   if( addRemove & PCACHE_DIRTYLIST_ADD ){
39336     assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
39337 
39338     pPage->pDirtyNext = p->pDirty;
39339     if( pPage->pDirtyNext ){
39340       assert( pPage->pDirtyNext->pDirtyPrev==0 );
39341       pPage->pDirtyNext->pDirtyPrev = pPage;
39342     }else{
39343       p->pDirtyTail = pPage;
39344       if( p->bPurgeable ){
39345         assert( p->eCreate==2 );
39346         p->eCreate = 1;
39347       }
39348     }
39349     p->pDirty = pPage;
39350     if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
39351       p->pSynced = pPage;
39352     }
39353   }
39354 }
39355 
39356 /*
39357 ** Wrapper around the pluggable caches xUnpin method. If the cache is
39358 ** being used for an in-memory database, this function is a no-op.
39359 */
39360 static void pcacheUnpin(PgHdr *p){
39361   if( p->pCache->bPurgeable ){
39362     if( p->pgno==1 ){
39363       p->pCache->pPage1 = 0;
39364     }
39365     sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
39366   }
39367 }
39368 
39369 /*
39370 ** Compute the number of pages of cache requested.  p->szCache is the
39371 ** cache size requested by the "PRAGMA cache_size" statement.
39372 **
39373 **
39374 */
39375 static int numberOfCachePages(PCache *p){
39376   if( p->szCache>=0 ){
39377     /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
39378     ** suggested cache size is set to N. */
39379     return p->szCache;
39380   }else{
39381     /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
39382     ** the number of cache pages is adjusted to use approximately abs(N*1024)
39383     ** bytes of memory. */
39384     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
39385   }
39386 }
39387 
39388 /*************************************************** General Interfaces ******
39389 **
39390 ** Initialize and shutdown the page cache subsystem. Neither of these
39391 ** functions are threadsafe.
39392 */
39393 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
39394   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
39395     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
39396     ** built-in default page cache is used instead of the application defined
39397     ** page cache. */
39398     sqlite3PCacheSetDefault();
39399   }
39400   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
39401 }
39402 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
39403   if( sqlite3GlobalConfig.pcache2.xShutdown ){
39404     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
39405     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
39406   }
39407 }
39408 
39409 /*
39410 ** Return the size in bytes of a PCache object.
39411 */
39412 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
39413 
39414 /*
39415 ** Create a new PCache object. Storage space to hold the object
39416 ** has already been allocated and is passed in as the p pointer.
39417 ** The caller discovers how much space needs to be allocated by
39418 ** calling sqlite3PcacheSize().
39419 */
39420 SQLITE_PRIVATE int sqlite3PcacheOpen(
39421   int szPage,                  /* Size of every page */
39422   int szExtra,                 /* Extra space associated with each page */
39423   int bPurgeable,              /* True if pages are on backing store */
39424   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
39425   void *pStress,               /* Argument to xStress */
39426   PCache *p                    /* Preallocated space for the PCache */
39427 ){
39428   memset(p, 0, sizeof(PCache));
39429   p->szPage = 1;
39430   p->szExtra = szExtra;
39431   p->bPurgeable = bPurgeable;
39432   p->eCreate = 2;
39433   p->xStress = xStress;
39434   p->pStress = pStress;
39435   p->szCache = 100;
39436   return sqlite3PcacheSetPageSize(p, szPage);
39437 }
39438 
39439 /*
39440 ** Change the page size for PCache object. The caller must ensure that there
39441 ** are no outstanding page references when this function is called.
39442 */
39443 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
39444   assert( pCache->nRef==0 && pCache->pDirty==0 );
39445   if( pCache->szPage ){
39446     sqlite3_pcache *pNew;
39447     pNew = sqlite3GlobalConfig.pcache2.xCreate(
39448                 szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
39449                 pCache->bPurgeable
39450     );
39451     if( pNew==0 ) return SQLITE_NOMEM;
39452     sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
39453     if( pCache->pCache ){
39454       sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
39455     }
39456     pCache->pCache = pNew;
39457     pCache->pPage1 = 0;
39458     pCache->szPage = szPage;
39459   }
39460   return SQLITE_OK;
39461 }
39462 
39463 /*
39464 ** Try to obtain a page from the cache.
39465 **
39466 ** This routine returns a pointer to an sqlite3_pcache_page object if
39467 ** such an object is already in cache, or if a new one is created.
39468 ** This routine returns a NULL pointer if the object was not in cache
39469 ** and could not be created.
39470 **
39471 ** The createFlags should be 0 to check for existing pages and should
39472 ** be 3 (not 1, but 3) to try to create a new page.
39473 **
39474 ** If the createFlag is 0, then NULL is always returned if the page
39475 ** is not already in the cache.  If createFlag is 1, then a new page
39476 ** is created only if that can be done without spilling dirty pages
39477 ** and without exceeding the cache size limit.
39478 **
39479 ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
39480 ** initialize the sqlite3_pcache_page object and convert it into a
39481 ** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
39482 ** routines are split this way for performance reasons. When separated
39483 ** they can both (usually) operate without having to push values to
39484 ** the stack on entry and pop them back off on exit, which saves a
39485 ** lot of pushing and popping.
39486 */
39487 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
39488   PCache *pCache,       /* Obtain the page from this cache */
39489   Pgno pgno,            /* Page number to obtain */
39490   int createFlag        /* If true, create page if it does not exist already */
39491 ){
39492   int eCreate;
39493 
39494   assert( pCache!=0 );
39495   assert( pCache->pCache!=0 );
39496   assert( createFlag==3 || createFlag==0 );
39497   assert( pgno>0 );
39498 
39499   /* eCreate defines what to do if the page does not exist.
39500   **    0     Do not allocate a new page.  (createFlag==0)
39501   **    1     Allocate a new page if doing so is inexpensive.
39502   **          (createFlag==1 AND bPurgeable AND pDirty)
39503   **    2     Allocate a new page even it doing so is difficult.
39504   **          (createFlag==1 AND !(bPurgeable AND pDirty)
39505   */
39506   eCreate = createFlag & pCache->eCreate;
39507   assert( eCreate==0 || eCreate==1 || eCreate==2 );
39508   assert( createFlag==0 || pCache->eCreate==eCreate );
39509   assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
39510   return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
39511 }
39512 
39513 /*
39514 ** If the sqlite3PcacheFetch() routine is unable to allocate a new
39515 ** page because new clean pages are available for reuse and the cache
39516 ** size limit has been reached, then this routine can be invoked to
39517 ** try harder to allocate a page.  This routine might invoke the stress
39518 ** callback to spill dirty pages to the journal.  It will then try to
39519 ** allocate the new page and will only fail to allocate a new page on
39520 ** an OOM error.
39521 **
39522 ** This routine should be invoked only after sqlite3PcacheFetch() fails.
39523 */
39524 SQLITE_PRIVATE int sqlite3PcacheFetchStress(
39525   PCache *pCache,                 /* Obtain the page from this cache */
39526   Pgno pgno,                      /* Page number to obtain */
39527   sqlite3_pcache_page **ppPage    /* Write result here */
39528 ){
39529   PgHdr *pPg;
39530   if( pCache->eCreate==2 ) return 0;
39531 
39532 
39533   /* Find a dirty page to write-out and recycle. First try to find a
39534   ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
39535   ** cleared), but if that is not possible settle for any other
39536   ** unreferenced dirty page.
39537   */
39538   for(pPg=pCache->pSynced;
39539       pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
39540       pPg=pPg->pDirtyPrev
39541   );
39542   pCache->pSynced = pPg;
39543   if( !pPg ){
39544     for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
39545   }
39546   if( pPg ){
39547     int rc;
39548 #ifdef SQLITE_LOG_CACHE_SPILL
39549     sqlite3_log(SQLITE_FULL,
39550                 "spill page %d making room for %d - cache used: %d/%d",
39551                 pPg->pgno, pgno,
39552                 sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
39553                 numberOfCachePages(pCache));
39554 #endif
39555     rc = pCache->xStress(pCache->pStress, pPg);
39556     if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
39557       return rc;
39558     }
39559   }
39560   *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
39561   return *ppPage==0 ? SQLITE_NOMEM : SQLITE_OK;
39562 }
39563 
39564 /*
39565 ** This is a helper routine for sqlite3PcacheFetchFinish()
39566 **
39567 ** In the uncommon case where the page being fetched has not been
39568 ** initialized, this routine is invoked to do the initialization.
39569 ** This routine is broken out into a separate function since it
39570 ** requires extra stack manipulation that can be avoided in the common
39571 ** case.
39572 */
39573 static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
39574   PCache *pCache,             /* Obtain the page from this cache */
39575   Pgno pgno,                  /* Page number obtained */
39576   sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
39577 ){
39578   PgHdr *pPgHdr;
39579   assert( pPage!=0 );
39580   pPgHdr = (PgHdr*)pPage->pExtra;
39581   assert( pPgHdr->pPage==0 );
39582  memset(pPgHdr, 0, sizeof(PgHdr));
39583   pPgHdr->pPage = pPage;
39584   pPgHdr->pData = pPage->pBuf;
39585   pPgHdr->pExtra = (void *)&pPgHdr[1];
39586   memset(pPgHdr->pExtra, 0, pCache->szExtra);
39587   pPgHdr->pCache = pCache;
39588   pPgHdr->pgno = pgno;
39589   return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
39590 }
39591 
39592 /*
39593 ** This routine converts the sqlite3_pcache_page object returned by
39594 ** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine
39595 ** must be called after sqlite3PcacheFetch() in order to get a usable
39596 ** result.
39597 */
39598 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
39599   PCache *pCache,             /* Obtain the page from this cache */
39600   Pgno pgno,                  /* Page number obtained */
39601   sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
39602 ){
39603   PgHdr *pPgHdr;
39604 
39605   if( pPage==0 ) return 0;
39606   pPgHdr = (PgHdr *)pPage->pExtra;
39607 
39608   if( !pPgHdr->pPage ){
39609     return pcacheFetchFinishWithInit(pCache, pgno, pPage);
39610   }
39611   if( 0==pPgHdr->nRef ){
39612     pCache->nRef++;
39613   }
39614   pPgHdr->nRef++;
39615   if( pgno==1 ){
39616     pCache->pPage1 = pPgHdr;
39617   }
39618   return pPgHdr;
39619 }
39620 
39621 /*
39622 ** Decrement the reference count on a page. If the page is clean and the
39623 ** reference count drops to 0, then it is made eligible for recycling.
39624 */
39625 SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
39626   assert( p->nRef>0 );
39627   p->nRef--;
39628   if( p->nRef==0 ){
39629     p->pCache->nRef--;
39630     if( (p->flags&PGHDR_DIRTY)==0 ){
39631       pcacheUnpin(p);
39632     }else if( p->pDirtyPrev!=0 ){
39633       /* Move the page to the head of the dirty list. */
39634       pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
39635     }
39636   }
39637 }
39638 
39639 /*
39640 ** Increase the reference count of a supplied page by 1.
39641 */
39642 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
39643   assert(p->nRef>0);
39644   p->nRef++;
39645 }
39646 
39647 /*
39648 ** Drop a page from the cache. There must be exactly one reference to the
39649 ** page. This function deletes that reference, so after it returns the
39650 ** page pointed to by p is invalid.
39651 */
39652 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
39653   assert( p->nRef==1 );
39654   if( p->flags&PGHDR_DIRTY ){
39655     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
39656   }
39657   p->pCache->nRef--;
39658   if( p->pgno==1 ){
39659     p->pCache->pPage1 = 0;
39660   }
39661   sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
39662 }
39663 
39664 /*
39665 ** Make sure the page is marked as dirty. If it isn't dirty already,
39666 ** make it so.
39667 */
39668 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
39669   p->flags &= ~PGHDR_DONT_WRITE;
39670   assert( p->nRef>0 );
39671   if( 0==(p->flags & PGHDR_DIRTY) ){
39672     p->flags |= PGHDR_DIRTY;
39673     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
39674   }
39675 }
39676 
39677 /*
39678 ** Make sure the page is marked as clean. If it isn't clean already,
39679 ** make it so.
39680 */
39681 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
39682   if( (p->flags & PGHDR_DIRTY) ){
39683     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
39684     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
39685     if( p->nRef==0 ){
39686       pcacheUnpin(p);
39687     }
39688   }
39689 }
39690 
39691 /*
39692 ** Make every page in the cache clean.
39693 */
39694 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
39695   PgHdr *p;
39696   while( (p = pCache->pDirty)!=0 ){
39697     sqlite3PcacheMakeClean(p);
39698   }
39699 }
39700 
39701 /*
39702 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
39703 */
39704 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
39705   PgHdr *p;
39706   for(p=pCache->pDirty; p; p=p->pDirtyNext){
39707     p->flags &= ~PGHDR_NEED_SYNC;
39708   }
39709   pCache->pSynced = pCache->pDirtyTail;
39710 }
39711 
39712 /*
39713 ** Change the page number of page p to newPgno.
39714 */
39715 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
39716   PCache *pCache = p->pCache;
39717   assert( p->nRef>0 );
39718   assert( newPgno>0 );
39719   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
39720   p->pgno = newPgno;
39721   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
39722     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
39723   }
39724 }
39725 
39726 /*
39727 ** Drop every cache entry whose page number is greater than "pgno". The
39728 ** caller must ensure that there are no outstanding references to any pages
39729 ** other than page 1 with a page number greater than pgno.
39730 **
39731 ** If there is a reference to page 1 and the pgno parameter passed to this
39732 ** function is 0, then the data area associated with page 1 is zeroed, but
39733 ** the page object is not dropped.
39734 */
39735 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
39736   if( pCache->pCache ){
39737     PgHdr *p;
39738     PgHdr *pNext;
39739     for(p=pCache->pDirty; p; p=pNext){
39740       pNext = p->pDirtyNext;
39741       /* This routine never gets call with a positive pgno except right
39742       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
39743       ** it must be that pgno==0.
39744       */
39745       assert( p->pgno>0 );
39746       if( ALWAYS(p->pgno>pgno) ){
39747         assert( p->flags&PGHDR_DIRTY );
39748         sqlite3PcacheMakeClean(p);
39749       }
39750     }
39751     if( pgno==0 && pCache->pPage1 ){
39752       memset(pCache->pPage1->pData, 0, pCache->szPage);
39753       pgno = 1;
39754     }
39755     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
39756   }
39757 }
39758 
39759 /*
39760 ** Close a cache.
39761 */
39762 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
39763   assert( pCache->pCache!=0 );
39764   sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
39765 }
39766 
39767 /*
39768 ** Discard the contents of the cache.
39769 */
39770 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
39771   sqlite3PcacheTruncate(pCache, 0);
39772 }
39773 
39774 /*
39775 ** Merge two lists of pages connected by pDirty and in pgno order.
39776 ** Do not both fixing the pDirtyPrev pointers.
39777 */
39778 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
39779   PgHdr result, *pTail;
39780   pTail = &result;
39781   while( pA && pB ){
39782     if( pA->pgno<pB->pgno ){
39783       pTail->pDirty = pA;
39784       pTail = pA;
39785       pA = pA->pDirty;
39786     }else{
39787       pTail->pDirty = pB;
39788       pTail = pB;
39789       pB = pB->pDirty;
39790     }
39791   }
39792   if( pA ){
39793     pTail->pDirty = pA;
39794   }else if( pB ){
39795     pTail->pDirty = pB;
39796   }else{
39797     pTail->pDirty = 0;
39798   }
39799   return result.pDirty;
39800 }
39801 
39802 /*
39803 ** Sort the list of pages in accending order by pgno.  Pages are
39804 ** connected by pDirty pointers.  The pDirtyPrev pointers are
39805 ** corrupted by this sort.
39806 **
39807 ** Since there cannot be more than 2^31 distinct pages in a database,
39808 ** there cannot be more than 31 buckets required by the merge sorter.
39809 ** One extra bucket is added to catch overflow in case something
39810 ** ever changes to make the previous sentence incorrect.
39811 */
39812 #define N_SORT_BUCKET  32
39813 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
39814   PgHdr *a[N_SORT_BUCKET], *p;
39815   int i;
39816   memset(a, 0, sizeof(a));
39817   while( pIn ){
39818     p = pIn;
39819     pIn = p->pDirty;
39820     p->pDirty = 0;
39821     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
39822       if( a[i]==0 ){
39823         a[i] = p;
39824         break;
39825       }else{
39826         p = pcacheMergeDirtyList(a[i], p);
39827         a[i] = 0;
39828       }
39829     }
39830     if( NEVER(i==N_SORT_BUCKET-1) ){
39831       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
39832       ** the input list.  But that is impossible.
39833       */
39834       a[i] = pcacheMergeDirtyList(a[i], p);
39835     }
39836   }
39837   p = a[0];
39838   for(i=1; i<N_SORT_BUCKET; i++){
39839     p = pcacheMergeDirtyList(p, a[i]);
39840   }
39841   return p;
39842 }
39843 
39844 /*
39845 ** Return a list of all dirty pages in the cache, sorted by page number.
39846 */
39847 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
39848   PgHdr *p;
39849   for(p=pCache->pDirty; p; p=p->pDirtyNext){
39850     p->pDirty = p->pDirtyNext;
39851   }
39852   return pcacheSortDirtyList(pCache->pDirty);
39853 }
39854 
39855 /*
39856 ** Return the total number of referenced pages held by the cache.
39857 */
39858 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
39859   return pCache->nRef;
39860 }
39861 
39862 /*
39863 ** Return the number of references to the page supplied as an argument.
39864 */
39865 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
39866   return p->nRef;
39867 }
39868 
39869 /*
39870 ** Return the total number of pages in the cache.
39871 */
39872 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
39873   assert( pCache->pCache!=0 );
39874   return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
39875 }
39876 
39877 #ifdef SQLITE_TEST
39878 /*
39879 ** Get the suggested cache-size value.
39880 */
39881 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
39882   return numberOfCachePages(pCache);
39883 }
39884 #endif
39885 
39886 /*
39887 ** Set the suggested cache-size value.
39888 */
39889 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
39890   assert( pCache->pCache!=0 );
39891   pCache->szCache = mxPage;
39892   sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
39893                                          numberOfCachePages(pCache));
39894 }
39895 
39896 /*
39897 ** Free up as much memory as possible from the page cache.
39898 */
39899 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
39900   assert( pCache->pCache!=0 );
39901   sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
39902 }
39903 
39904 /*
39905 ** Return the size of the header added by this middleware layer
39906 ** in the page-cache hierarchy.
39907 */
39908 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
39909 
39910 
39911 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
39912 /*
39913 ** For all dirty pages currently in the cache, invoke the specified
39914 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
39915 ** defined.
39916 */
39917 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
39918   PgHdr *pDirty;
39919   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
39920     xIter(pDirty);
39921   }
39922 }
39923 #endif
39924 
39925 /************** End of pcache.c **********************************************/
39926 /************** Begin file pcache1.c *****************************************/
39927 /*
39928 ** 2008 November 05
39929 **
39930 ** The author disclaims copyright to this source code.  In place of
39931 ** a legal notice, here is a blessing:
39932 **
39933 **    May you do good and not evil.
39934 **    May you find forgiveness for yourself and forgive others.
39935 **    May you share freely, never taking more than you give.
39936 **
39937 *************************************************************************
39938 **
39939 ** This file implements the default page cache implementation (the
39940 ** sqlite3_pcache interface). It also contains part of the implementation
39941 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
39942 ** If the default page cache implementation is overridden, then neither of
39943 ** these two features are available.
39944 */
39945 
39946 
39947 typedef struct PCache1 PCache1;
39948 typedef struct PgHdr1 PgHdr1;
39949 typedef struct PgFreeslot PgFreeslot;
39950 typedef struct PGroup PGroup;
39951 
39952 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
39953 ** of one or more PCaches that are able to recycle each other's unpinned
39954 ** pages when they are under memory pressure.  A PGroup is an instance of
39955 ** the following object.
39956 **
39957 ** This page cache implementation works in one of two modes:
39958 **
39959 **   (1)  Every PCache is the sole member of its own PGroup.  There is
39960 **        one PGroup per PCache.
39961 **
39962 **   (2)  There is a single global PGroup that all PCaches are a member
39963 **        of.
39964 **
39965 ** Mode 1 uses more memory (since PCache instances are not able to rob
39966 ** unused pages from other PCaches) but it also operates without a mutex,
39967 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
39968 ** threadsafe, but recycles pages more efficiently.
39969 **
39970 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
39971 ** PGroup which is the pcache1.grp global variable and its mutex is
39972 ** SQLITE_MUTEX_STATIC_LRU.
39973 */
39974 struct PGroup {
39975   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
39976   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
39977   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
39978   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
39979   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
39980   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
39981 };
39982 
39983 /* Each page cache is an instance of the following object.  Every
39984 ** open database file (including each in-memory database and each
39985 ** temporary or transient database) has a single page cache which
39986 ** is an instance of this object.
39987 **
39988 ** Pointers to structures of this type are cast and returned as
39989 ** opaque sqlite3_pcache* handles.
39990 */
39991 struct PCache1 {
39992   /* Cache configuration parameters. Page size (szPage) and the purgeable
39993   ** flag (bPurgeable) are set when the cache is created. nMax may be
39994   ** modified at any time by a call to the pcache1Cachesize() method.
39995   ** The PGroup mutex must be held when accessing nMax.
39996   */
39997   PGroup *pGroup;                     /* PGroup this cache belongs to */
39998   int szPage;                         /* Size of allocated pages in bytes */
39999   int szExtra;                        /* Size of extra space in bytes */
40000   int bPurgeable;                     /* True if cache is purgeable */
40001   unsigned int nMin;                  /* Minimum number of pages reserved */
40002   unsigned int nMax;                  /* Configured "cache_size" value */
40003   unsigned int n90pct;                /* nMax*9/10 */
40004   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
40005 
40006   /* Hash table of all pages. The following variables may only be accessed
40007   ** when the accessor is holding the PGroup mutex.
40008   */
40009   unsigned int nRecyclable;           /* Number of pages in the LRU list */
40010   unsigned int nPage;                 /* Total number of pages in apHash */
40011   unsigned int nHash;                 /* Number of slots in apHash[] */
40012   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
40013 };
40014 
40015 /*
40016 ** Each cache entry is represented by an instance of the following
40017 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
40018 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
40019 ** in memory.
40020 */
40021 struct PgHdr1 {
40022   sqlite3_pcache_page page;
40023   unsigned int iKey;             /* Key value (page number) */
40024   u8 isPinned;                   /* Page in use, not on the LRU list */
40025   PgHdr1 *pNext;                 /* Next in hash table chain */
40026   PCache1 *pCache;               /* Cache that currently owns this page */
40027   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
40028   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
40029 };
40030 
40031 /*
40032 ** Free slots in the allocator used to divide up the buffer provided using
40033 ** the SQLITE_CONFIG_PAGECACHE mechanism.
40034 */
40035 struct PgFreeslot {
40036   PgFreeslot *pNext;  /* Next free slot */
40037 };
40038 
40039 /*
40040 ** Global data used by this cache.
40041 */
40042 static SQLITE_WSD struct PCacheGlobal {
40043   PGroup grp;                    /* The global PGroup for mode (2) */
40044 
40045   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
40046   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
40047   ** fixed at sqlite3_initialize() time and do not require mutex protection.
40048   ** The nFreeSlot and pFree values do require mutex protection.
40049   */
40050   int isInit;                    /* True if initialized */
40051   int szSlot;                    /* Size of each free slot */
40052   int nSlot;                     /* The number of pcache slots */
40053   int nReserve;                  /* Try to keep nFreeSlot above this */
40054   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
40055   /* Above requires no mutex.  Use mutex below for variable that follow. */
40056   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
40057   PgFreeslot *pFree;             /* Free page blocks */
40058   int nFreeSlot;                 /* Number of unused pcache slots */
40059   /* The following value requires a mutex to change.  We skip the mutex on
40060   ** reading because (1) most platforms read a 32-bit integer atomically and
40061   ** (2) even if an incorrect value is read, no great harm is done since this
40062   ** is really just an optimization. */
40063   int bUnderPressure;            /* True if low on PAGECACHE memory */
40064 } pcache1_g;
40065 
40066 /*
40067 ** All code in this file should access the global structure above via the
40068 ** alias "pcache1". This ensures that the WSD emulation is used when
40069 ** compiling for systems that do not support real WSD.
40070 */
40071 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
40072 
40073 /*
40074 ** Macros to enter and leave the PCache LRU mutex.
40075 */
40076 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
40077 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
40078 
40079 /******************************************************************************/
40080 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
40081 
40082 /*
40083 ** This function is called during initialization if a static buffer is
40084 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
40085 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
40086 ** enough to contain 'n' buffers of 'sz' bytes each.
40087 **
40088 ** This routine is called from sqlite3_initialize() and so it is guaranteed
40089 ** to be serialized already.  There is no need for further mutexing.
40090 */
40091 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
40092   if( pcache1.isInit ){
40093     PgFreeslot *p;
40094     sz = ROUNDDOWN8(sz);
40095     pcache1.szSlot = sz;
40096     pcache1.nSlot = pcache1.nFreeSlot = n;
40097     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
40098     pcache1.pStart = pBuf;
40099     pcache1.pFree = 0;
40100     pcache1.bUnderPressure = 0;
40101     while( n-- ){
40102       p = (PgFreeslot*)pBuf;
40103       p->pNext = pcache1.pFree;
40104       pcache1.pFree = p;
40105       pBuf = (void*)&((char*)pBuf)[sz];
40106     }
40107     pcache1.pEnd = pBuf;
40108   }
40109 }
40110 
40111 /*
40112 ** Malloc function used within this file to allocate space from the buffer
40113 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
40114 ** such buffer exists or there is no space left in it, this function falls
40115 ** back to sqlite3Malloc().
40116 **
40117 ** Multiple threads can run this routine at the same time.  Global variables
40118 ** in pcache1 need to be protected via mutex.
40119 */
40120 static void *pcache1Alloc(int nByte){
40121   void *p = 0;
40122   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
40123   if( nByte<=pcache1.szSlot ){
40124     sqlite3_mutex_enter(pcache1.mutex);
40125     p = (PgHdr1 *)pcache1.pFree;
40126     if( p ){
40127       pcache1.pFree = pcache1.pFree->pNext;
40128       pcache1.nFreeSlot--;
40129       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
40130       assert( pcache1.nFreeSlot>=0 );
40131       sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
40132       sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
40133     }
40134     sqlite3_mutex_leave(pcache1.mutex);
40135   }
40136   if( p==0 ){
40137     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
40138     ** it from sqlite3Malloc instead.
40139     */
40140     p = sqlite3Malloc(nByte);
40141 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
40142     if( p ){
40143       int sz = sqlite3MallocSize(p);
40144       sqlite3_mutex_enter(pcache1.mutex);
40145       sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
40146       sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
40147       sqlite3_mutex_leave(pcache1.mutex);
40148     }
40149 #endif
40150     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
40151   }
40152   return p;
40153 }
40154 
40155 /*
40156 ** Free an allocated buffer obtained from pcache1Alloc().
40157 */
40158 static int pcache1Free(void *p){
40159   int nFreed = 0;
40160   if( p==0 ) return 0;
40161   if( p>=pcache1.pStart && p<pcache1.pEnd ){
40162     PgFreeslot *pSlot;
40163     sqlite3_mutex_enter(pcache1.mutex);
40164     sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
40165     pSlot = (PgFreeslot*)p;
40166     pSlot->pNext = pcache1.pFree;
40167     pcache1.pFree = pSlot;
40168     pcache1.nFreeSlot++;
40169     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
40170     assert( pcache1.nFreeSlot<=pcache1.nSlot );
40171     sqlite3_mutex_leave(pcache1.mutex);
40172   }else{
40173     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
40174     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
40175     nFreed = sqlite3MallocSize(p);
40176 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
40177     sqlite3_mutex_enter(pcache1.mutex);
40178     sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
40179     sqlite3_mutex_leave(pcache1.mutex);
40180 #endif
40181     sqlite3_free(p);
40182   }
40183   return nFreed;
40184 }
40185 
40186 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
40187 /*
40188 ** Return the size of a pcache allocation
40189 */
40190 static int pcache1MemSize(void *p){
40191   if( p>=pcache1.pStart && p<pcache1.pEnd ){
40192     return pcache1.szSlot;
40193   }else{
40194     int iSize;
40195     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
40196     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
40197     iSize = sqlite3MallocSize(p);
40198     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
40199     return iSize;
40200   }
40201 }
40202 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
40203 
40204 /*
40205 ** Allocate a new page object initially associated with cache pCache.
40206 */
40207 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
40208   PgHdr1 *p = 0;
40209   void *pPg;
40210 
40211   /* The group mutex must be released before pcache1Alloc() is called. This
40212   ** is because it may call sqlite3_release_memory(), which assumes that
40213   ** this mutex is not held. */
40214   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
40215   pcache1LeaveMutex(pCache->pGroup);
40216 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
40217   pPg = pcache1Alloc(pCache->szPage);
40218   p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
40219   if( !pPg || !p ){
40220     pcache1Free(pPg);
40221     sqlite3_free(p);
40222     pPg = 0;
40223   }
40224 #else
40225   pPg = pcache1Alloc(ROUND8(sizeof(PgHdr1)) + pCache->szPage + pCache->szExtra);
40226   p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
40227 #endif
40228   pcache1EnterMutex(pCache->pGroup);
40229 
40230   if( pPg ){
40231     p->page.pBuf = pPg;
40232     p->page.pExtra = &p[1];
40233     if( pCache->bPurgeable ){
40234       pCache->pGroup->nCurrentPage++;
40235     }
40236     return p;
40237   }
40238   return 0;
40239 }
40240 
40241 /*
40242 ** Free a page object allocated by pcache1AllocPage().
40243 **
40244 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
40245 ** that the current implementation happens to never call this routine
40246 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
40247 */
40248 static void pcache1FreePage(PgHdr1 *p){
40249   if( ALWAYS(p) ){
40250     PCache1 *pCache = p->pCache;
40251     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
40252     pcache1Free(p->page.pBuf);
40253 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
40254     sqlite3_free(p);
40255 #endif
40256     if( pCache->bPurgeable ){
40257       pCache->pGroup->nCurrentPage--;
40258     }
40259   }
40260 }
40261 
40262 /*
40263 ** Malloc function used by SQLite to obtain space from the buffer configured
40264 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
40265 ** exists, this function falls back to sqlite3Malloc().
40266 */
40267 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
40268   return pcache1Alloc(sz);
40269 }
40270 
40271 /*
40272 ** Free an allocated buffer obtained from sqlite3PageMalloc().
40273 */
40274 SQLITE_PRIVATE void sqlite3PageFree(void *p){
40275   pcache1Free(p);
40276 }
40277 
40278 
40279 /*
40280 ** Return true if it desirable to avoid allocating a new page cache
40281 ** entry.
40282 **
40283 ** If memory was allocated specifically to the page cache using
40284 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
40285 ** it is desirable to avoid allocating a new page cache entry because
40286 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
40287 ** for all page cache needs and we should not need to spill the
40288 ** allocation onto the heap.
40289 **
40290 ** Or, the heap is used for all page cache memory but the heap is
40291 ** under memory pressure, then again it is desirable to avoid
40292 ** allocating a new page cache entry in order to avoid stressing
40293 ** the heap even further.
40294 */
40295 static int pcache1UnderMemoryPressure(PCache1 *pCache){
40296   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
40297     return pcache1.bUnderPressure;
40298   }else{
40299     return sqlite3HeapNearlyFull();
40300   }
40301 }
40302 
40303 /******************************************************************************/
40304 /******** General Implementation Functions ************************************/
40305 
40306 /*
40307 ** This function is used to resize the hash table used by the cache passed
40308 ** as the first argument.
40309 **
40310 ** The PCache mutex must be held when this function is called.
40311 */
40312 static void pcache1ResizeHash(PCache1 *p){
40313   PgHdr1 **apNew;
40314   unsigned int nNew;
40315   unsigned int i;
40316 
40317   assert( sqlite3_mutex_held(p->pGroup->mutex) );
40318 
40319   nNew = p->nHash*2;
40320   if( nNew<256 ){
40321     nNew = 256;
40322   }
40323 
40324   pcache1LeaveMutex(p->pGroup);
40325   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
40326   apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
40327   if( p->nHash ){ sqlite3EndBenignMalloc(); }
40328   pcache1EnterMutex(p->pGroup);
40329   if( apNew ){
40330     for(i=0; i<p->nHash; i++){
40331       PgHdr1 *pPage;
40332       PgHdr1 *pNext = p->apHash[i];
40333       while( (pPage = pNext)!=0 ){
40334         unsigned int h = pPage->iKey % nNew;
40335         pNext = pPage->pNext;
40336         pPage->pNext = apNew[h];
40337         apNew[h] = pPage;
40338       }
40339     }
40340     sqlite3_free(p->apHash);
40341     p->apHash = apNew;
40342     p->nHash = nNew;
40343   }
40344 }
40345 
40346 /*
40347 ** This function is used internally to remove the page pPage from the
40348 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
40349 ** LRU list, then this function is a no-op.
40350 **
40351 ** The PGroup mutex must be held when this function is called.
40352 */
40353 static void pcache1PinPage(PgHdr1 *pPage){
40354   PCache1 *pCache;
40355   PGroup *pGroup;
40356 
40357   assert( pPage!=0 );
40358   assert( pPage->isPinned==0 );
40359   pCache = pPage->pCache;
40360   pGroup = pCache->pGroup;
40361   assert( pPage->pLruNext || pPage==pGroup->pLruTail );
40362   assert( pPage->pLruPrev || pPage==pGroup->pLruHead );
40363   assert( sqlite3_mutex_held(pGroup->mutex) );
40364   if( pPage->pLruPrev ){
40365     pPage->pLruPrev->pLruNext = pPage->pLruNext;
40366   }else{
40367     pGroup->pLruHead = pPage->pLruNext;
40368   }
40369   if( pPage->pLruNext ){
40370     pPage->pLruNext->pLruPrev = pPage->pLruPrev;
40371   }else{
40372     pGroup->pLruTail = pPage->pLruPrev;
40373   }
40374   pPage->pLruNext = 0;
40375   pPage->pLruPrev = 0;
40376   pPage->isPinned = 1;
40377   pCache->nRecyclable--;
40378 }
40379 
40380 
40381 /*
40382 ** Remove the page supplied as an argument from the hash table
40383 ** (PCache1.apHash structure) that it is currently stored in.
40384 **
40385 ** The PGroup mutex must be held when this function is called.
40386 */
40387 static void pcache1RemoveFromHash(PgHdr1 *pPage){
40388   unsigned int h;
40389   PCache1 *pCache = pPage->pCache;
40390   PgHdr1 **pp;
40391 
40392   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
40393   h = pPage->iKey % pCache->nHash;
40394   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
40395   *pp = (*pp)->pNext;
40396 
40397   pCache->nPage--;
40398 }
40399 
40400 /*
40401 ** If there are currently more than nMaxPage pages allocated, try
40402 ** to recycle pages to reduce the number allocated to nMaxPage.
40403 */
40404 static void pcache1EnforceMaxPage(PGroup *pGroup){
40405   assert( sqlite3_mutex_held(pGroup->mutex) );
40406   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
40407     PgHdr1 *p = pGroup->pLruTail;
40408     assert( p->pCache->pGroup==pGroup );
40409     assert( p->isPinned==0 );
40410     pcache1PinPage(p);
40411     pcache1RemoveFromHash(p);
40412     pcache1FreePage(p);
40413   }
40414 }
40415 
40416 /*
40417 ** Discard all pages from cache pCache with a page number (key value)
40418 ** greater than or equal to iLimit. Any pinned pages that meet this
40419 ** criteria are unpinned before they are discarded.
40420 **
40421 ** The PCache mutex must be held when this function is called.
40422 */
40423 static void pcache1TruncateUnsafe(
40424   PCache1 *pCache,             /* The cache to truncate */
40425   unsigned int iLimit          /* Drop pages with this pgno or larger */
40426 ){
40427   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
40428   unsigned int h;
40429   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
40430   for(h=0; h<pCache->nHash; h++){
40431     PgHdr1 **pp = &pCache->apHash[h];
40432     PgHdr1 *pPage;
40433     while( (pPage = *pp)!=0 ){
40434       if( pPage->iKey>=iLimit ){
40435         pCache->nPage--;
40436         *pp = pPage->pNext;
40437         if( !pPage->isPinned ) pcache1PinPage(pPage);
40438         pcache1FreePage(pPage);
40439       }else{
40440         pp = &pPage->pNext;
40441         TESTONLY( nPage++; )
40442       }
40443     }
40444   }
40445   assert( pCache->nPage==nPage );
40446 }
40447 
40448 /******************************************************************************/
40449 /******** sqlite3_pcache Methods **********************************************/
40450 
40451 /*
40452 ** Implementation of the sqlite3_pcache.xInit method.
40453 */
40454 static int pcache1Init(void *NotUsed){
40455   UNUSED_PARAMETER(NotUsed);
40456   assert( pcache1.isInit==0 );
40457   memset(&pcache1, 0, sizeof(pcache1));
40458   if( sqlite3GlobalConfig.bCoreMutex ){
40459     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
40460     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
40461   }
40462   pcache1.grp.mxPinned = 10;
40463   pcache1.isInit = 1;
40464   return SQLITE_OK;
40465 }
40466 
40467 /*
40468 ** Implementation of the sqlite3_pcache.xShutdown method.
40469 ** Note that the static mutex allocated in xInit does
40470 ** not need to be freed.
40471 */
40472 static void pcache1Shutdown(void *NotUsed){
40473   UNUSED_PARAMETER(NotUsed);
40474   assert( pcache1.isInit!=0 );
40475   memset(&pcache1, 0, sizeof(pcache1));
40476 }
40477 
40478 /* forward declaration */
40479 static void pcache1Destroy(sqlite3_pcache *p);
40480 
40481 /*
40482 ** Implementation of the sqlite3_pcache.xCreate method.
40483 **
40484 ** Allocate a new cache.
40485 */
40486 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
40487   PCache1 *pCache;      /* The newly created page cache */
40488   PGroup *pGroup;       /* The group the new page cache will belong to */
40489   int sz;               /* Bytes of memory required to allocate the new cache */
40490 
40491   /*
40492   ** The separateCache variable is true if each PCache has its own private
40493   ** PGroup.  In other words, separateCache is true for mode (1) where no
40494   ** mutexing is required.
40495   **
40496   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
40497   **
40498   **   *  Always use a unified cache in single-threaded applications
40499   **
40500   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
40501   **      use separate caches (mode-1)
40502   */
40503 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
40504   const int separateCache = 0;
40505 #else
40506   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
40507 #endif
40508 
40509   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
40510   assert( szExtra < 300 );
40511 
40512   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
40513   pCache = (PCache1 *)sqlite3MallocZero(sz);
40514   if( pCache ){
40515     if( separateCache ){
40516       pGroup = (PGroup*)&pCache[1];
40517       pGroup->mxPinned = 10;
40518     }else{
40519       pGroup = &pcache1.grp;
40520     }
40521     pCache->pGroup = pGroup;
40522     pCache->szPage = szPage;
40523     pCache->szExtra = szExtra;
40524     pCache->bPurgeable = (bPurgeable ? 1 : 0);
40525     pcache1EnterMutex(pGroup);
40526     pcache1ResizeHash(pCache);
40527     if( bPurgeable ){
40528       pCache->nMin = 10;
40529       pGroup->nMinPage += pCache->nMin;
40530       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
40531     }
40532     pcache1LeaveMutex(pGroup);
40533     if( pCache->nHash==0 ){
40534       pcache1Destroy((sqlite3_pcache*)pCache);
40535       pCache = 0;
40536     }
40537   }
40538   return (sqlite3_pcache *)pCache;
40539 }
40540 
40541 /*
40542 ** Implementation of the sqlite3_pcache.xCachesize method.
40543 **
40544 ** Configure the cache_size limit for a cache.
40545 */
40546 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
40547   PCache1 *pCache = (PCache1 *)p;
40548   if( pCache->bPurgeable ){
40549     PGroup *pGroup = pCache->pGroup;
40550     pcache1EnterMutex(pGroup);
40551     pGroup->nMaxPage += (nMax - pCache->nMax);
40552     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
40553     pCache->nMax = nMax;
40554     pCache->n90pct = pCache->nMax*9/10;
40555     pcache1EnforceMaxPage(pGroup);
40556     pcache1LeaveMutex(pGroup);
40557   }
40558 }
40559 
40560 /*
40561 ** Implementation of the sqlite3_pcache.xShrink method.
40562 **
40563 ** Free up as much memory as possible.
40564 */
40565 static void pcache1Shrink(sqlite3_pcache *p){
40566   PCache1 *pCache = (PCache1*)p;
40567   if( pCache->bPurgeable ){
40568     PGroup *pGroup = pCache->pGroup;
40569     int savedMaxPage;
40570     pcache1EnterMutex(pGroup);
40571     savedMaxPage = pGroup->nMaxPage;
40572     pGroup->nMaxPage = 0;
40573     pcache1EnforceMaxPage(pGroup);
40574     pGroup->nMaxPage = savedMaxPage;
40575     pcache1LeaveMutex(pGroup);
40576   }
40577 }
40578 
40579 /*
40580 ** Implementation of the sqlite3_pcache.xPagecount method.
40581 */
40582 static int pcache1Pagecount(sqlite3_pcache *p){
40583   int n;
40584   PCache1 *pCache = (PCache1*)p;
40585   pcache1EnterMutex(pCache->pGroup);
40586   n = pCache->nPage;
40587   pcache1LeaveMutex(pCache->pGroup);
40588   return n;
40589 }
40590 
40591 
40592 /*
40593 ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
40594 ** in the header of the pcache1Fetch() procedure.
40595 **
40596 ** This steps are broken out into a separate procedure because they are
40597 ** usually not needed, and by avoiding the stack initialization required
40598 ** for these steps, the main pcache1Fetch() procedure can run faster.
40599 */
40600 static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
40601   PCache1 *pCache,
40602   unsigned int iKey,
40603   int createFlag
40604 ){
40605   unsigned int nPinned;
40606   PGroup *pGroup = pCache->pGroup;
40607   PgHdr1 *pPage = 0;
40608 
40609   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
40610   assert( pCache->nPage >= pCache->nRecyclable );
40611   nPinned = pCache->nPage - pCache->nRecyclable;
40612   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
40613   assert( pCache->n90pct == pCache->nMax*9/10 );
40614   if( createFlag==1 && (
40615         nPinned>=pGroup->mxPinned
40616      || nPinned>=pCache->n90pct
40617      || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
40618   )){
40619     return 0;
40620   }
40621 
40622   if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
40623   assert( pCache->nHash>0 && pCache->apHash );
40624 
40625   /* Step 4. Try to recycle a page. */
40626   if( pCache->bPurgeable && pGroup->pLruTail && (
40627          (pCache->nPage+1>=pCache->nMax)
40628       || pGroup->nCurrentPage>=pGroup->nMaxPage
40629       || pcache1UnderMemoryPressure(pCache)
40630   )){
40631     PCache1 *pOther;
40632     pPage = pGroup->pLruTail;
40633     assert( pPage->isPinned==0 );
40634     pcache1RemoveFromHash(pPage);
40635     pcache1PinPage(pPage);
40636     pOther = pPage->pCache;
40637 
40638     /* We want to verify that szPage and szExtra are the same for pOther
40639     ** and pCache.  Assert that we can verify this by comparing sums. */
40640     assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
40641     assert( pCache->szExtra<512 );
40642     assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
40643     assert( pOther->szExtra<512 );
40644 
40645     if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
40646       pcache1FreePage(pPage);
40647       pPage = 0;
40648     }else{
40649       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
40650     }
40651   }
40652 
40653   /* Step 5. If a usable page buffer has still not been found,
40654   ** attempt to allocate a new one.
40655   */
40656   if( !pPage ){
40657     if( createFlag==1 ) sqlite3BeginBenignMalloc();
40658     pPage = pcache1AllocPage(pCache);
40659     if( createFlag==1 ) sqlite3EndBenignMalloc();
40660   }
40661 
40662   if( pPage ){
40663     unsigned int h = iKey % pCache->nHash;
40664     pCache->nPage++;
40665     pPage->iKey = iKey;
40666     pPage->pNext = pCache->apHash[h];
40667     pPage->pCache = pCache;
40668     pPage->pLruPrev = 0;
40669     pPage->pLruNext = 0;
40670     pPage->isPinned = 1;
40671     *(void **)pPage->page.pExtra = 0;
40672     pCache->apHash[h] = pPage;
40673     if( iKey>pCache->iMaxKey ){
40674       pCache->iMaxKey = iKey;
40675     }
40676   }
40677   return pPage;
40678 }
40679 
40680 /*
40681 ** Implementation of the sqlite3_pcache.xFetch method.
40682 **
40683 ** Fetch a page by key value.
40684 **
40685 ** Whether or not a new page may be allocated by this function depends on
40686 ** the value of the createFlag argument.  0 means do not allocate a new
40687 ** page.  1 means allocate a new page if space is easily available.  2
40688 ** means to try really hard to allocate a new page.
40689 **
40690 ** For a non-purgeable cache (a cache used as the storage for an in-memory
40691 ** database) there is really no difference between createFlag 1 and 2.  So
40692 ** the calling function (pcache.c) will never have a createFlag of 1 on
40693 ** a non-purgeable cache.
40694 **
40695 ** There are three different approaches to obtaining space for a page,
40696 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
40697 **
40698 **   1. Regardless of the value of createFlag, the cache is searched for a
40699 **      copy of the requested page. If one is found, it is returned.
40700 **
40701 **   2. If createFlag==0 and the page is not already in the cache, NULL is
40702 **      returned.
40703 **
40704 **   3. If createFlag is 1, and the page is not already in the cache, then
40705 **      return NULL (do not allocate a new page) if any of the following
40706 **      conditions are true:
40707 **
40708 **       (a) the number of pages pinned by the cache is greater than
40709 **           PCache1.nMax, or
40710 **
40711 **       (b) the number of pages pinned by the cache is greater than
40712 **           the sum of nMax for all purgeable caches, less the sum of
40713 **           nMin for all other purgeable caches, or
40714 **
40715 **   4. If none of the first three conditions apply and the cache is marked
40716 **      as purgeable, and if one of the following is true:
40717 **
40718 **       (a) The number of pages allocated for the cache is already
40719 **           PCache1.nMax, or
40720 **
40721 **       (b) The number of pages allocated for all purgeable caches is
40722 **           already equal to or greater than the sum of nMax for all
40723 **           purgeable caches,
40724 **
40725 **       (c) The system is under memory pressure and wants to avoid
40726 **           unnecessary pages cache entry allocations
40727 **
40728 **      then attempt to recycle a page from the LRU list. If it is the right
40729 **      size, return the recycled buffer. Otherwise, free the buffer and
40730 **      proceed to step 5.
40731 **
40732 **   5. Otherwise, allocate and return a new page buffer.
40733 */
40734 static sqlite3_pcache_page *pcache1Fetch(
40735   sqlite3_pcache *p,
40736   unsigned int iKey,
40737   int createFlag
40738 ){
40739   PCache1 *pCache = (PCache1 *)p;
40740   PgHdr1 *pPage = 0;
40741 
40742   assert( offsetof(PgHdr1,page)==0 );
40743   assert( pCache->bPurgeable || createFlag!=1 );
40744   assert( pCache->bPurgeable || pCache->nMin==0 );
40745   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
40746   assert( pCache->nMin==0 || pCache->bPurgeable );
40747   assert( pCache->nHash>0 );
40748   pcache1EnterMutex(pCache->pGroup);
40749 
40750   /* Step 1: Search the hash table for an existing entry. */
40751   pPage = pCache->apHash[iKey % pCache->nHash];
40752   while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
40753 
40754   /* Step 2: Abort if no existing page is found and createFlag is 0 */
40755   if( pPage ){
40756     if( !pPage->isPinned ) pcache1PinPage(pPage);
40757   }else if( createFlag ){
40758     /* Steps 3, 4, and 5 implemented by this subroutine */
40759     pPage = pcache1FetchStage2(pCache, iKey, createFlag);
40760   }
40761   assert( pPage==0 || pCache->iMaxKey>=iKey );
40762   pcache1LeaveMutex(pCache->pGroup);
40763   return (sqlite3_pcache_page*)pPage;
40764 }
40765 
40766 
40767 /*
40768 ** Implementation of the sqlite3_pcache.xUnpin method.
40769 **
40770 ** Mark a page as unpinned (eligible for asynchronous recycling).
40771 */
40772 static void pcache1Unpin(
40773   sqlite3_pcache *p,
40774   sqlite3_pcache_page *pPg,
40775   int reuseUnlikely
40776 ){
40777   PCache1 *pCache = (PCache1 *)p;
40778   PgHdr1 *pPage = (PgHdr1 *)pPg;
40779   PGroup *pGroup = pCache->pGroup;
40780 
40781   assert( pPage->pCache==pCache );
40782   pcache1EnterMutex(pGroup);
40783 
40784   /* It is an error to call this function if the page is already
40785   ** part of the PGroup LRU list.
40786   */
40787   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
40788   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
40789   assert( pPage->isPinned==1 );
40790 
40791   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
40792     pcache1RemoveFromHash(pPage);
40793     pcache1FreePage(pPage);
40794   }else{
40795     /* Add the page to the PGroup LRU list. */
40796     if( pGroup->pLruHead ){
40797       pGroup->pLruHead->pLruPrev = pPage;
40798       pPage->pLruNext = pGroup->pLruHead;
40799       pGroup->pLruHead = pPage;
40800     }else{
40801       pGroup->pLruTail = pPage;
40802       pGroup->pLruHead = pPage;
40803     }
40804     pCache->nRecyclable++;
40805     pPage->isPinned = 0;
40806   }
40807 
40808   pcache1LeaveMutex(pCache->pGroup);
40809 }
40810 
40811 /*
40812 ** Implementation of the sqlite3_pcache.xRekey method.
40813 */
40814 static void pcache1Rekey(
40815   sqlite3_pcache *p,
40816   sqlite3_pcache_page *pPg,
40817   unsigned int iOld,
40818   unsigned int iNew
40819 ){
40820   PCache1 *pCache = (PCache1 *)p;
40821   PgHdr1 *pPage = (PgHdr1 *)pPg;
40822   PgHdr1 **pp;
40823   unsigned int h;
40824   assert( pPage->iKey==iOld );
40825   assert( pPage->pCache==pCache );
40826 
40827   pcache1EnterMutex(pCache->pGroup);
40828 
40829   h = iOld%pCache->nHash;
40830   pp = &pCache->apHash[h];
40831   while( (*pp)!=pPage ){
40832     pp = &(*pp)->pNext;
40833   }
40834   *pp = pPage->pNext;
40835 
40836   h = iNew%pCache->nHash;
40837   pPage->iKey = iNew;
40838   pPage->pNext = pCache->apHash[h];
40839   pCache->apHash[h] = pPage;
40840   if( iNew>pCache->iMaxKey ){
40841     pCache->iMaxKey = iNew;
40842   }
40843 
40844   pcache1LeaveMutex(pCache->pGroup);
40845 }
40846 
40847 /*
40848 ** Implementation of the sqlite3_pcache.xTruncate method.
40849 **
40850 ** Discard all unpinned pages in the cache with a page number equal to
40851 ** or greater than parameter iLimit. Any pinned pages with a page number
40852 ** equal to or greater than iLimit are implicitly unpinned.
40853 */
40854 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
40855   PCache1 *pCache = (PCache1 *)p;
40856   pcache1EnterMutex(pCache->pGroup);
40857   if( iLimit<=pCache->iMaxKey ){
40858     pcache1TruncateUnsafe(pCache, iLimit);
40859     pCache->iMaxKey = iLimit-1;
40860   }
40861   pcache1LeaveMutex(pCache->pGroup);
40862 }
40863 
40864 /*
40865 ** Implementation of the sqlite3_pcache.xDestroy method.
40866 **
40867 ** Destroy a cache allocated using pcache1Create().
40868 */
40869 static void pcache1Destroy(sqlite3_pcache *p){
40870   PCache1 *pCache = (PCache1 *)p;
40871   PGroup *pGroup = pCache->pGroup;
40872   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
40873   pcache1EnterMutex(pGroup);
40874   pcache1TruncateUnsafe(pCache, 0);
40875   assert( pGroup->nMaxPage >= pCache->nMax );
40876   pGroup->nMaxPage -= pCache->nMax;
40877   assert( pGroup->nMinPage >= pCache->nMin );
40878   pGroup->nMinPage -= pCache->nMin;
40879   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
40880   pcache1EnforceMaxPage(pGroup);
40881   pcache1LeaveMutex(pGroup);
40882   sqlite3_free(pCache->apHash);
40883   sqlite3_free(pCache);
40884 }
40885 
40886 /*
40887 ** This function is called during initialization (sqlite3_initialize()) to
40888 ** install the default pluggable cache module, assuming the user has not
40889 ** already provided an alternative.
40890 */
40891 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
40892   static const sqlite3_pcache_methods2 defaultMethods = {
40893     1,                       /* iVersion */
40894     0,                       /* pArg */
40895     pcache1Init,             /* xInit */
40896     pcache1Shutdown,         /* xShutdown */
40897     pcache1Create,           /* xCreate */
40898     pcache1Cachesize,        /* xCachesize */
40899     pcache1Pagecount,        /* xPagecount */
40900     pcache1Fetch,            /* xFetch */
40901     pcache1Unpin,            /* xUnpin */
40902     pcache1Rekey,            /* xRekey */
40903     pcache1Truncate,         /* xTruncate */
40904     pcache1Destroy,          /* xDestroy */
40905     pcache1Shrink            /* xShrink */
40906   };
40907   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
40908 }
40909 
40910 /*
40911 ** Return the size of the header on each page of this PCACHE implementation.
40912 */
40913 SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
40914 
40915 /*
40916 ** Return the global mutex used by this PCACHE implementation.  The
40917 ** sqlite3_status() routine needs access to this mutex.
40918 */
40919 SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
40920   return pcache1.mutex;
40921 }
40922 
40923 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
40924 /*
40925 ** This function is called to free superfluous dynamically allocated memory
40926 ** held by the pager system. Memory in use by any SQLite pager allocated
40927 ** by the current thread may be sqlite3_free()ed.
40928 **
40929 ** nReq is the number of bytes of memory required. Once this much has
40930 ** been released, the function returns. The return value is the total number
40931 ** of bytes of memory released.
40932 */
40933 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
40934   int nFree = 0;
40935   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
40936   assert( sqlite3_mutex_notheld(pcache1.mutex) );
40937   if( pcache1.pStart==0 ){
40938     PgHdr1 *p;
40939     pcache1EnterMutex(&pcache1.grp);
40940     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
40941       nFree += pcache1MemSize(p->page.pBuf);
40942 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
40943       nFree += sqlite3MemSize(p);
40944 #endif
40945       assert( p->isPinned==0 );
40946       pcache1PinPage(p);
40947       pcache1RemoveFromHash(p);
40948       pcache1FreePage(p);
40949     }
40950     pcache1LeaveMutex(&pcache1.grp);
40951   }
40952   return nFree;
40953 }
40954 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
40955 
40956 #ifdef SQLITE_TEST
40957 /*
40958 ** This function is used by test procedures to inspect the internal state
40959 ** of the global cache.
40960 */
40961 SQLITE_PRIVATE void sqlite3PcacheStats(
40962   int *pnCurrent,      /* OUT: Total number of pages cached */
40963   int *pnMax,          /* OUT: Global maximum cache size */
40964   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
40965   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
40966 ){
40967   PgHdr1 *p;
40968   int nRecyclable = 0;
40969   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
40970     assert( p->isPinned==0 );
40971     nRecyclable++;
40972   }
40973   *pnCurrent = pcache1.grp.nCurrentPage;
40974   *pnMax = (int)pcache1.grp.nMaxPage;
40975   *pnMin = (int)pcache1.grp.nMinPage;
40976   *pnRecyclable = nRecyclable;
40977 }
40978 #endif
40979 
40980 /************** End of pcache1.c *********************************************/
40981 /************** Begin file rowset.c ******************************************/
40982 /*
40983 ** 2008 December 3
40984 **
40985 ** The author disclaims copyright to this source code.  In place of
40986 ** a legal notice, here is a blessing:
40987 **
40988 **    May you do good and not evil.
40989 **    May you find forgiveness for yourself and forgive others.
40990 **    May you share freely, never taking more than you give.
40991 **
40992 *************************************************************************
40993 **
40994 ** This module implements an object we call a "RowSet".
40995 **
40996 ** The RowSet object is a collection of rowids.  Rowids
40997 ** are inserted into the RowSet in an arbitrary order.  Inserts
40998 ** can be intermixed with tests to see if a given rowid has been
40999 ** previously inserted into the RowSet.
41000 **
41001 ** After all inserts are finished, it is possible to extract the
41002 ** elements of the RowSet in sorted order.  Once this extraction
41003 ** process has started, no new elements may be inserted.
41004 **
41005 ** Hence, the primitive operations for a RowSet are:
41006 **
41007 **    CREATE
41008 **    INSERT
41009 **    TEST
41010 **    SMALLEST
41011 **    DESTROY
41012 **
41013 ** The CREATE and DESTROY primitives are the constructor and destructor,
41014 ** obviously.  The INSERT primitive adds a new element to the RowSet.
41015 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
41016 ** extracts the least value from the RowSet.
41017 **
41018 ** The INSERT primitive might allocate additional memory.  Memory is
41019 ** allocated in chunks so most INSERTs do no allocation.  There is an
41020 ** upper bound on the size of allocated memory.  No memory is freed
41021 ** until DESTROY.
41022 **
41023 ** The TEST primitive includes a "batch" number.  The TEST primitive
41024 ** will only see elements that were inserted before the last change
41025 ** in the batch number.  In other words, if an INSERT occurs between
41026 ** two TESTs where the TESTs have the same batch nubmer, then the
41027 ** value added by the INSERT will not be visible to the second TEST.
41028 ** The initial batch number is zero, so if the very first TEST contains
41029 ** a non-zero batch number, it will see all prior INSERTs.
41030 **
41031 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
41032 ** that is attempted.
41033 **
41034 ** The cost of an INSERT is roughly constant.  (Sometimes new memory
41035 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
41036 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
41037 ** The cost of a TEST using the same batch number is O(logN).  The cost
41038 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
41039 ** primitives are constant time.  The cost of DESTROY is O(N).
41040 **
41041 ** There is an added cost of O(N) when switching between TEST and
41042 ** SMALLEST primitives.
41043 */
41044 
41045 
41046 /*
41047 ** Target size for allocation chunks.
41048 */
41049 #define ROWSET_ALLOCATION_SIZE 1024
41050 
41051 /*
41052 ** The number of rowset entries per allocation chunk.
41053 */
41054 #define ROWSET_ENTRY_PER_CHUNK  \
41055                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
41056 
41057 /*
41058 ** Each entry in a RowSet is an instance of the following object.
41059 **
41060 ** This same object is reused to store a linked list of trees of RowSetEntry
41061 ** objects.  In that alternative use, pRight points to the next entry
41062 ** in the list, pLeft points to the tree, and v is unused.  The
41063 ** RowSet.pForest value points to the head of this forest list.
41064 */
41065 struct RowSetEntry {
41066   i64 v;                        /* ROWID value for this entry */
41067   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
41068   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
41069 };
41070 
41071 /*
41072 ** RowSetEntry objects are allocated in large chunks (instances of the
41073 ** following structure) to reduce memory allocation overhead.  The
41074 ** chunks are kept on a linked list so that they can be deallocated
41075 ** when the RowSet is destroyed.
41076 */
41077 struct RowSetChunk {
41078   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
41079   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
41080 };
41081 
41082 /*
41083 ** A RowSet in an instance of the following structure.
41084 **
41085 ** A typedef of this structure if found in sqliteInt.h.
41086 */
41087 struct RowSet {
41088   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
41089   sqlite3 *db;                   /* The database connection */
41090   struct RowSetEntry *pEntry;    /* List of entries using pRight */
41091   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
41092   struct RowSetEntry *pFresh;    /* Source of new entry objects */
41093   struct RowSetEntry *pForest;   /* List of binary trees of entries */
41094   u16 nFresh;                    /* Number of objects on pFresh */
41095   u16 rsFlags;                   /* Various flags */
41096   int iBatch;                    /* Current insert batch */
41097 };
41098 
41099 /*
41100 ** Allowed values for RowSet.rsFlags
41101 */
41102 #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
41103 #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
41104 
41105 /*
41106 ** Turn bulk memory into a RowSet object.  N bytes of memory
41107 ** are available at pSpace.  The db pointer is used as a memory context
41108 ** for any subsequent allocations that need to occur.
41109 ** Return a pointer to the new RowSet object.
41110 **
41111 ** It must be the case that N is sufficient to make a Rowset.  If not
41112 ** an assertion fault occurs.
41113 **
41114 ** If N is larger than the minimum, use the surplus as an initial
41115 ** allocation of entries available to be filled.
41116 */
41117 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
41118   RowSet *p;
41119   assert( N >= ROUND8(sizeof(*p)) );
41120   p = pSpace;
41121   p->pChunk = 0;
41122   p->db = db;
41123   p->pEntry = 0;
41124   p->pLast = 0;
41125   p->pForest = 0;
41126   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
41127   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
41128   p->rsFlags = ROWSET_SORTED;
41129   p->iBatch = 0;
41130   return p;
41131 }
41132 
41133 /*
41134 ** Deallocate all chunks from a RowSet.  This frees all memory that
41135 ** the RowSet has allocated over its lifetime.  This routine is
41136 ** the destructor for the RowSet.
41137 */
41138 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
41139   struct RowSetChunk *pChunk, *pNextChunk;
41140   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
41141     pNextChunk = pChunk->pNextChunk;
41142     sqlite3DbFree(p->db, pChunk);
41143   }
41144   p->pChunk = 0;
41145   p->nFresh = 0;
41146   p->pEntry = 0;
41147   p->pLast = 0;
41148   p->pForest = 0;
41149   p->rsFlags = ROWSET_SORTED;
41150 }
41151 
41152 /*
41153 ** Allocate a new RowSetEntry object that is associated with the
41154 ** given RowSet.  Return a pointer to the new and completely uninitialized
41155 ** objected.
41156 **
41157 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
41158 ** routine returns NULL.
41159 */
41160 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
41161   assert( p!=0 );
41162   if( p->nFresh==0 ){
41163     struct RowSetChunk *pNew;
41164     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
41165     if( pNew==0 ){
41166       return 0;
41167     }
41168     pNew->pNextChunk = p->pChunk;
41169     p->pChunk = pNew;
41170     p->pFresh = pNew->aEntry;
41171     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
41172   }
41173   p->nFresh--;
41174   return p->pFresh++;
41175 }
41176 
41177 /*
41178 ** Insert a new value into a RowSet.
41179 **
41180 ** The mallocFailed flag of the database connection is set if a
41181 ** memory allocation fails.
41182 */
41183 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
41184   struct RowSetEntry *pEntry;  /* The new entry */
41185   struct RowSetEntry *pLast;   /* The last prior entry */
41186 
41187   /* This routine is never called after sqlite3RowSetNext() */
41188   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
41189 
41190   pEntry = rowSetEntryAlloc(p);
41191   if( pEntry==0 ) return;
41192   pEntry->v = rowid;
41193   pEntry->pRight = 0;
41194   pLast = p->pLast;
41195   if( pLast ){
41196     if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
41197       p->rsFlags &= ~ROWSET_SORTED;
41198     }
41199     pLast->pRight = pEntry;
41200   }else{
41201     p->pEntry = pEntry;
41202   }
41203   p->pLast = pEntry;
41204 }
41205 
41206 /*
41207 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
41208 **
41209 ** The input lists are connected via pRight pointers and are
41210 ** assumed to each already be in sorted order.
41211 */
41212 static struct RowSetEntry *rowSetEntryMerge(
41213   struct RowSetEntry *pA,    /* First sorted list to be merged */
41214   struct RowSetEntry *pB     /* Second sorted list to be merged */
41215 ){
41216   struct RowSetEntry head;
41217   struct RowSetEntry *pTail;
41218 
41219   pTail = &head;
41220   while( pA && pB ){
41221     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
41222     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
41223     if( pA->v<pB->v ){
41224       pTail->pRight = pA;
41225       pA = pA->pRight;
41226       pTail = pTail->pRight;
41227     }else if( pB->v<pA->v ){
41228       pTail->pRight = pB;
41229       pB = pB->pRight;
41230       pTail = pTail->pRight;
41231     }else{
41232       pA = pA->pRight;
41233     }
41234   }
41235   if( pA ){
41236     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
41237     pTail->pRight = pA;
41238   }else{
41239     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
41240     pTail->pRight = pB;
41241   }
41242   return head.pRight;
41243 }
41244 
41245 /*
41246 ** Sort all elements on the list of RowSetEntry objects into order of
41247 ** increasing v.
41248 */
41249 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
41250   unsigned int i;
41251   struct RowSetEntry *pNext, *aBucket[40];
41252 
41253   memset(aBucket, 0, sizeof(aBucket));
41254   while( pIn ){
41255     pNext = pIn->pRight;
41256     pIn->pRight = 0;
41257     for(i=0; aBucket[i]; i++){
41258       pIn = rowSetEntryMerge(aBucket[i], pIn);
41259       aBucket[i] = 0;
41260     }
41261     aBucket[i] = pIn;
41262     pIn = pNext;
41263   }
41264   pIn = 0;
41265   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
41266     pIn = rowSetEntryMerge(pIn, aBucket[i]);
41267   }
41268   return pIn;
41269 }
41270 
41271 
41272 /*
41273 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
41274 ** Convert this tree into a linked list connected by the pRight pointers
41275 ** and return pointers to the first and last elements of the new list.
41276 */
41277 static void rowSetTreeToList(
41278   struct RowSetEntry *pIn,         /* Root of the input tree */
41279   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
41280   struct RowSetEntry **ppLast      /* Write tail of the output list here */
41281 ){
41282   assert( pIn!=0 );
41283   if( pIn->pLeft ){
41284     struct RowSetEntry *p;
41285     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
41286     p->pRight = pIn;
41287   }else{
41288     *ppFirst = pIn;
41289   }
41290   if( pIn->pRight ){
41291     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
41292   }else{
41293     *ppLast = pIn;
41294   }
41295   assert( (*ppLast)->pRight==0 );
41296 }
41297 
41298 
41299 /*
41300 ** Convert a sorted list of elements (connected by pRight) into a binary
41301 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
41302 ** node taken from the head of *ppList.  A depth of 2 means a tree with
41303 ** three nodes.  And so forth.
41304 **
41305 ** Use as many entries from the input list as required and update the
41306 ** *ppList to point to the unused elements of the list.  If the input
41307 ** list contains too few elements, then construct an incomplete tree
41308 ** and leave *ppList set to NULL.
41309 **
41310 ** Return a pointer to the root of the constructed binary tree.
41311 */
41312 static struct RowSetEntry *rowSetNDeepTree(
41313   struct RowSetEntry **ppList,
41314   int iDepth
41315 ){
41316   struct RowSetEntry *p;         /* Root of the new tree */
41317   struct RowSetEntry *pLeft;     /* Left subtree */
41318   if( *ppList==0 ){
41319     return 0;
41320   }
41321   if( iDepth==1 ){
41322     p = *ppList;
41323     *ppList = p->pRight;
41324     p->pLeft = p->pRight = 0;
41325     return p;
41326   }
41327   pLeft = rowSetNDeepTree(ppList, iDepth-1);
41328   p = *ppList;
41329   if( p==0 ){
41330     return pLeft;
41331   }
41332   p->pLeft = pLeft;
41333   *ppList = p->pRight;
41334   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
41335   return p;
41336 }
41337 
41338 /*
41339 ** Convert a sorted list of elements into a binary tree. Make the tree
41340 ** as deep as it needs to be in order to contain the entire list.
41341 */
41342 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
41343   int iDepth;           /* Depth of the tree so far */
41344   struct RowSetEntry *p;       /* Current tree root */
41345   struct RowSetEntry *pLeft;   /* Left subtree */
41346 
41347   assert( pList!=0 );
41348   p = pList;
41349   pList = p->pRight;
41350   p->pLeft = p->pRight = 0;
41351   for(iDepth=1; pList; iDepth++){
41352     pLeft = p;
41353     p = pList;
41354     pList = p->pRight;
41355     p->pLeft = pLeft;
41356     p->pRight = rowSetNDeepTree(&pList, iDepth);
41357   }
41358   return p;
41359 }
41360 
41361 /*
41362 ** Take all the entries on p->pEntry and on the trees in p->pForest and
41363 ** sort them all together into one big ordered list on p->pEntry.
41364 **
41365 ** This routine should only be called once in the life of a RowSet.
41366 */
41367 static void rowSetToList(RowSet *p){
41368 
41369   /* This routine is called only once */
41370   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
41371 
41372   if( (p->rsFlags & ROWSET_SORTED)==0 ){
41373     p->pEntry = rowSetEntrySort(p->pEntry);
41374   }
41375 
41376   /* While this module could theoretically support it, sqlite3RowSetNext()
41377   ** is never called after sqlite3RowSetText() for the same RowSet.  So
41378   ** there is never a forest to deal with.  Should this change, simply
41379   ** remove the assert() and the #if 0. */
41380   assert( p->pForest==0 );
41381 #if 0
41382   while( p->pForest ){
41383     struct RowSetEntry *pTree = p->pForest->pLeft;
41384     if( pTree ){
41385       struct RowSetEntry *pHead, *pTail;
41386       rowSetTreeToList(pTree, &pHead, &pTail);
41387       p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
41388     }
41389     p->pForest = p->pForest->pRight;
41390   }
41391 #endif
41392   p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
41393 }
41394 
41395 /*
41396 ** Extract the smallest element from the RowSet.
41397 ** Write the element into *pRowid.  Return 1 on success.  Return
41398 ** 0 if the RowSet is already empty.
41399 **
41400 ** After this routine has been called, the sqlite3RowSetInsert()
41401 ** routine may not be called again.
41402 */
41403 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
41404   assert( p!=0 );
41405 
41406   /* Merge the forest into a single sorted list on first call */
41407   if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
41408 
41409   /* Return the next entry on the list */
41410   if( p->pEntry ){
41411     *pRowid = p->pEntry->v;
41412     p->pEntry = p->pEntry->pRight;
41413     if( p->pEntry==0 ){
41414       sqlite3RowSetClear(p);
41415     }
41416     return 1;
41417   }else{
41418     return 0;
41419   }
41420 }
41421 
41422 /*
41423 ** Check to see if element iRowid was inserted into the rowset as
41424 ** part of any insert batch prior to iBatch.  Return 1 or 0.
41425 **
41426 ** If this is the first test of a new batch and if there exist entries
41427 ** on pRowSet->pEntry, then sort those entries into the forest at
41428 ** pRowSet->pForest so that they can be tested.
41429 */
41430 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
41431   struct RowSetEntry *p, *pTree;
41432 
41433   /* This routine is never called after sqlite3RowSetNext() */
41434   assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
41435 
41436   /* Sort entries into the forest on the first test of a new batch
41437   */
41438   if( iBatch!=pRowSet->iBatch ){
41439     p = pRowSet->pEntry;
41440     if( p ){
41441       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
41442       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
41443         p = rowSetEntrySort(p);
41444       }
41445       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
41446         ppPrevTree = &pTree->pRight;
41447         if( pTree->pLeft==0 ){
41448           pTree->pLeft = rowSetListToTree(p);
41449           break;
41450         }else{
41451           struct RowSetEntry *pAux, *pTail;
41452           rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
41453           pTree->pLeft = 0;
41454           p = rowSetEntryMerge(pAux, p);
41455         }
41456       }
41457       if( pTree==0 ){
41458         *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
41459         if( pTree ){
41460           pTree->v = 0;
41461           pTree->pRight = 0;
41462           pTree->pLeft = rowSetListToTree(p);
41463         }
41464       }
41465       pRowSet->pEntry = 0;
41466       pRowSet->pLast = 0;
41467       pRowSet->rsFlags |= ROWSET_SORTED;
41468     }
41469     pRowSet->iBatch = iBatch;
41470   }
41471 
41472   /* Test to see if the iRowid value appears anywhere in the forest.
41473   ** Return 1 if it does and 0 if not.
41474   */
41475   for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
41476     p = pTree->pLeft;
41477     while( p ){
41478       if( p->v<iRowid ){
41479         p = p->pRight;
41480       }else if( p->v>iRowid ){
41481         p = p->pLeft;
41482       }else{
41483         return 1;
41484       }
41485     }
41486   }
41487   return 0;
41488 }
41489 
41490 /************** End of rowset.c **********************************************/
41491 /************** Begin file pager.c *******************************************/
41492 /*
41493 ** 2001 September 15
41494 **
41495 ** The author disclaims copyright to this source code.  In place of
41496 ** a legal notice, here is a blessing:
41497 **
41498 **    May you do good and not evil.
41499 **    May you find forgiveness for yourself and forgive others.
41500 **    May you share freely, never taking more than you give.
41501 **
41502 *************************************************************************
41503 ** This is the implementation of the page cache subsystem or "pager".
41504 **
41505 ** The pager is used to access a database disk file.  It implements
41506 ** atomic commit and rollback through the use of a journal file that
41507 ** is separate from the database file.  The pager also implements file
41508 ** locking to prevent two processes from writing the same database
41509 ** file simultaneously, or one process from reading the database while
41510 ** another is writing.
41511 */
41512 #ifndef SQLITE_OMIT_DISKIO
41513 /************** Include wal.h in the middle of pager.c ***********************/
41514 /************** Begin file wal.h *********************************************/
41515 /*
41516 ** 2010 February 1
41517 **
41518 ** The author disclaims copyright to this source code.  In place of
41519 ** a legal notice, here is a blessing:
41520 **
41521 **    May you do good and not evil.
41522 **    May you find forgiveness for yourself and forgive others.
41523 **    May you share freely, never taking more than you give.
41524 **
41525 *************************************************************************
41526 ** This header file defines the interface to the write-ahead logging
41527 ** system. Refer to the comments below and the header comment attached to
41528 ** the implementation of each function in log.c for further details.
41529 */
41530 
41531 #ifndef _WAL_H_
41532 #define _WAL_H_
41533 
41534 
41535 /* Additional values that can be added to the sync_flags argument of
41536 ** sqlite3WalFrames():
41537 */
41538 #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
41539 #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
41540 
41541 #ifdef SQLITE_OMIT_WAL
41542 # define sqlite3WalOpen(x,y,z)                   0
41543 # define sqlite3WalLimit(x,y)
41544 # define sqlite3WalClose(w,x,y,z)                0
41545 # define sqlite3WalBeginReadTransaction(y,z)     0
41546 # define sqlite3WalEndReadTransaction(z)
41547 # define sqlite3WalDbsize(y)                     0
41548 # define sqlite3WalBeginWriteTransaction(y)      0
41549 # define sqlite3WalEndWriteTransaction(x)        0
41550 # define sqlite3WalUndo(x,y,z)                   0
41551 # define sqlite3WalSavepoint(y,z)
41552 # define sqlite3WalSavepointUndo(y,z)            0
41553 # define sqlite3WalFrames(u,v,w,x,y,z)           0
41554 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
41555 # define sqlite3WalCallback(z)                   0
41556 # define sqlite3WalExclusiveMode(y,z)            0
41557 # define sqlite3WalHeapMemory(z)                 0
41558 # define sqlite3WalFramesize(z)                  0
41559 # define sqlite3WalFindFrame(x,y,z)              0
41560 #else
41561 
41562 #define WAL_SAVEPOINT_NDATA 4
41563 
41564 /* Connection to a write-ahead log (WAL) file.
41565 ** There is one object of this type for each pager.
41566 */
41567 typedef struct Wal Wal;
41568 
41569 /* Open and close a connection to a write-ahead log. */
41570 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
41571 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
41572 
41573 /* Set the limiting size of a WAL file. */
41574 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
41575 
41576 /* Used by readers to open (lock) and close (unlock) a snapshot.  A
41577 ** snapshot is like a read-transaction.  It is the state of the database
41578 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
41579 ** preserves the current state even if the other threads or processes
41580 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
41581 ** transaction and releases the lock.
41582 */
41583 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
41584 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
41585 
41586 /* Read a page from the write-ahead log, if it is present. */
41587 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
41588 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
41589 
41590 /* If the WAL is not empty, return the size of the database. */
41591 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
41592 
41593 /* Obtain or release the WRITER lock. */
41594 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
41595 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
41596 
41597 /* Undo any frames written (but not committed) to the log */
41598 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
41599 
41600 /* Return an integer that records the current (uncommitted) write
41601 ** position in the WAL */
41602 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
41603 
41604 /* Move the write position of the WAL back to iFrame.  Called in
41605 ** response to a ROLLBACK TO command. */
41606 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
41607 
41608 /* Write a frame or frames to the log. */
41609 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
41610 
41611 /* Copy pages from the log to the database file */
41612 SQLITE_PRIVATE int sqlite3WalCheckpoint(
41613   Wal *pWal,                      /* Write-ahead log connection */
41614   int eMode,                      /* One of PASSIVE, FULL and RESTART */
41615   int (*xBusy)(void*),            /* Function to call when busy */
41616   void *pBusyArg,                 /* Context argument for xBusyHandler */
41617   int sync_flags,                 /* Flags to sync db file with (or 0) */
41618   int nBuf,                       /* Size of buffer nBuf */
41619   u8 *zBuf,                       /* Temporary buffer to use */
41620   int *pnLog,                     /* OUT: Number of frames in WAL */
41621   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
41622 );
41623 
41624 /* Return the value to pass to a sqlite3_wal_hook callback, the
41625 ** number of frames in the WAL at the point of the last commit since
41626 ** sqlite3WalCallback() was called.  If no commits have occurred since
41627 ** the last call, then return 0.
41628 */
41629 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
41630 
41631 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
41632 ** by the pager layer on the database file.
41633 */
41634 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
41635 
41636 /* Return true if the argument is non-NULL and the WAL module is using
41637 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
41638 ** WAL module is using shared-memory, return false.
41639 */
41640 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
41641 
41642 #ifdef SQLITE_ENABLE_ZIPVFS
41643 /* If the WAL file is not empty, return the number of bytes of content
41644 ** stored in each frame (i.e. the db page-size when the WAL was created).
41645 */
41646 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
41647 #endif
41648 
41649 #endif /* ifndef SQLITE_OMIT_WAL */
41650 #endif /* _WAL_H_ */
41651 
41652 /************** End of wal.h *************************************************/
41653 /************** Continuing where we left off in pager.c **********************/
41654 
41655 
41656 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
41657 **
41658 ** This comment block describes invariants that hold when using a rollback
41659 ** journal.  These invariants do not apply for journal_mode=WAL,
41660 ** journal_mode=MEMORY, or journal_mode=OFF.
41661 **
41662 ** Within this comment block, a page is deemed to have been synced
41663 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
41664 ** Otherwise, the page is not synced until the xSync method of the VFS
41665 ** is called successfully on the file containing the page.
41666 **
41667 ** Definition:  A page of the database file is said to be "overwriteable" if
41668 ** one or more of the following are true about the page:
41669 **
41670 **     (a)  The original content of the page as it was at the beginning of
41671 **          the transaction has been written into the rollback journal and
41672 **          synced.
41673 **
41674 **     (b)  The page was a freelist leaf page at the start of the transaction.
41675 **
41676 **     (c)  The page number is greater than the largest page that existed in
41677 **          the database file at the start of the transaction.
41678 **
41679 ** (1) A page of the database file is never overwritten unless one of the
41680 **     following are true:
41681 **
41682 **     (a) The page and all other pages on the same sector are overwriteable.
41683 **
41684 **     (b) The atomic page write optimization is enabled, and the entire
41685 **         transaction other than the update of the transaction sequence
41686 **         number consists of a single page change.
41687 **
41688 ** (2) The content of a page written into the rollback journal exactly matches
41689 **     both the content in the database when the rollback journal was written
41690 **     and the content in the database at the beginning of the current
41691 **     transaction.
41692 **
41693 ** (3) Writes to the database file are an integer multiple of the page size
41694 **     in length and are aligned on a page boundary.
41695 **
41696 ** (4) Reads from the database file are either aligned on a page boundary and
41697 **     an integer multiple of the page size in length or are taken from the
41698 **     first 100 bytes of the database file.
41699 **
41700 ** (5) All writes to the database file are synced prior to the rollback journal
41701 **     being deleted, truncated, or zeroed.
41702 **
41703 ** (6) If a master journal file is used, then all writes to the database file
41704 **     are synced prior to the master journal being deleted.
41705 **
41706 ** Definition: Two databases (or the same database at two points it time)
41707 ** are said to be "logically equivalent" if they give the same answer to
41708 ** all queries.  Note in particular the content of freelist leaf
41709 ** pages can be changed arbitrarily without affecting the logical equivalence
41710 ** of the database.
41711 **
41712 ** (7) At any time, if any subset, including the empty set and the total set,
41713 **     of the unsynced changes to a rollback journal are removed and the
41714 **     journal is rolled back, the resulting database file will be logically
41715 **     equivalent to the database file at the beginning of the transaction.
41716 **
41717 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
41718 **     is called to restore the database file to the same size it was at
41719 **     the beginning of the transaction.  (In some VFSes, the xTruncate
41720 **     method is a no-op, but that does not change the fact the SQLite will
41721 **     invoke it.)
41722 **
41723 ** (9) Whenever the database file is modified, at least one bit in the range
41724 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
41725 **     the EXCLUSIVE lock, thus signaling other connections on the same
41726 **     database to flush their caches.
41727 **
41728 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
41729 **      than one billion transactions.
41730 **
41731 ** (11) A database file is well-formed at the beginning and at the conclusion
41732 **      of every transaction.
41733 **
41734 ** (12) An EXCLUSIVE lock is held on the database file when writing to
41735 **      the database file.
41736 **
41737 ** (13) A SHARED lock is held on the database file while reading any
41738 **      content out of the database file.
41739 **
41740 ******************************************************************************/
41741 
41742 /*
41743 ** Macros for troubleshooting.  Normally turned off
41744 */
41745 #if 0
41746 int sqlite3PagerTrace=1;  /* True to enable tracing */
41747 #define sqlite3DebugPrintf printf
41748 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
41749 #else
41750 #define PAGERTRACE(X)
41751 #endif
41752 
41753 /*
41754 ** The following two macros are used within the PAGERTRACE() macros above
41755 ** to print out file-descriptors.
41756 **
41757 ** PAGERID() takes a pointer to a Pager struct as its argument. The
41758 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
41759 ** struct as its argument.
41760 */
41761 #define PAGERID(p) ((int)(p->fd))
41762 #define FILEHANDLEID(fd) ((int)fd)
41763 
41764 /*
41765 ** The Pager.eState variable stores the current 'state' of a pager. A
41766 ** pager may be in any one of the seven states shown in the following
41767 ** state diagram.
41768 **
41769 **                            OPEN <------+------+
41770 **                              |         |      |
41771 **                              V         |      |
41772 **               +---------> READER-------+      |
41773 **               |              |                |
41774 **               |              V                |
41775 **               |<-------WRITER_LOCKED------> ERROR
41776 **               |              |                ^
41777 **               |              V                |
41778 **               |<------WRITER_CACHEMOD-------->|
41779 **               |              |                |
41780 **               |              V                |
41781 **               |<-------WRITER_DBMOD---------->|
41782 **               |              |                |
41783 **               |              V                |
41784 **               +<------WRITER_FINISHED-------->+
41785 **
41786 **
41787 ** List of state transitions and the C [function] that performs each:
41788 **
41789 **   OPEN              -> READER              [sqlite3PagerSharedLock]
41790 **   READER            -> OPEN                [pager_unlock]
41791 **
41792 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
41793 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
41794 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
41795 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
41796 **   WRITER_***        -> READER              [pager_end_transaction]
41797 **
41798 **   WRITER_***        -> ERROR               [pager_error]
41799 **   ERROR             -> OPEN                [pager_unlock]
41800 **
41801 **
41802 **  OPEN:
41803 **
41804 **    The pager starts up in this state. Nothing is guaranteed in this
41805 **    state - the file may or may not be locked and the database size is
41806 **    unknown. The database may not be read or written.
41807 **
41808 **    * No read or write transaction is active.
41809 **    * Any lock, or no lock at all, may be held on the database file.
41810 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
41811 **
41812 **  READER:
41813 **
41814 **    In this state all the requirements for reading the database in
41815 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
41816 **    was) in exclusive-locking mode, a user-level read transaction is
41817 **    open. The database size is known in this state.
41818 **
41819 **    A connection running with locking_mode=normal enters this state when
41820 **    it opens a read-transaction on the database and returns to state
41821 **    OPEN after the read-transaction is completed. However a connection
41822 **    running in locking_mode=exclusive (including temp databases) remains in
41823 **    this state even after the read-transaction is closed. The only way
41824 **    a locking_mode=exclusive connection can transition from READER to OPEN
41825 **    is via the ERROR state (see below).
41826 **
41827 **    * A read transaction may be active (but a write-transaction cannot).
41828 **    * A SHARED or greater lock is held on the database file.
41829 **    * The dbSize variable may be trusted (even if a user-level read
41830 **      transaction is not active). The dbOrigSize and dbFileSize variables
41831 **      may not be trusted at this point.
41832 **    * If the database is a WAL database, then the WAL connection is open.
41833 **    * Even if a read-transaction is not open, it is guaranteed that
41834 **      there is no hot-journal in the file-system.
41835 **
41836 **  WRITER_LOCKED:
41837 **
41838 **    The pager moves to this state from READER when a write-transaction
41839 **    is first opened on the database. In WRITER_LOCKED state, all locks
41840 **    required to start a write-transaction are held, but no actual
41841 **    modifications to the cache or database have taken place.
41842 **
41843 **    In rollback mode, a RESERVED or (if the transaction was opened with
41844 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
41845 **    moving to this state, but the journal file is not written to or opened
41846 **    to in this state. If the transaction is committed or rolled back while
41847 **    in WRITER_LOCKED state, all that is required is to unlock the database
41848 **    file.
41849 **
41850 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
41851 **    If the connection is running with locking_mode=exclusive, an attempt
41852 **    is made to obtain an EXCLUSIVE lock on the database file.
41853 **
41854 **    * A write transaction is active.
41855 **    * If the connection is open in rollback-mode, a RESERVED or greater
41856 **      lock is held on the database file.
41857 **    * If the connection is open in WAL-mode, a WAL write transaction
41858 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
41859 **      called).
41860 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
41861 **    * The contents of the pager cache have not been modified.
41862 **    * The journal file may or may not be open.
41863 **    * Nothing (not even the first header) has been written to the journal.
41864 **
41865 **  WRITER_CACHEMOD:
41866 **
41867 **    A pager moves from WRITER_LOCKED state to this state when a page is
41868 **    first modified by the upper layer. In rollback mode the journal file
41869 **    is opened (if it is not already open) and a header written to the
41870 **    start of it. The database file on disk has not been modified.
41871 **
41872 **    * A write transaction is active.
41873 **    * A RESERVED or greater lock is held on the database file.
41874 **    * The journal file is open and the first header has been written
41875 **      to it, but the header has not been synced to disk.
41876 **    * The contents of the page cache have been modified.
41877 **
41878 **  WRITER_DBMOD:
41879 **
41880 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
41881 **    when it modifies the contents of the database file. WAL connections
41882 **    never enter this state (since they do not modify the database file,
41883 **    just the log file).
41884 **
41885 **    * A write transaction is active.
41886 **    * An EXCLUSIVE or greater lock is held on the database file.
41887 **    * The journal file is open and the first header has been written
41888 **      and synced to disk.
41889 **    * The contents of the page cache have been modified (and possibly
41890 **      written to disk).
41891 **
41892 **  WRITER_FINISHED:
41893 **
41894 **    It is not possible for a WAL connection to enter this state.
41895 **
41896 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
41897 **    state after the entire transaction has been successfully written into the
41898 **    database file. In this state the transaction may be committed simply
41899 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is
41900 **    not possible to modify the database further. At this point, the upper
41901 **    layer must either commit or rollback the transaction.
41902 **
41903 **    * A write transaction is active.
41904 **    * An EXCLUSIVE or greater lock is held on the database file.
41905 **    * All writing and syncing of journal and database data has finished.
41906 **      If no error occurred, all that remains is to finalize the journal to
41907 **      commit the transaction. If an error did occur, the caller will need
41908 **      to rollback the transaction.
41909 **
41910 **  ERROR:
41911 **
41912 **    The ERROR state is entered when an IO or disk-full error (including
41913 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
41914 **    difficult to be sure that the in-memory pager state (cache contents,
41915 **    db size etc.) are consistent with the contents of the file-system.
41916 **
41917 **    Temporary pager files may enter the ERROR state, but in-memory pagers
41918 **    cannot.
41919 **
41920 **    For example, if an IO error occurs while performing a rollback,
41921 **    the contents of the page-cache may be left in an inconsistent state.
41922 **    At this point it would be dangerous to change back to READER state
41923 **    (as usually happens after a rollback). Any subsequent readers might
41924 **    report database corruption (due to the inconsistent cache), and if
41925 **    they upgrade to writers, they may inadvertently corrupt the database
41926 **    file. To avoid this hazard, the pager switches into the ERROR state
41927 **    instead of READER following such an error.
41928 **
41929 **    Once it has entered the ERROR state, any attempt to use the pager
41930 **    to read or write data returns an error. Eventually, once all
41931 **    outstanding transactions have been abandoned, the pager is able to
41932 **    transition back to OPEN state, discarding the contents of the
41933 **    page-cache and any other in-memory state at the same time. Everything
41934 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
41935 **    when a read-transaction is next opened on the pager (transitioning
41936 **    the pager into READER state). At that point the system has recovered
41937 **    from the error.
41938 **
41939 **    Specifically, the pager jumps into the ERROR state if:
41940 **
41941 **      1. An error occurs while attempting a rollback. This happens in
41942 **         function sqlite3PagerRollback().
41943 **
41944 **      2. An error occurs while attempting to finalize a journal file
41945 **         following a commit in function sqlite3PagerCommitPhaseTwo().
41946 **
41947 **      3. An error occurs while attempting to write to the journal or
41948 **         database file in function pagerStress() in order to free up
41949 **         memory.
41950 **
41951 **    In other cases, the error is returned to the b-tree layer. The b-tree
41952 **    layer then attempts a rollback operation. If the error condition
41953 **    persists, the pager enters the ERROR state via condition (1) above.
41954 **
41955 **    Condition (3) is necessary because it can be triggered by a read-only
41956 **    statement executed within a transaction. In this case, if the error
41957 **    code were simply returned to the user, the b-tree layer would not
41958 **    automatically attempt a rollback, as it assumes that an error in a
41959 **    read-only statement cannot leave the pager in an internally inconsistent
41960 **    state.
41961 **
41962 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
41963 **    * There are one or more outstanding references to pages (after the
41964 **      last reference is dropped the pager should move back to OPEN state).
41965 **    * The pager is not an in-memory pager.
41966 **
41967 **
41968 ** Notes:
41969 **
41970 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
41971 **     connection is open in WAL mode. A WAL connection is always in one
41972 **     of the first four states.
41973 **
41974 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
41975 **     state. There are two exceptions: immediately after exclusive-mode has
41976 **     been turned on (and before any read or write transactions are
41977 **     executed), and when the pager is leaving the "error state".
41978 **
41979 **   * See also: assert_pager_state().
41980 */
41981 #define PAGER_OPEN                  0
41982 #define PAGER_READER                1
41983 #define PAGER_WRITER_LOCKED         2
41984 #define PAGER_WRITER_CACHEMOD       3
41985 #define PAGER_WRITER_DBMOD          4
41986 #define PAGER_WRITER_FINISHED       5
41987 #define PAGER_ERROR                 6
41988 
41989 /*
41990 ** The Pager.eLock variable is almost always set to one of the
41991 ** following locking-states, according to the lock currently held on
41992 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
41993 ** This variable is kept up to date as locks are taken and released by
41994 ** the pagerLockDb() and pagerUnlockDb() wrappers.
41995 **
41996 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
41997 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
41998 ** the operation was successful. In these circumstances pagerLockDb() and
41999 ** pagerUnlockDb() take a conservative approach - eLock is always updated
42000 ** when unlocking the file, and only updated when locking the file if the
42001 ** VFS call is successful. This way, the Pager.eLock variable may be set
42002 ** to a less exclusive (lower) value than the lock that is actually held
42003 ** at the system level, but it is never set to a more exclusive value.
42004 **
42005 ** This is usually safe. If an xUnlock fails or appears to fail, there may
42006 ** be a few redundant xLock() calls or a lock may be held for longer than
42007 ** required, but nothing really goes wrong.
42008 **
42009 ** The exception is when the database file is unlocked as the pager moves
42010 ** from ERROR to OPEN state. At this point there may be a hot-journal file
42011 ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
42012 ** transition, by the same pager or any other). If the call to xUnlock()
42013 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
42014 ** can confuse the call to xCheckReservedLock() call made later as part
42015 ** of hot-journal detection.
42016 **
42017 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
42018 ** lock held by this process or any others". So xCheckReservedLock may
42019 ** return true because the caller itself is holding an EXCLUSIVE lock (but
42020 ** doesn't know it because of a previous error in xUnlock). If this happens
42021 ** a hot-journal may be mistaken for a journal being created by an active
42022 ** transaction in another process, causing SQLite to read from the database
42023 ** without rolling it back.
42024 **
42025 ** To work around this, if a call to xUnlock() fails when unlocking the
42026 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
42027 ** is only changed back to a real locking state after a successful call
42028 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
42029 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
42030 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
42031 ** lock on the database file before attempting to roll it back. See function
42032 ** PagerSharedLock() for more detail.
42033 **
42034 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
42035 ** PAGER_OPEN state.
42036 */
42037 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
42038 
42039 /*
42040 ** A macro used for invoking the codec if there is one
42041 */
42042 #ifdef SQLITE_HAS_CODEC
42043 # define CODEC1(P,D,N,X,E) \
42044     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
42045 # define CODEC2(P,D,N,X,E,O) \
42046     if( P->xCodec==0 ){ O=(char*)D; }else \
42047     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
42048 #else
42049 # define CODEC1(P,D,N,X,E)   /* NO-OP */
42050 # define CODEC2(P,D,N,X,E,O) O=(char*)D
42051 #endif
42052 
42053 /*
42054 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
42055 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
42056 ** This could conceivably cause corruption following a power failure on
42057 ** such a system. This is currently an undocumented limit.
42058 */
42059 #define MAX_SECTOR_SIZE 0x10000
42060 
42061 /*
42062 ** An instance of the following structure is allocated for each active
42063 ** savepoint and statement transaction in the system. All such structures
42064 ** are stored in the Pager.aSavepoint[] array, which is allocated and
42065 ** resized using sqlite3Realloc().
42066 **
42067 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
42068 ** set to 0. If a journal-header is written into the main journal while
42069 ** the savepoint is active, then iHdrOffset is set to the byte offset
42070 ** immediately following the last journal record written into the main
42071 ** journal before the journal-header. This is required during savepoint
42072 ** rollback (see pagerPlaybackSavepoint()).
42073 */
42074 typedef struct PagerSavepoint PagerSavepoint;
42075 struct PagerSavepoint {
42076   i64 iOffset;                 /* Starting offset in main journal */
42077   i64 iHdrOffset;              /* See above */
42078   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
42079   Pgno nOrig;                  /* Original number of pages in file */
42080   Pgno iSubRec;                /* Index of first record in sub-journal */
42081 #ifndef SQLITE_OMIT_WAL
42082   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
42083 #endif
42084 };
42085 
42086 /*
42087 ** Bits of the Pager.doNotSpill flag.  See further description below.
42088 */
42089 #define SPILLFLAG_OFF         0x01      /* Never spill cache.  Set via pragma */
42090 #define SPILLFLAG_ROLLBACK    0x02      /* Current rolling back, so do not spill */
42091 #define SPILLFLAG_NOSYNC      0x04      /* Spill is ok, but do not sync */
42092 
42093 /*
42094 ** An open page cache is an instance of struct Pager. A description of
42095 ** some of the more important member variables follows:
42096 **
42097 ** eState
42098 **
42099 **   The current 'state' of the pager object. See the comment and state
42100 **   diagram above for a description of the pager state.
42101 **
42102 ** eLock
42103 **
42104 **   For a real on-disk database, the current lock held on the database file -
42105 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
42106 **
42107 **   For a temporary or in-memory database (neither of which require any
42108 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
42109 **   databases always have Pager.exclusiveMode==1, this tricks the pager
42110 **   logic into thinking that it already has all the locks it will ever
42111 **   need (and no reason to release them).
42112 **
42113 **   In some (obscure) circumstances, this variable may also be set to
42114 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
42115 **   details.
42116 **
42117 ** changeCountDone
42118 **
42119 **   This boolean variable is used to make sure that the change-counter
42120 **   (the 4-byte header field at byte offset 24 of the database file) is
42121 **   not updated more often than necessary.
42122 **
42123 **   It is set to true when the change-counter field is updated, which
42124 **   can only happen if an exclusive lock is held on the database file.
42125 **   It is cleared (set to false) whenever an exclusive lock is
42126 **   relinquished on the database file. Each time a transaction is committed,
42127 **   The changeCountDone flag is inspected. If it is true, the work of
42128 **   updating the change-counter is omitted for the current transaction.
42129 **
42130 **   This mechanism means that when running in exclusive mode, a connection
42131 **   need only update the change-counter once, for the first transaction
42132 **   committed.
42133 **
42134 ** setMaster
42135 **
42136 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
42137 **   (or may not) specify a master-journal name to be written into the
42138 **   journal file before it is synced to disk.
42139 **
42140 **   Whether or not a journal file contains a master-journal pointer affects
42141 **   the way in which the journal file is finalized after the transaction is
42142 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
42143 **   If a journal file does not contain a master-journal pointer, it is
42144 **   finalized by overwriting the first journal header with zeroes. If
42145 **   it does contain a master-journal pointer the journal file is finalized
42146 **   by truncating it to zero bytes, just as if the connection were
42147 **   running in "journal_mode=truncate" mode.
42148 **
42149 **   Journal files that contain master journal pointers cannot be finalized
42150 **   simply by overwriting the first journal-header with zeroes, as the
42151 **   master journal pointer could interfere with hot-journal rollback of any
42152 **   subsequently interrupted transaction that reuses the journal file.
42153 **
42154 **   The flag is cleared as soon as the journal file is finalized (either
42155 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
42156 **   journal file from being successfully finalized, the setMaster flag
42157 **   is cleared anyway (and the pager will move to ERROR state).
42158 **
42159 ** doNotSpill
42160 **
42161 **   This variables control the behavior of cache-spills  (calls made by
42162 **   the pcache module to the pagerStress() routine to write cached data
42163 **   to the file-system in order to free up memory).
42164 **
42165 **   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
42166 **   writing to the database from pagerStress() is disabled altogether.
42167 **   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
42168 **   comes up during savepoint rollback that requires the pcache module
42169 **   to allocate a new page to prevent the journal file from being written
42170 **   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
42171 **   case is a user preference.
42172 **
42173 **   If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
42174 **   is permitted, but syncing the journal file is not. This flag is set
42175 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
42176 **   the database page-size in order to prevent a journal sync from happening
42177 **   in between the journalling of two pages on the same sector.
42178 **
42179 ** subjInMemory
42180 **
42181 **   This is a boolean variable. If true, then any required sub-journal
42182 **   is opened as an in-memory journal file. If false, then in-memory
42183 **   sub-journals are only used for in-memory pager files.
42184 **
42185 **   This variable is updated by the upper layer each time a new
42186 **   write-transaction is opened.
42187 **
42188 ** dbSize, dbOrigSize, dbFileSize
42189 **
42190 **   Variable dbSize is set to the number of pages in the database file.
42191 **   It is valid in PAGER_READER and higher states (all states except for
42192 **   OPEN and ERROR).
42193 **
42194 **   dbSize is set based on the size of the database file, which may be
42195 **   larger than the size of the database (the value stored at offset
42196 **   28 of the database header by the btree). If the size of the file
42197 **   is not an integer multiple of the page-size, the value stored in
42198 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
42199 **   Except, any file that is greater than 0 bytes in size is considered
42200 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
42201 **   to dbSize==1).
42202 **
42203 **   During a write-transaction, if pages with page-numbers greater than
42204 **   dbSize are modified in the cache, dbSize is updated accordingly.
42205 **   Similarly, if the database is truncated using PagerTruncateImage(),
42206 **   dbSize is updated.
42207 **
42208 **   Variables dbOrigSize and dbFileSize are valid in states
42209 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
42210 **   variable at the start of the transaction. It is used during rollback,
42211 **   and to determine whether or not pages need to be journalled before
42212 **   being modified.
42213 **
42214 **   Throughout a write-transaction, dbFileSize contains the size of
42215 **   the file on disk in pages. It is set to a copy of dbSize when the
42216 **   write-transaction is first opened, and updated when VFS calls are made
42217 **   to write or truncate the database file on disk.
42218 **
42219 **   The only reason the dbFileSize variable is required is to suppress
42220 **   unnecessary calls to xTruncate() after committing a transaction. If,
42221 **   when a transaction is committed, the dbFileSize variable indicates
42222 **   that the database file is larger than the database image (Pager.dbSize),
42223 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
42224 **   to measure the database file on disk, and then truncates it if required.
42225 **   dbFileSize is not used when rolling back a transaction. In this case
42226 **   pager_truncate() is called unconditionally (which means there may be
42227 **   a call to xFilesize() that is not strictly required). In either case,
42228 **   pager_truncate() may cause the file to become smaller or larger.
42229 **
42230 ** dbHintSize
42231 **
42232 **   The dbHintSize variable is used to limit the number of calls made to
42233 **   the VFS xFileControl(FCNTL_SIZE_HINT) method.
42234 **
42235 **   dbHintSize is set to a copy of the dbSize variable when a
42236 **   write-transaction is opened (at the same time as dbFileSize and
42237 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
42238 **   dbHintSize is increased to the number of pages that correspond to the
42239 **   size-hint passed to the method call. See pager_write_pagelist() for
42240 **   details.
42241 **
42242 ** errCode
42243 **
42244 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
42245 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
42246 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
42247 **   sub-codes.
42248 */
42249 struct Pager {
42250   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
42251   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
42252   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
42253   u8 useJournal;              /* Use a rollback journal on this file */
42254   u8 noSync;                  /* Do not sync the journal if true */
42255   u8 fullSync;                /* Do extra syncs of the journal for robustness */
42256   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
42257   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
42258   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
42259   u8 tempFile;                /* zFilename is a temporary or immutable file */
42260   u8 noLock;                  /* Do not lock (except in WAL mode) */
42261   u8 readOnly;                /* True for a read-only database */
42262   u8 memDb;                   /* True to inhibit all file I/O */
42263 
42264   /**************************************************************************
42265   ** The following block contains those class members that change during
42266   ** routine operation.  Class members not in this block are either fixed
42267   ** when the pager is first created or else only change when there is a
42268   ** significant mode change (such as changing the page_size, locking_mode,
42269   ** or the journal_mode).  From another view, these class members describe
42270   ** the "state" of the pager, while other class members describe the
42271   ** "configuration" of the pager.
42272   */
42273   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
42274   u8 eLock;                   /* Current lock held on database file */
42275   u8 changeCountDone;         /* Set after incrementing the change-counter */
42276   u8 setMaster;               /* True if a m-j name has been written to jrnl */
42277   u8 doNotSpill;              /* Do not spill the cache when non-zero */
42278   u8 subjInMemory;            /* True to use in-memory sub-journals */
42279   u8 bUseFetch;               /* True to use xFetch() */
42280   u8 hasBeenUsed;             /* True if any content previously read from this pager*/
42281   Pgno dbSize;                /* Number of pages in the database */
42282   Pgno dbOrigSize;            /* dbSize before the current transaction */
42283   Pgno dbFileSize;            /* Number of pages in the database file */
42284   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
42285   int errCode;                /* One of several kinds of errors */
42286   int nRec;                   /* Pages journalled since last j-header written */
42287   u32 cksumInit;              /* Quasi-random value added to every checksum */
42288   u32 nSubRec;                /* Number of records written to sub-journal */
42289   Bitvec *pInJournal;         /* One bit for each page in the database file */
42290   sqlite3_file *fd;           /* File descriptor for database */
42291   sqlite3_file *jfd;          /* File descriptor for main journal */
42292   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
42293   i64 journalOff;             /* Current write offset in the journal file */
42294   i64 journalHdr;             /* Byte offset to previous journal header */
42295   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
42296   PagerSavepoint *aSavepoint; /* Array of active savepoints */
42297   int nSavepoint;             /* Number of elements in aSavepoint[] */
42298   u32 iDataVersion;           /* Changes whenever database content changes */
42299   char dbFileVers[16];        /* Changes whenever database file changes */
42300 
42301   int nMmapOut;               /* Number of mmap pages currently outstanding */
42302   sqlite3_int64 szMmap;       /* Desired maximum mmap size */
42303   PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
42304   /*
42305   ** End of the routinely-changing class members
42306   ***************************************************************************/
42307 
42308   u16 nExtra;                 /* Add this many bytes to each in-memory page */
42309   i16 nReserve;               /* Number of unused bytes at end of each page */
42310   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
42311   u32 sectorSize;             /* Assumed sector size during rollback */
42312   int pageSize;               /* Number of bytes in a page */
42313   Pgno mxPgno;                /* Maximum allowed size of the database */
42314   i64 journalSizeLimit;       /* Size limit for persistent journal files */
42315   char *zFilename;            /* Name of the database file */
42316   char *zJournal;             /* Name of the journal file */
42317   int (*xBusyHandler)(void*); /* Function to call when busy */
42318   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
42319   int aStat[3];               /* Total cache hits, misses and writes */
42320 #ifdef SQLITE_TEST
42321   int nRead;                  /* Database pages read */
42322 #endif
42323   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
42324 #ifdef SQLITE_HAS_CODEC
42325   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
42326   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
42327   void (*xCodecFree)(void*);             /* Destructor for the codec */
42328   void *pCodec;               /* First argument to xCodec... methods */
42329 #endif
42330   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
42331   PCache *pPCache;            /* Pointer to page cache object */
42332 #ifndef SQLITE_OMIT_WAL
42333   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
42334   char *zWal;                 /* File name for write-ahead log */
42335 #endif
42336 };
42337 
42338 /*
42339 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
42340 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
42341 ** or CACHE_WRITE to sqlite3_db_status().
42342 */
42343 #define PAGER_STAT_HIT   0
42344 #define PAGER_STAT_MISS  1
42345 #define PAGER_STAT_WRITE 2
42346 
42347 /*
42348 ** The following global variables hold counters used for
42349 ** testing purposes only.  These variables do not exist in
42350 ** a non-testing build.  These variables are not thread-safe.
42351 */
42352 #ifdef SQLITE_TEST
42353 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
42354 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
42355 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
42356 # define PAGER_INCR(v)  v++
42357 #else
42358 # define PAGER_INCR(v)
42359 #endif
42360 
42361 
42362 
42363 /*
42364 ** Journal files begin with the following magic string.  The data
42365 ** was obtained from /dev/random.  It is used only as a sanity check.
42366 **
42367 ** Since version 2.8.0, the journal format contains additional sanity
42368 ** checking information.  If the power fails while the journal is being
42369 ** written, semi-random garbage data might appear in the journal
42370 ** file after power is restored.  If an attempt is then made
42371 ** to roll the journal back, the database could be corrupted.  The additional
42372 ** sanity checking data is an attempt to discover the garbage in the
42373 ** journal and ignore it.
42374 **
42375 ** The sanity checking information for the new journal format consists
42376 ** of a 32-bit checksum on each page of data.  The checksum covers both
42377 ** the page number and the pPager->pageSize bytes of data for the page.
42378 ** This cksum is initialized to a 32-bit random value that appears in the
42379 ** journal file right after the header.  The random initializer is important,
42380 ** because garbage data that appears at the end of a journal is likely
42381 ** data that was once in other files that have now been deleted.  If the
42382 ** garbage data came from an obsolete journal file, the checksums might
42383 ** be correct.  But by initializing the checksum to random value which
42384 ** is different for every journal, we minimize that risk.
42385 */
42386 static const unsigned char aJournalMagic[] = {
42387   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
42388 };
42389 
42390 /*
42391 ** The size of the of each page record in the journal is given by
42392 ** the following macro.
42393 */
42394 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
42395 
42396 /*
42397 ** The journal header size for this pager. This is usually the same
42398 ** size as a single disk sector. See also setSectorSize().
42399 */
42400 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
42401 
42402 /*
42403 ** The macro MEMDB is true if we are dealing with an in-memory database.
42404 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
42405 ** the value of MEMDB will be a constant and the compiler will optimize
42406 ** out code that would never execute.
42407 */
42408 #ifdef SQLITE_OMIT_MEMORYDB
42409 # define MEMDB 0
42410 #else
42411 # define MEMDB pPager->memDb
42412 #endif
42413 
42414 /*
42415 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
42416 ** interfaces to access the database using memory-mapped I/O.
42417 */
42418 #if SQLITE_MAX_MMAP_SIZE>0
42419 # define USEFETCH(x) ((x)->bUseFetch)
42420 #else
42421 # define USEFETCH(x) 0
42422 #endif
42423 
42424 /*
42425 ** The maximum legal page number is (2^31 - 1).
42426 */
42427 #define PAGER_MAX_PGNO 2147483647
42428 
42429 /*
42430 ** The argument to this macro is a file descriptor (type sqlite3_file*).
42431 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
42432 **
42433 ** This is so that expressions can be written as:
42434 **
42435 **   if( isOpen(pPager->jfd) ){ ...
42436 **
42437 ** instead of
42438 **
42439 **   if( pPager->jfd->pMethods ){ ...
42440 */
42441 #define isOpen(pFd) ((pFd)->pMethods)
42442 
42443 /*
42444 ** Return true if this pager uses a write-ahead log instead of the usual
42445 ** rollback journal. Otherwise false.
42446 */
42447 #ifndef SQLITE_OMIT_WAL
42448 static int pagerUseWal(Pager *pPager){
42449   return (pPager->pWal!=0);
42450 }
42451 #else
42452 # define pagerUseWal(x) 0
42453 # define pagerRollbackWal(x) 0
42454 # define pagerWalFrames(v,w,x,y) 0
42455 # define pagerOpenWalIfPresent(z) SQLITE_OK
42456 # define pagerBeginReadTransaction(z) SQLITE_OK
42457 #endif
42458 
42459 #ifndef NDEBUG
42460 /*
42461 ** Usage:
42462 **
42463 **   assert( assert_pager_state(pPager) );
42464 **
42465 ** This function runs many asserts to try to find inconsistencies in
42466 ** the internal state of the Pager object.
42467 */
42468 static int assert_pager_state(Pager *p){
42469   Pager *pPager = p;
42470 
42471   /* State must be valid. */
42472   assert( p->eState==PAGER_OPEN
42473        || p->eState==PAGER_READER
42474        || p->eState==PAGER_WRITER_LOCKED
42475        || p->eState==PAGER_WRITER_CACHEMOD
42476        || p->eState==PAGER_WRITER_DBMOD
42477        || p->eState==PAGER_WRITER_FINISHED
42478        || p->eState==PAGER_ERROR
42479   );
42480 
42481   /* Regardless of the current state, a temp-file connection always behaves
42482   ** as if it has an exclusive lock on the database file. It never updates
42483   ** the change-counter field, so the changeCountDone flag is always set.
42484   */
42485   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
42486   assert( p->tempFile==0 || pPager->changeCountDone );
42487 
42488   /* If the useJournal flag is clear, the journal-mode must be "OFF".
42489   ** And if the journal-mode is "OFF", the journal file must not be open.
42490   */
42491   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
42492   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
42493 
42494   /* Check that MEMDB implies noSync. And an in-memory journal. Since
42495   ** this means an in-memory pager performs no IO at all, it cannot encounter
42496   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
42497   ** a journal file. (although the in-memory journal implementation may
42498   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
42499   ** is therefore not possible for an in-memory pager to enter the ERROR
42500   ** state.
42501   */
42502   if( MEMDB ){
42503     assert( p->noSync );
42504     assert( p->journalMode==PAGER_JOURNALMODE_OFF
42505          || p->journalMode==PAGER_JOURNALMODE_MEMORY
42506     );
42507     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
42508     assert( pagerUseWal(p)==0 );
42509   }
42510 
42511   /* If changeCountDone is set, a RESERVED lock or greater must be held
42512   ** on the file.
42513   */
42514   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
42515   assert( p->eLock!=PENDING_LOCK );
42516 
42517   switch( p->eState ){
42518     case PAGER_OPEN:
42519       assert( !MEMDB );
42520       assert( pPager->errCode==SQLITE_OK );
42521       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
42522       break;
42523 
42524     case PAGER_READER:
42525       assert( pPager->errCode==SQLITE_OK );
42526       assert( p->eLock!=UNKNOWN_LOCK );
42527       assert( p->eLock>=SHARED_LOCK );
42528       break;
42529 
42530     case PAGER_WRITER_LOCKED:
42531       assert( p->eLock!=UNKNOWN_LOCK );
42532       assert( pPager->errCode==SQLITE_OK );
42533       if( !pagerUseWal(pPager) ){
42534         assert( p->eLock>=RESERVED_LOCK );
42535       }
42536       assert( pPager->dbSize==pPager->dbOrigSize );
42537       assert( pPager->dbOrigSize==pPager->dbFileSize );
42538       assert( pPager->dbOrigSize==pPager->dbHintSize );
42539       assert( pPager->setMaster==0 );
42540       break;
42541 
42542     case PAGER_WRITER_CACHEMOD:
42543       assert( p->eLock!=UNKNOWN_LOCK );
42544       assert( pPager->errCode==SQLITE_OK );
42545       if( !pagerUseWal(pPager) ){
42546         /* It is possible that if journal_mode=wal here that neither the
42547         ** journal file nor the WAL file are open. This happens during
42548         ** a rollback transaction that switches from journal_mode=off
42549         ** to journal_mode=wal.
42550         */
42551         assert( p->eLock>=RESERVED_LOCK );
42552         assert( isOpen(p->jfd)
42553              || p->journalMode==PAGER_JOURNALMODE_OFF
42554              || p->journalMode==PAGER_JOURNALMODE_WAL
42555         );
42556       }
42557       assert( pPager->dbOrigSize==pPager->dbFileSize );
42558       assert( pPager->dbOrigSize==pPager->dbHintSize );
42559       break;
42560 
42561     case PAGER_WRITER_DBMOD:
42562       assert( p->eLock==EXCLUSIVE_LOCK );
42563       assert( pPager->errCode==SQLITE_OK );
42564       assert( !pagerUseWal(pPager) );
42565       assert( p->eLock>=EXCLUSIVE_LOCK );
42566       assert( isOpen(p->jfd)
42567            || p->journalMode==PAGER_JOURNALMODE_OFF
42568            || p->journalMode==PAGER_JOURNALMODE_WAL
42569       );
42570       assert( pPager->dbOrigSize<=pPager->dbHintSize );
42571       break;
42572 
42573     case PAGER_WRITER_FINISHED:
42574       assert( p->eLock==EXCLUSIVE_LOCK );
42575       assert( pPager->errCode==SQLITE_OK );
42576       assert( !pagerUseWal(pPager) );
42577       assert( isOpen(p->jfd)
42578            || p->journalMode==PAGER_JOURNALMODE_OFF
42579            || p->journalMode==PAGER_JOURNALMODE_WAL
42580       );
42581       break;
42582 
42583     case PAGER_ERROR:
42584       /* There must be at least one outstanding reference to the pager if
42585       ** in ERROR state. Otherwise the pager should have already dropped
42586       ** back to OPEN state.
42587       */
42588       assert( pPager->errCode!=SQLITE_OK );
42589       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
42590       break;
42591   }
42592 
42593   return 1;
42594 }
42595 #endif /* ifndef NDEBUG */
42596 
42597 #ifdef SQLITE_DEBUG
42598 /*
42599 ** Return a pointer to a human readable string in a static buffer
42600 ** containing the state of the Pager object passed as an argument. This
42601 ** is intended to be used within debuggers. For example, as an alternative
42602 ** to "print *pPager" in gdb:
42603 **
42604 ** (gdb) printf "%s", print_pager_state(pPager)
42605 */
42606 static char *print_pager_state(Pager *p){
42607   static char zRet[1024];
42608 
42609   sqlite3_snprintf(1024, zRet,
42610       "Filename:      %s\n"
42611       "State:         %s errCode=%d\n"
42612       "Lock:          %s\n"
42613       "Locking mode:  locking_mode=%s\n"
42614       "Journal mode:  journal_mode=%s\n"
42615       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
42616       "Journal:       journalOff=%lld journalHdr=%lld\n"
42617       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
42618       , p->zFilename
42619       , p->eState==PAGER_OPEN            ? "OPEN" :
42620         p->eState==PAGER_READER          ? "READER" :
42621         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
42622         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
42623         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
42624         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
42625         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
42626       , (int)p->errCode
42627       , p->eLock==NO_LOCK         ? "NO_LOCK" :
42628         p->eLock==RESERVED_LOCK   ? "RESERVED" :
42629         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
42630         p->eLock==SHARED_LOCK     ? "SHARED" :
42631         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
42632       , p->exclusiveMode ? "exclusive" : "normal"
42633       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
42634         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
42635         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
42636         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
42637         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
42638         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
42639       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
42640       , p->journalOff, p->journalHdr
42641       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
42642   );
42643 
42644   return zRet;
42645 }
42646 #endif
42647 
42648 /*
42649 ** Return true if it is necessary to write page *pPg into the sub-journal.
42650 ** A page needs to be written into the sub-journal if there exists one
42651 ** or more open savepoints for which:
42652 **
42653 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
42654 **   * The bit corresponding to the page-number is not set in
42655 **     PagerSavepoint.pInSavepoint.
42656 */
42657 static int subjRequiresPage(PgHdr *pPg){
42658   Pager *pPager = pPg->pPager;
42659   PagerSavepoint *p;
42660   Pgno pgno = pPg->pgno;
42661   int i;
42662   for(i=0; i<pPager->nSavepoint; i++){
42663     p = &pPager->aSavepoint[i];
42664     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
42665       return 1;
42666     }
42667   }
42668   return 0;
42669 }
42670 
42671 /*
42672 ** Return true if the page is already in the journal file.
42673 */
42674 static int pageInJournal(Pager *pPager, PgHdr *pPg){
42675   return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
42676 }
42677 
42678 /*
42679 ** Read a 32-bit integer from the given file descriptor.  Store the integer
42680 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
42681 ** error code is something goes wrong.
42682 **
42683 ** All values are stored on disk as big-endian.
42684 */
42685 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
42686   unsigned char ac[4];
42687   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
42688   if( rc==SQLITE_OK ){
42689     *pRes = sqlite3Get4byte(ac);
42690   }
42691   return rc;
42692 }
42693 
42694 /*
42695 ** Write a 32-bit integer into a string buffer in big-endian byte order.
42696 */
42697 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
42698 
42699 
42700 /*
42701 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
42702 ** on success or an error code is something goes wrong.
42703 */
42704 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
42705   char ac[4];
42706   put32bits(ac, val);
42707   return sqlite3OsWrite(fd, ac, 4, offset);
42708 }
42709 
42710 /*
42711 ** Unlock the database file to level eLock, which must be either NO_LOCK
42712 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
42713 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
42714 **
42715 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
42716 ** called, do not modify it. See the comment above the #define of
42717 ** UNKNOWN_LOCK for an explanation of this.
42718 */
42719 static int pagerUnlockDb(Pager *pPager, int eLock){
42720   int rc = SQLITE_OK;
42721 
42722   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
42723   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
42724   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
42725   if( isOpen(pPager->fd) ){
42726     assert( pPager->eLock>=eLock );
42727     rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
42728     if( pPager->eLock!=UNKNOWN_LOCK ){
42729       pPager->eLock = (u8)eLock;
42730     }
42731     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
42732   }
42733   return rc;
42734 }
42735 
42736 /*
42737 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
42738 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
42739 ** Pager.eLock variable to the new locking state.
42740 **
42741 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
42742 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
42743 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
42744 ** of this.
42745 */
42746 static int pagerLockDb(Pager *pPager, int eLock){
42747   int rc = SQLITE_OK;
42748 
42749   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
42750   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
42751     rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
42752     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
42753       pPager->eLock = (u8)eLock;
42754       IOTRACE(("LOCK %p %d\n", pPager, eLock))
42755     }
42756   }
42757   return rc;
42758 }
42759 
42760 /*
42761 ** This function determines whether or not the atomic-write optimization
42762 ** can be used with this pager. The optimization can be used if:
42763 **
42764 **  (a) the value returned by OsDeviceCharacteristics() indicates that
42765 **      a database page may be written atomically, and
42766 **  (b) the value returned by OsSectorSize() is less than or equal
42767 **      to the page size.
42768 **
42769 ** The optimization is also always enabled for temporary files. It is
42770 ** an error to call this function if pPager is opened on an in-memory
42771 ** database.
42772 **
42773 ** If the optimization cannot be used, 0 is returned. If it can be used,
42774 ** then the value returned is the size of the journal file when it
42775 ** contains rollback data for exactly one page.
42776 */
42777 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42778 static int jrnlBufferSize(Pager *pPager){
42779   assert( !MEMDB );
42780   if( !pPager->tempFile ){
42781     int dc;                           /* Device characteristics */
42782     int nSector;                      /* Sector size */
42783     int szPage;                       /* Page size */
42784 
42785     assert( isOpen(pPager->fd) );
42786     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
42787     nSector = pPager->sectorSize;
42788     szPage = pPager->pageSize;
42789 
42790     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
42791     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
42792     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
42793       return 0;
42794     }
42795   }
42796 
42797   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
42798 }
42799 #endif
42800 
42801 /*
42802 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
42803 ** on the cache using a hash function.  This is used for testing
42804 ** and debugging only.
42805 */
42806 #ifdef SQLITE_CHECK_PAGES
42807 /*
42808 ** Return a 32-bit hash of the page data for pPage.
42809 */
42810 static u32 pager_datahash(int nByte, unsigned char *pData){
42811   u32 hash = 0;
42812   int i;
42813   for(i=0; i<nByte; i++){
42814     hash = (hash*1039) + pData[i];
42815   }
42816   return hash;
42817 }
42818 static u32 pager_pagehash(PgHdr *pPage){
42819   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
42820 }
42821 static void pager_set_pagehash(PgHdr *pPage){
42822   pPage->pageHash = pager_pagehash(pPage);
42823 }
42824 
42825 /*
42826 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
42827 ** is defined, and NDEBUG is not defined, an assert() statement checks
42828 ** that the page is either dirty or still matches the calculated page-hash.
42829 */
42830 #define CHECK_PAGE(x) checkPage(x)
42831 static void checkPage(PgHdr *pPg){
42832   Pager *pPager = pPg->pPager;
42833   assert( pPager->eState!=PAGER_ERROR );
42834   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
42835 }
42836 
42837 #else
42838 #define pager_datahash(X,Y)  0
42839 #define pager_pagehash(X)  0
42840 #define pager_set_pagehash(X)
42841 #define CHECK_PAGE(x)
42842 #endif  /* SQLITE_CHECK_PAGES */
42843 
42844 /*
42845 ** When this is called the journal file for pager pPager must be open.
42846 ** This function attempts to read a master journal file name from the
42847 ** end of the file and, if successful, copies it into memory supplied
42848 ** by the caller. See comments above writeMasterJournal() for the format
42849 ** used to store a master journal file name at the end of a journal file.
42850 **
42851 ** zMaster must point to a buffer of at least nMaster bytes allocated by
42852 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
42853 ** enough space to write the master journal name). If the master journal
42854 ** name in the journal is longer than nMaster bytes (including a
42855 ** nul-terminator), then this is handled as if no master journal name
42856 ** were present in the journal.
42857 **
42858 ** If a master journal file name is present at the end of the journal
42859 ** file, then it is copied into the buffer pointed to by zMaster. A
42860 ** nul-terminator byte is appended to the buffer following the master
42861 ** journal file name.
42862 **
42863 ** If it is determined that no master journal file name is present
42864 ** zMaster[0] is set to 0 and SQLITE_OK returned.
42865 **
42866 ** If an error occurs while reading from the journal file, an SQLite
42867 ** error code is returned.
42868 */
42869 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
42870   int rc;                    /* Return code */
42871   u32 len;                   /* Length in bytes of master journal name */
42872   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
42873   u32 cksum;                 /* MJ checksum value read from journal */
42874   u32 u;                     /* Unsigned loop counter */
42875   unsigned char aMagic[8];   /* A buffer to hold the magic header */
42876   zMaster[0] = '\0';
42877 
42878   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
42879    || szJ<16
42880    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
42881    || len>=nMaster
42882    || len==0
42883    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
42884    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
42885    || memcmp(aMagic, aJournalMagic, 8)
42886    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
42887   ){
42888     return rc;
42889   }
42890 
42891   /* See if the checksum matches the master journal name */
42892   for(u=0; u<len; u++){
42893     cksum -= zMaster[u];
42894   }
42895   if( cksum ){
42896     /* If the checksum doesn't add up, then one or more of the disk sectors
42897     ** containing the master journal filename is corrupted. This means
42898     ** definitely roll back, so just return SQLITE_OK and report a (nul)
42899     ** master-journal filename.
42900     */
42901     len = 0;
42902   }
42903   zMaster[len] = '\0';
42904 
42905   return SQLITE_OK;
42906 }
42907 
42908 /*
42909 ** Return the offset of the sector boundary at or immediately
42910 ** following the value in pPager->journalOff, assuming a sector
42911 ** size of pPager->sectorSize bytes.
42912 **
42913 ** i.e for a sector size of 512:
42914 **
42915 **   Pager.journalOff          Return value
42916 **   ---------------------------------------
42917 **   0                         0
42918 **   512                       512
42919 **   100                       512
42920 **   2000                      2048
42921 **
42922 */
42923 static i64 journalHdrOffset(Pager *pPager){
42924   i64 offset = 0;
42925   i64 c = pPager->journalOff;
42926   if( c ){
42927     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
42928   }
42929   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
42930   assert( offset>=c );
42931   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
42932   return offset;
42933 }
42934 
42935 /*
42936 ** The journal file must be open when this function is called.
42937 **
42938 ** This function is a no-op if the journal file has not been written to
42939 ** within the current transaction (i.e. if Pager.journalOff==0).
42940 **
42941 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
42942 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
42943 ** zero the 28-byte header at the start of the journal file. In either case,
42944 ** if the pager is not in no-sync mode, sync the journal file immediately
42945 ** after writing or truncating it.
42946 **
42947 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
42948 ** following the truncation or zeroing described above the size of the
42949 ** journal file in bytes is larger than this value, then truncate the
42950 ** journal file to Pager.journalSizeLimit bytes. The journal file does
42951 ** not need to be synced following this operation.
42952 **
42953 ** If an IO error occurs, abandon processing and return the IO error code.
42954 ** Otherwise, return SQLITE_OK.
42955 */
42956 static int zeroJournalHdr(Pager *pPager, int doTruncate){
42957   int rc = SQLITE_OK;                               /* Return code */
42958   assert( isOpen(pPager->jfd) );
42959   if( pPager->journalOff ){
42960     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
42961 
42962     IOTRACE(("JZEROHDR %p\n", pPager))
42963     if( doTruncate || iLimit==0 ){
42964       rc = sqlite3OsTruncate(pPager->jfd, 0);
42965     }else{
42966       static const char zeroHdr[28] = {0};
42967       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
42968     }
42969     if( rc==SQLITE_OK && !pPager->noSync ){
42970       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
42971     }
42972 
42973     /* At this point the transaction is committed but the write lock
42974     ** is still held on the file. If there is a size limit configured for
42975     ** the persistent journal and the journal file currently consumes more
42976     ** space than that limit allows for, truncate it now. There is no need
42977     ** to sync the file following this operation.
42978     */
42979     if( rc==SQLITE_OK && iLimit>0 ){
42980       i64 sz;
42981       rc = sqlite3OsFileSize(pPager->jfd, &sz);
42982       if( rc==SQLITE_OK && sz>iLimit ){
42983         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
42984       }
42985     }
42986   }
42987   return rc;
42988 }
42989 
42990 /*
42991 ** The journal file must be open when this routine is called. A journal
42992 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
42993 ** current location.
42994 **
42995 ** The format for the journal header is as follows:
42996 ** - 8 bytes: Magic identifying journal format.
42997 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
42998 ** - 4 bytes: Random number used for page hash.
42999 ** - 4 bytes: Initial database page count.
43000 ** - 4 bytes: Sector size used by the process that wrote this journal.
43001 ** - 4 bytes: Database page size.
43002 **
43003 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
43004 */
43005 static int writeJournalHdr(Pager *pPager){
43006   int rc = SQLITE_OK;                 /* Return code */
43007   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
43008   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
43009   u32 nWrite;                         /* Bytes of header sector written */
43010   int ii;                             /* Loop counter */
43011 
43012   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
43013 
43014   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
43015     nHeader = JOURNAL_HDR_SZ(pPager);
43016   }
43017 
43018   /* If there are active savepoints and any of them were created
43019   ** since the most recent journal header was written, update the
43020   ** PagerSavepoint.iHdrOffset fields now.
43021   */
43022   for(ii=0; ii<pPager->nSavepoint; ii++){
43023     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
43024       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
43025     }
43026   }
43027 
43028   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
43029 
43030   /*
43031   ** Write the nRec Field - the number of page records that follow this
43032   ** journal header. Normally, zero is written to this value at this time.
43033   ** After the records are added to the journal (and the journal synced,
43034   ** if in full-sync mode), the zero is overwritten with the true number
43035   ** of records (see syncJournal()).
43036   **
43037   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
43038   ** reading the journal this value tells SQLite to assume that the
43039   ** rest of the journal file contains valid page records. This assumption
43040   ** is dangerous, as if a failure occurred whilst writing to the journal
43041   ** file it may contain some garbage data. There are two scenarios
43042   ** where this risk can be ignored:
43043   **
43044   **   * When the pager is in no-sync mode. Corruption can follow a
43045   **     power failure in this case anyway.
43046   **
43047   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
43048   **     that garbage data is never appended to the journal file.
43049   */
43050   assert( isOpen(pPager->fd) || pPager->noSync );
43051   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
43052    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
43053   ){
43054     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
43055     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
43056   }else{
43057     memset(zHeader, 0, sizeof(aJournalMagic)+4);
43058   }
43059 
43060   /* The random check-hash initializer */
43061   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
43062   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
43063   /* The initial database size */
43064   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
43065   /* The assumed sector size for this process */
43066   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
43067 
43068   /* The page size */
43069   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
43070 
43071   /* Initializing the tail of the buffer is not necessary.  Everything
43072   ** works find if the following memset() is omitted.  But initializing
43073   ** the memory prevents valgrind from complaining, so we are willing to
43074   ** take the performance hit.
43075   */
43076   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
43077          nHeader-(sizeof(aJournalMagic)+20));
43078 
43079   /* In theory, it is only necessary to write the 28 bytes that the
43080   ** journal header consumes to the journal file here. Then increment the
43081   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
43082   ** record is written to the following sector (leaving a gap in the file
43083   ** that will be implicitly filled in by the OS).
43084   **
43085   ** However it has been discovered that on some systems this pattern can
43086   ** be significantly slower than contiguously writing data to the file,
43087   ** even if that means explicitly writing data to the block of
43088   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
43089   ** is done.
43090   **
43091   ** The loop is required here in case the sector-size is larger than the
43092   ** database page size. Since the zHeader buffer is only Pager.pageSize
43093   ** bytes in size, more than one call to sqlite3OsWrite() may be required
43094   ** to populate the entire journal header sector.
43095   */
43096   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
43097     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
43098     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
43099     assert( pPager->journalHdr <= pPager->journalOff );
43100     pPager->journalOff += nHeader;
43101   }
43102 
43103   return rc;
43104 }
43105 
43106 /*
43107 ** The journal file must be open when this is called. A journal header file
43108 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
43109 ** file. The current location in the journal file is given by
43110 ** pPager->journalOff. See comments above function writeJournalHdr() for
43111 ** a description of the journal header format.
43112 **
43113 ** If the header is read successfully, *pNRec is set to the number of
43114 ** page records following this header and *pDbSize is set to the size of the
43115 ** database before the transaction began, in pages. Also, pPager->cksumInit
43116 ** is set to the value read from the journal header. SQLITE_OK is returned
43117 ** in this case.
43118 **
43119 ** If the journal header file appears to be corrupted, SQLITE_DONE is
43120 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
43121 ** cannot be read from the journal file an error code is returned.
43122 */
43123 static int readJournalHdr(
43124   Pager *pPager,               /* Pager object */
43125   int isHot,
43126   i64 journalSize,             /* Size of the open journal file in bytes */
43127   u32 *pNRec,                  /* OUT: Value read from the nRec field */
43128   u32 *pDbSize                 /* OUT: Value of original database size field */
43129 ){
43130   int rc;                      /* Return code */
43131   unsigned char aMagic[8];     /* A buffer to hold the magic header */
43132   i64 iHdrOff;                 /* Offset of journal header being read */
43133 
43134   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
43135 
43136   /* Advance Pager.journalOff to the start of the next sector. If the
43137   ** journal file is too small for there to be a header stored at this
43138   ** point, return SQLITE_DONE.
43139   */
43140   pPager->journalOff = journalHdrOffset(pPager);
43141   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
43142     return SQLITE_DONE;
43143   }
43144   iHdrOff = pPager->journalOff;
43145 
43146   /* Read in the first 8 bytes of the journal header. If they do not match
43147   ** the  magic string found at the start of each journal header, return
43148   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
43149   ** proceed.
43150   */
43151   if( isHot || iHdrOff!=pPager->journalHdr ){
43152     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
43153     if( rc ){
43154       return rc;
43155     }
43156     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
43157       return SQLITE_DONE;
43158     }
43159   }
43160 
43161   /* Read the first three 32-bit fields of the journal header: The nRec
43162   ** field, the checksum-initializer and the database size at the start
43163   ** of the transaction. Return an error code if anything goes wrong.
43164   */
43165   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
43166    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
43167    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
43168   ){
43169     return rc;
43170   }
43171 
43172   if( pPager->journalOff==0 ){
43173     u32 iPageSize;               /* Page-size field of journal header */
43174     u32 iSectorSize;             /* Sector-size field of journal header */
43175 
43176     /* Read the page-size and sector-size journal header fields. */
43177     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
43178      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
43179     ){
43180       return rc;
43181     }
43182 
43183     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
43184     ** journal header to zero. In this case, assume that the Pager.pageSize
43185     ** variable is already set to the correct page size.
43186     */
43187     if( iPageSize==0 ){
43188       iPageSize = pPager->pageSize;
43189     }
43190 
43191     /* Check that the values read from the page-size and sector-size fields
43192     ** are within range. To be 'in range', both values need to be a power
43193     ** of two greater than or equal to 512 or 32, and not greater than their
43194     ** respective compile time maximum limits.
43195     */
43196     if( iPageSize<512                  || iSectorSize<32
43197      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
43198      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
43199     ){
43200       /* If the either the page-size or sector-size in the journal-header is
43201       ** invalid, then the process that wrote the journal-header must have
43202       ** crashed before the header was synced. In this case stop reading
43203       ** the journal file here.
43204       */
43205       return SQLITE_DONE;
43206     }
43207 
43208     /* Update the page-size to match the value read from the journal.
43209     ** Use a testcase() macro to make sure that malloc failure within
43210     ** PagerSetPagesize() is tested.
43211     */
43212     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
43213     testcase( rc!=SQLITE_OK );
43214 
43215     /* Update the assumed sector-size to match the value used by
43216     ** the process that created this journal. If this journal was
43217     ** created by a process other than this one, then this routine
43218     ** is being called from within pager_playback(). The local value
43219     ** of Pager.sectorSize is restored at the end of that routine.
43220     */
43221     pPager->sectorSize = iSectorSize;
43222   }
43223 
43224   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
43225   return rc;
43226 }
43227 
43228 
43229 /*
43230 ** Write the supplied master journal name into the journal file for pager
43231 ** pPager at the current location. The master journal name must be the last
43232 ** thing written to a journal file. If the pager is in full-sync mode, the
43233 ** journal file descriptor is advanced to the next sector boundary before
43234 ** anything is written. The format is:
43235 **
43236 **   + 4 bytes: PAGER_MJ_PGNO.
43237 **   + N bytes: Master journal filename in utf-8.
43238 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
43239 **   + 4 bytes: Master journal name checksum.
43240 **   + 8 bytes: aJournalMagic[].
43241 **
43242 ** The master journal page checksum is the sum of the bytes in the master
43243 ** journal name, where each byte is interpreted as a signed 8-bit integer.
43244 **
43245 ** If zMaster is a NULL pointer (occurs for a single database transaction),
43246 ** this call is a no-op.
43247 */
43248 static int writeMasterJournal(Pager *pPager, const char *zMaster){
43249   int rc;                          /* Return code */
43250   int nMaster;                     /* Length of string zMaster */
43251   i64 iHdrOff;                     /* Offset of header in journal file */
43252   i64 jrnlSize;                    /* Size of journal file on disk */
43253   u32 cksum = 0;                   /* Checksum of string zMaster */
43254 
43255   assert( pPager->setMaster==0 );
43256   assert( !pagerUseWal(pPager) );
43257 
43258   if( !zMaster
43259    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
43260    || !isOpen(pPager->jfd)
43261   ){
43262     return SQLITE_OK;
43263   }
43264   pPager->setMaster = 1;
43265   assert( pPager->journalHdr <= pPager->journalOff );
43266 
43267   /* Calculate the length in bytes and the checksum of zMaster */
43268   for(nMaster=0; zMaster[nMaster]; nMaster++){
43269     cksum += zMaster[nMaster];
43270   }
43271 
43272   /* If in full-sync mode, advance to the next disk sector before writing
43273   ** the master journal name. This is in case the previous page written to
43274   ** the journal has already been synced.
43275   */
43276   if( pPager->fullSync ){
43277     pPager->journalOff = journalHdrOffset(pPager);
43278   }
43279   iHdrOff = pPager->journalOff;
43280 
43281   /* Write the master journal data to the end of the journal file. If
43282   ** an error occurs, return the error code to the caller.
43283   */
43284   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
43285    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
43286    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
43287    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
43288    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
43289   ){
43290     return rc;
43291   }
43292   pPager->journalOff += (nMaster+20);
43293 
43294   /* If the pager is in peristent-journal mode, then the physical
43295   ** journal-file may extend past the end of the master-journal name
43296   ** and 8 bytes of magic data just written to the file. This is
43297   ** dangerous because the code to rollback a hot-journal file
43298   ** will not be able to find the master-journal name to determine
43299   ** whether or not the journal is hot.
43300   **
43301   ** Easiest thing to do in this scenario is to truncate the journal
43302   ** file to the required size.
43303   */
43304   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
43305    && jrnlSize>pPager->journalOff
43306   ){
43307     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
43308   }
43309   return rc;
43310 }
43311 
43312 /*
43313 ** Discard the entire contents of the in-memory page-cache.
43314 */
43315 static void pager_reset(Pager *pPager){
43316   pPager->iDataVersion++;
43317   sqlite3BackupRestart(pPager->pBackup);
43318   sqlite3PcacheClear(pPager->pPCache);
43319 }
43320 
43321 /*
43322 ** Return the pPager->iDataVersion value
43323 */
43324 SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
43325   assert( pPager->eState>PAGER_OPEN );
43326   return pPager->iDataVersion;
43327 }
43328 
43329 /*
43330 ** Free all structures in the Pager.aSavepoint[] array and set both
43331 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
43332 ** if it is open and the pager is not in exclusive mode.
43333 */
43334 static void releaseAllSavepoints(Pager *pPager){
43335   int ii;               /* Iterator for looping through Pager.aSavepoint */
43336   for(ii=0; ii<pPager->nSavepoint; ii++){
43337     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
43338   }
43339   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
43340     sqlite3OsClose(pPager->sjfd);
43341   }
43342   sqlite3_free(pPager->aSavepoint);
43343   pPager->aSavepoint = 0;
43344   pPager->nSavepoint = 0;
43345   pPager->nSubRec = 0;
43346 }
43347 
43348 /*
43349 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
43350 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
43351 ** or SQLITE_NOMEM if a malloc failure occurs.
43352 */
43353 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
43354   int ii;                   /* Loop counter */
43355   int rc = SQLITE_OK;       /* Result code */
43356 
43357   for(ii=0; ii<pPager->nSavepoint; ii++){
43358     PagerSavepoint *p = &pPager->aSavepoint[ii];
43359     if( pgno<=p->nOrig ){
43360       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
43361       testcase( rc==SQLITE_NOMEM );
43362       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
43363     }
43364   }
43365   return rc;
43366 }
43367 
43368 /*
43369 ** This function is a no-op if the pager is in exclusive mode and not
43370 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
43371 ** state.
43372 **
43373 ** If the pager is not in exclusive-access mode, the database file is
43374 ** completely unlocked. If the file is unlocked and the file-system does
43375 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
43376 ** closed (if it is open).
43377 **
43378 ** If the pager is in ERROR state when this function is called, the
43379 ** contents of the pager cache are discarded before switching back to
43380 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
43381 ** or not, any journal file left in the file-system will be treated
43382 ** as a hot-journal and rolled back the next time a read-transaction
43383 ** is opened (by this or by any other connection).
43384 */
43385 static void pager_unlock(Pager *pPager){
43386 
43387   assert( pPager->eState==PAGER_READER
43388        || pPager->eState==PAGER_OPEN
43389        || pPager->eState==PAGER_ERROR
43390   );
43391 
43392   sqlite3BitvecDestroy(pPager->pInJournal);
43393   pPager->pInJournal = 0;
43394   releaseAllSavepoints(pPager);
43395 
43396   if( pagerUseWal(pPager) ){
43397     assert( !isOpen(pPager->jfd) );
43398     sqlite3WalEndReadTransaction(pPager->pWal);
43399     pPager->eState = PAGER_OPEN;
43400   }else if( !pPager->exclusiveMode ){
43401     int rc;                       /* Error code returned by pagerUnlockDb() */
43402     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
43403 
43404     /* If the operating system support deletion of open files, then
43405     ** close the journal file when dropping the database lock.  Otherwise
43406     ** another connection with journal_mode=delete might delete the file
43407     ** out from under us.
43408     */
43409     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
43410     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
43411     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
43412     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
43413     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
43414     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
43415     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
43416      || 1!=(pPager->journalMode & 5)
43417     ){
43418       sqlite3OsClose(pPager->jfd);
43419     }
43420 
43421     /* If the pager is in the ERROR state and the call to unlock the database
43422     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
43423     ** above the #define for UNKNOWN_LOCK for an explanation of why this
43424     ** is necessary.
43425     */
43426     rc = pagerUnlockDb(pPager, NO_LOCK);
43427     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
43428       pPager->eLock = UNKNOWN_LOCK;
43429     }
43430 
43431     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
43432     ** without clearing the error code. This is intentional - the error
43433     ** code is cleared and the cache reset in the block below.
43434     */
43435     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
43436     pPager->changeCountDone = 0;
43437     pPager->eState = PAGER_OPEN;
43438   }
43439 
43440   /* If Pager.errCode is set, the contents of the pager cache cannot be
43441   ** trusted. Now that there are no outstanding references to the pager,
43442   ** it can safely move back to PAGER_OPEN state. This happens in both
43443   ** normal and exclusive-locking mode.
43444   */
43445   if( pPager->errCode ){
43446     assert( !MEMDB );
43447     pager_reset(pPager);
43448     pPager->changeCountDone = pPager->tempFile;
43449     pPager->eState = PAGER_OPEN;
43450     pPager->errCode = SQLITE_OK;
43451     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
43452   }
43453 
43454   pPager->journalOff = 0;
43455   pPager->journalHdr = 0;
43456   pPager->setMaster = 0;
43457 }
43458 
43459 /*
43460 ** This function is called whenever an IOERR or FULL error that requires
43461 ** the pager to transition into the ERROR state may ahve occurred.
43462 ** The first argument is a pointer to the pager structure, the second
43463 ** the error-code about to be returned by a pager API function. The
43464 ** value returned is a copy of the second argument to this function.
43465 **
43466 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
43467 ** IOERR sub-codes, the pager enters the ERROR state and the error code
43468 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
43469 ** all major API calls on the Pager will immediately return Pager.errCode.
43470 **
43471 ** The ERROR state indicates that the contents of the pager-cache
43472 ** cannot be trusted. This state can be cleared by completely discarding
43473 ** the contents of the pager-cache. If a transaction was active when
43474 ** the persistent error occurred, then the rollback journal may need
43475 ** to be replayed to restore the contents of the database file (as if
43476 ** it were a hot-journal).
43477 */
43478 static int pager_error(Pager *pPager, int rc){
43479   int rc2 = rc & 0xff;
43480   assert( rc==SQLITE_OK || !MEMDB );
43481   assert(
43482        pPager->errCode==SQLITE_FULL ||
43483        pPager->errCode==SQLITE_OK ||
43484        (pPager->errCode & 0xff)==SQLITE_IOERR
43485   );
43486   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
43487     pPager->errCode = rc;
43488     pPager->eState = PAGER_ERROR;
43489   }
43490   return rc;
43491 }
43492 
43493 static int pager_truncate(Pager *pPager, Pgno nPage);
43494 
43495 /*
43496 ** This routine ends a transaction. A transaction is usually ended by
43497 ** either a COMMIT or a ROLLBACK operation. This routine may be called
43498 ** after rollback of a hot-journal, or if an error occurs while opening
43499 ** the journal file or writing the very first journal-header of a
43500 ** database transaction.
43501 **
43502 ** This routine is never called in PAGER_ERROR state. If it is called
43503 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
43504 ** exclusive than a RESERVED lock, it is a no-op.
43505 **
43506 ** Otherwise, any active savepoints are released.
43507 **
43508 ** If the journal file is open, then it is "finalized". Once a journal
43509 ** file has been finalized it is not possible to use it to roll back a
43510 ** transaction. Nor will it be considered to be a hot-journal by this
43511 ** or any other database connection. Exactly how a journal is finalized
43512 ** depends on whether or not the pager is running in exclusive mode and
43513 ** the current journal-mode (Pager.journalMode value), as follows:
43514 **
43515 **   journalMode==MEMORY
43516 **     Journal file descriptor is simply closed. This destroys an
43517 **     in-memory journal.
43518 **
43519 **   journalMode==TRUNCATE
43520 **     Journal file is truncated to zero bytes in size.
43521 **
43522 **   journalMode==PERSIST
43523 **     The first 28 bytes of the journal file are zeroed. This invalidates
43524 **     the first journal header in the file, and hence the entire journal
43525 **     file. An invalid journal file cannot be rolled back.
43526 **
43527 **   journalMode==DELETE
43528 **     The journal file is closed and deleted using sqlite3OsDelete().
43529 **
43530 **     If the pager is running in exclusive mode, this method of finalizing
43531 **     the journal file is never used. Instead, if the journalMode is
43532 **     DELETE and the pager is in exclusive mode, the method described under
43533 **     journalMode==PERSIST is used instead.
43534 **
43535 ** After the journal is finalized, the pager moves to PAGER_READER state.
43536 ** If running in non-exclusive rollback mode, the lock on the file is
43537 ** downgraded to a SHARED_LOCK.
43538 **
43539 ** SQLITE_OK is returned if no error occurs. If an error occurs during
43540 ** any of the IO operations to finalize the journal file or unlock the
43541 ** database then the IO error code is returned to the user. If the
43542 ** operation to finalize the journal file fails, then the code still
43543 ** tries to unlock the database file if not in exclusive mode. If the
43544 ** unlock operation fails as well, then the first error code related
43545 ** to the first error encountered (the journal finalization one) is
43546 ** returned.
43547 */
43548 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
43549   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
43550   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
43551 
43552   /* Do nothing if the pager does not have an open write transaction
43553   ** or at least a RESERVED lock. This function may be called when there
43554   ** is no write-transaction active but a RESERVED or greater lock is
43555   ** held under two circumstances:
43556   **
43557   **   1. After a successful hot-journal rollback, it is called with
43558   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
43559   **
43560   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
43561   **      lock switches back to locking_mode=normal and then executes a
43562   **      read-transaction, this function is called with eState==PAGER_READER
43563   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
43564   */
43565   assert( assert_pager_state(pPager) );
43566   assert( pPager->eState!=PAGER_ERROR );
43567   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
43568     return SQLITE_OK;
43569   }
43570 
43571   releaseAllSavepoints(pPager);
43572   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
43573   if( isOpen(pPager->jfd) ){
43574     assert( !pagerUseWal(pPager) );
43575 
43576     /* Finalize the journal file. */
43577     if( sqlite3IsMemJournal(pPager->jfd) ){
43578       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
43579       sqlite3OsClose(pPager->jfd);
43580     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
43581       if( pPager->journalOff==0 ){
43582         rc = SQLITE_OK;
43583       }else{
43584         rc = sqlite3OsTruncate(pPager->jfd, 0);
43585         if( rc==SQLITE_OK && pPager->fullSync ){
43586           /* Make sure the new file size is written into the inode right away.
43587           ** Otherwise the journal might resurrect following a power loss and
43588           ** cause the last transaction to roll back.  See
43589           ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
43590           */
43591           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
43592         }
43593       }
43594       pPager->journalOff = 0;
43595     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
43596       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
43597     ){
43598       rc = zeroJournalHdr(pPager, hasMaster);
43599       pPager->journalOff = 0;
43600     }else{
43601       /* This branch may be executed with Pager.journalMode==MEMORY if
43602       ** a hot-journal was just rolled back. In this case the journal
43603       ** file should be closed and deleted. If this connection writes to
43604       ** the database file, it will do so using an in-memory journal.
43605       */
43606       int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
43607       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
43608            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
43609            || pPager->journalMode==PAGER_JOURNALMODE_WAL
43610       );
43611       sqlite3OsClose(pPager->jfd);
43612       if( bDelete ){
43613         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43614       }
43615     }
43616   }
43617 
43618 #ifdef SQLITE_CHECK_PAGES
43619   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
43620   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
43621     PgHdr *p = sqlite3PagerLookup(pPager, 1);
43622     if( p ){
43623       p->pageHash = 0;
43624       sqlite3PagerUnrefNotNull(p);
43625     }
43626   }
43627 #endif
43628 
43629   sqlite3BitvecDestroy(pPager->pInJournal);
43630   pPager->pInJournal = 0;
43631   pPager->nRec = 0;
43632   sqlite3PcacheCleanAll(pPager->pPCache);
43633   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
43634 
43635   if( pagerUseWal(pPager) ){
43636     /* Drop the WAL write-lock, if any. Also, if the connection was in
43637     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
43638     ** lock held on the database file.
43639     */
43640     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
43641     assert( rc2==SQLITE_OK );
43642   }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
43643     /* This branch is taken when committing a transaction in rollback-journal
43644     ** mode if the database file on disk is larger than the database image.
43645     ** At this point the journal has been finalized and the transaction
43646     ** successfully committed, but the EXCLUSIVE lock is still held on the
43647     ** file. So it is safe to truncate the database file to its minimum
43648     ** required size.  */
43649     assert( pPager->eLock==EXCLUSIVE_LOCK );
43650     rc = pager_truncate(pPager, pPager->dbSize);
43651   }
43652 
43653   if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
43654     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
43655     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
43656   }
43657 
43658   if( !pPager->exclusiveMode
43659    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
43660   ){
43661     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
43662     pPager->changeCountDone = 0;
43663   }
43664   pPager->eState = PAGER_READER;
43665   pPager->setMaster = 0;
43666 
43667   return (rc==SQLITE_OK?rc2:rc);
43668 }
43669 
43670 /*
43671 ** Execute a rollback if a transaction is active and unlock the
43672 ** database file.
43673 **
43674 ** If the pager has already entered the ERROR state, do not attempt
43675 ** the rollback at this time. Instead, pager_unlock() is called. The
43676 ** call to pager_unlock() will discard all in-memory pages, unlock
43677 ** the database file and move the pager back to OPEN state. If this
43678 ** means that there is a hot-journal left in the file-system, the next
43679 ** connection to obtain a shared lock on the pager (which may be this one)
43680 ** will roll it back.
43681 **
43682 ** If the pager has not already entered the ERROR state, but an IO or
43683 ** malloc error occurs during a rollback, then this will itself cause
43684 ** the pager to enter the ERROR state. Which will be cleared by the
43685 ** call to pager_unlock(), as described above.
43686 */
43687 static void pagerUnlockAndRollback(Pager *pPager){
43688   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
43689     assert( assert_pager_state(pPager) );
43690     if( pPager->eState>=PAGER_WRITER_LOCKED ){
43691       sqlite3BeginBenignMalloc();
43692       sqlite3PagerRollback(pPager);
43693       sqlite3EndBenignMalloc();
43694     }else if( !pPager->exclusiveMode ){
43695       assert( pPager->eState==PAGER_READER );
43696       pager_end_transaction(pPager, 0, 0);
43697     }
43698   }
43699   pager_unlock(pPager);
43700 }
43701 
43702 /*
43703 ** Parameter aData must point to a buffer of pPager->pageSize bytes
43704 ** of data. Compute and return a checksum based ont the contents of the
43705 ** page of data and the current value of pPager->cksumInit.
43706 **
43707 ** This is not a real checksum. It is really just the sum of the
43708 ** random initial value (pPager->cksumInit) and every 200th byte
43709 ** of the page data, starting with byte offset (pPager->pageSize%200).
43710 ** Each byte is interpreted as an 8-bit unsigned integer.
43711 **
43712 ** Changing the formula used to compute this checksum results in an
43713 ** incompatible journal file format.
43714 **
43715 ** If journal corruption occurs due to a power failure, the most likely
43716 ** scenario is that one end or the other of the record will be changed.
43717 ** It is much less likely that the two ends of the journal record will be
43718 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
43719 ** though fast and simple, catches the mostly likely kind of corruption.
43720 */
43721 static u32 pager_cksum(Pager *pPager, const u8 *aData){
43722   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
43723   int i = pPager->pageSize-200;          /* Loop counter */
43724   while( i>0 ){
43725     cksum += aData[i];
43726     i -= 200;
43727   }
43728   return cksum;
43729 }
43730 
43731 /*
43732 ** Report the current page size and number of reserved bytes back
43733 ** to the codec.
43734 */
43735 #ifdef SQLITE_HAS_CODEC
43736 static void pagerReportSize(Pager *pPager){
43737   if( pPager->xCodecSizeChng ){
43738     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
43739                            (int)pPager->nReserve);
43740   }
43741 }
43742 #else
43743 # define pagerReportSize(X)     /* No-op if we do not support a codec */
43744 #endif
43745 
43746 /*
43747 ** Read a single page from either the journal file (if isMainJrnl==1) or
43748 ** from the sub-journal (if isMainJrnl==0) and playback that page.
43749 ** The page begins at offset *pOffset into the file. The *pOffset
43750 ** value is increased to the start of the next page in the journal.
43751 **
43752 ** The main rollback journal uses checksums - the statement journal does
43753 ** not.
43754 **
43755 ** If the page number of the page record read from the (sub-)journal file
43756 ** is greater than the current value of Pager.dbSize, then playback is
43757 ** skipped and SQLITE_OK is returned.
43758 **
43759 ** If pDone is not NULL, then it is a record of pages that have already
43760 ** been played back.  If the page at *pOffset has already been played back
43761 ** (if the corresponding pDone bit is set) then skip the playback.
43762 ** Make sure the pDone bit corresponding to the *pOffset page is set
43763 ** prior to returning.
43764 **
43765 ** If the page record is successfully read from the (sub-)journal file
43766 ** and played back, then SQLITE_OK is returned. If an IO error occurs
43767 ** while reading the record from the (sub-)journal file or while writing
43768 ** to the database file, then the IO error code is returned. If data
43769 ** is successfully read from the (sub-)journal file but appears to be
43770 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
43771 ** two circumstances:
43772 **
43773 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
43774 **   * If the record is being rolled back from the main journal file
43775 **     and the checksum field does not match the record content.
43776 **
43777 ** Neither of these two scenarios are possible during a savepoint rollback.
43778 **
43779 ** If this is a savepoint rollback, then memory may have to be dynamically
43780 ** allocated by this function. If this is the case and an allocation fails,
43781 ** SQLITE_NOMEM is returned.
43782 */
43783 static int pager_playback_one_page(
43784   Pager *pPager,                /* The pager being played back */
43785   i64 *pOffset,                 /* Offset of record to playback */
43786   Bitvec *pDone,                /* Bitvec of pages already played back */
43787   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
43788   int isSavepnt                 /* True for a savepoint rollback */
43789 ){
43790   int rc;
43791   PgHdr *pPg;                   /* An existing page in the cache */
43792   Pgno pgno;                    /* The page number of a page in journal */
43793   u32 cksum;                    /* Checksum used for sanity checking */
43794   char *aData;                  /* Temporary storage for the page */
43795   sqlite3_file *jfd;            /* The file descriptor for the journal file */
43796   int isSynced;                 /* True if journal page is synced */
43797 
43798   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
43799   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
43800   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
43801   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
43802 
43803   aData = pPager->pTmpSpace;
43804   assert( aData );         /* Temp storage must have already been allocated */
43805   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
43806 
43807   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
43808   ** or savepoint rollback done at the request of the caller) or this is
43809   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
43810   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
43811   ** only reads from the main journal, not the sub-journal.
43812   */
43813   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
43814        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
43815   );
43816   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
43817 
43818   /* Read the page number and page data from the journal or sub-journal
43819   ** file. Return an error code to the caller if an IO error occurs.
43820   */
43821   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
43822   rc = read32bits(jfd, *pOffset, &pgno);
43823   if( rc!=SQLITE_OK ) return rc;
43824   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
43825   if( rc!=SQLITE_OK ) return rc;
43826   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
43827 
43828   /* Sanity checking on the page.  This is more important that I originally
43829   ** thought.  If a power failure occurs while the journal is being written,
43830   ** it could cause invalid data to be written into the journal.  We need to
43831   ** detect this invalid data (with high probability) and ignore it.
43832   */
43833   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
43834     assert( !isSavepnt );
43835     return SQLITE_DONE;
43836   }
43837   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
43838     return SQLITE_OK;
43839   }
43840   if( isMainJrnl ){
43841     rc = read32bits(jfd, (*pOffset)-4, &cksum);
43842     if( rc ) return rc;
43843     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
43844       return SQLITE_DONE;
43845     }
43846   }
43847 
43848   /* If this page has already been played by before during the current
43849   ** rollback, then don't bother to play it back again.
43850   */
43851   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
43852     return rc;
43853   }
43854 
43855   /* When playing back page 1, restore the nReserve setting
43856   */
43857   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
43858     pPager->nReserve = ((u8*)aData)[20];
43859     pagerReportSize(pPager);
43860   }
43861 
43862   /* If the pager is in CACHEMOD state, then there must be a copy of this
43863   ** page in the pager cache. In this case just update the pager cache,
43864   ** not the database file. The page is left marked dirty in this case.
43865   **
43866   ** An exception to the above rule: If the database is in no-sync mode
43867   ** and a page is moved during an incremental vacuum then the page may
43868   ** not be in the pager cache. Later: if a malloc() or IO error occurs
43869   ** during a Movepage() call, then the page may not be in the cache
43870   ** either. So the condition described in the above paragraph is not
43871   ** assert()able.
43872   **
43873   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
43874   ** pager cache if it exists and the main file. The page is then marked
43875   ** not dirty. Since this code is only executed in PAGER_OPEN state for
43876   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
43877   ** if the pager is in OPEN state.
43878   **
43879   ** Ticket #1171:  The statement journal might contain page content that is
43880   ** different from the page content at the start of the transaction.
43881   ** This occurs when a page is changed prior to the start of a statement
43882   ** then changed again within the statement.  When rolling back such a
43883   ** statement we must not write to the original database unless we know
43884   ** for certain that original page contents are synced into the main rollback
43885   ** journal.  Otherwise, a power loss might leave modified data in the
43886   ** database file without an entry in the rollback journal that can
43887   ** restore the database to its original form.  Two conditions must be
43888   ** met before writing to the database files. (1) the database must be
43889   ** locked.  (2) we know that the original page content is fully synced
43890   ** in the main journal either because the page is not in cache or else
43891   ** the page is marked as needSync==0.
43892   **
43893   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
43894   ** is possible to fail a statement on a database that does not yet exist.
43895   ** Do not attempt to write if database file has never been opened.
43896   */
43897   if( pagerUseWal(pPager) ){
43898     pPg = 0;
43899   }else{
43900     pPg = sqlite3PagerLookup(pPager, pgno);
43901   }
43902   assert( pPg || !MEMDB );
43903   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
43904   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
43905            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
43906            (isMainJrnl?"main-journal":"sub-journal")
43907   ));
43908   if( isMainJrnl ){
43909     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
43910   }else{
43911     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
43912   }
43913   if( isOpen(pPager->fd)
43914    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
43915    && isSynced
43916   ){
43917     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
43918     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
43919     assert( !pagerUseWal(pPager) );
43920     rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
43921     if( pgno>pPager->dbFileSize ){
43922       pPager->dbFileSize = pgno;
43923     }
43924     if( pPager->pBackup ){
43925       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
43926       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
43927       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
43928     }
43929   }else if( !isMainJrnl && pPg==0 ){
43930     /* If this is a rollback of a savepoint and data was not written to
43931     ** the database and the page is not in-memory, there is a potential
43932     ** problem. When the page is next fetched by the b-tree layer, it
43933     ** will be read from the database file, which may or may not be
43934     ** current.
43935     **
43936     ** There are a couple of different ways this can happen. All are quite
43937     ** obscure. When running in synchronous mode, this can only happen
43938     ** if the page is on the free-list at the start of the transaction, then
43939     ** populated, then moved using sqlite3PagerMovepage().
43940     **
43941     ** The solution is to add an in-memory page to the cache containing
43942     ** the data just read from the sub-journal. Mark the page as dirty
43943     ** and if the pager requires a journal-sync, then mark the page as
43944     ** requiring a journal-sync before it is written.
43945     */
43946     assert( isSavepnt );
43947     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
43948     pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
43949     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
43950     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
43951     pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
43952     if( rc!=SQLITE_OK ) return rc;
43953     pPg->flags &= ~PGHDR_NEED_READ;
43954     sqlite3PcacheMakeDirty(pPg);
43955   }
43956   if( pPg ){
43957     /* No page should ever be explicitly rolled back that is in use, except
43958     ** for page 1 which is held in use in order to keep the lock on the
43959     ** database active. However such a page may be rolled back as a result
43960     ** of an internal error resulting in an automatic call to
43961     ** sqlite3PagerRollback().
43962     */
43963     void *pData;
43964     pData = pPg->pData;
43965     memcpy(pData, (u8*)aData, pPager->pageSize);
43966     pPager->xReiniter(pPg);
43967     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
43968       /* If the contents of this page were just restored from the main
43969       ** journal file, then its content must be as they were when the
43970       ** transaction was first opened. In this case we can mark the page
43971       ** as clean, since there will be no need to write it out to the
43972       ** database.
43973       **
43974       ** There is one exception to this rule. If the page is being rolled
43975       ** back as part of a savepoint (or statement) rollback from an
43976       ** unsynced portion of the main journal file, then it is not safe
43977       ** to mark the page as clean. This is because marking the page as
43978       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
43979       ** already in the journal file (recorded in Pager.pInJournal) and
43980       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
43981       ** again within this transaction, it will be marked as dirty but
43982       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
43983       ** be written out into the database file before its journal file
43984       ** segment is synced. If a crash occurs during or following this,
43985       ** database corruption may ensue.
43986       */
43987       assert( !pagerUseWal(pPager) );
43988       sqlite3PcacheMakeClean(pPg);
43989     }
43990     pager_set_pagehash(pPg);
43991 
43992     /* If this was page 1, then restore the value of Pager.dbFileVers.
43993     ** Do this before any decoding. */
43994     if( pgno==1 ){
43995       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
43996     }
43997 
43998     /* Decode the page just read from disk */
43999     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
44000     sqlite3PcacheRelease(pPg);
44001   }
44002   return rc;
44003 }
44004 
44005 /*
44006 ** Parameter zMaster is the name of a master journal file. A single journal
44007 ** file that referred to the master journal file has just been rolled back.
44008 ** This routine checks if it is possible to delete the master journal file,
44009 ** and does so if it is.
44010 **
44011 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
44012 ** available for use within this function.
44013 **
44014 ** When a master journal file is created, it is populated with the names
44015 ** of all of its child journals, one after another, formatted as utf-8
44016 ** encoded text. The end of each child journal file is marked with a
44017 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
44018 ** file for a transaction involving two databases might be:
44019 **
44020 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
44021 **
44022 ** A master journal file may only be deleted once all of its child
44023 ** journals have been rolled back.
44024 **
44025 ** This function reads the contents of the master-journal file into
44026 ** memory and loops through each of the child journal names. For
44027 ** each child journal, it checks if:
44028 **
44029 **   * if the child journal exists, and if so
44030 **   * if the child journal contains a reference to master journal
44031 **     file zMaster
44032 **
44033 ** If a child journal can be found that matches both of the criteria
44034 ** above, this function returns without doing anything. Otherwise, if
44035 ** no such child journal can be found, file zMaster is deleted from
44036 ** the file-system using sqlite3OsDelete().
44037 **
44038 ** If an IO error within this function, an error code is returned. This
44039 ** function allocates memory by calling sqlite3Malloc(). If an allocation
44040 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
44041 ** occur, SQLITE_OK is returned.
44042 **
44043 ** TODO: This function allocates a single block of memory to load
44044 ** the entire contents of the master journal file. This could be
44045 ** a couple of kilobytes or so - potentially larger than the page
44046 ** size.
44047 */
44048 static int pager_delmaster(Pager *pPager, const char *zMaster){
44049   sqlite3_vfs *pVfs = pPager->pVfs;
44050   int rc;                   /* Return code */
44051   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
44052   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
44053   char *zMasterJournal = 0; /* Contents of master journal file */
44054   i64 nMasterJournal;       /* Size of master journal file */
44055   char *zJournal;           /* Pointer to one journal within MJ file */
44056   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
44057   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
44058 
44059   /* Allocate space for both the pJournal and pMaster file descriptors.
44060   ** If successful, open the master journal file for reading.
44061   */
44062   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
44063   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
44064   if( !pMaster ){
44065     rc = SQLITE_NOMEM;
44066   }else{
44067     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
44068     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
44069   }
44070   if( rc!=SQLITE_OK ) goto delmaster_out;
44071 
44072   /* Load the entire master journal file into space obtained from
44073   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
44074   ** sufficient space (in zMasterPtr) to hold the names of master
44075   ** journal files extracted from regular rollback-journals.
44076   */
44077   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
44078   if( rc!=SQLITE_OK ) goto delmaster_out;
44079   nMasterPtr = pVfs->mxPathname+1;
44080   zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
44081   if( !zMasterJournal ){
44082     rc = SQLITE_NOMEM;
44083     goto delmaster_out;
44084   }
44085   zMasterPtr = &zMasterJournal[nMasterJournal+1];
44086   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
44087   if( rc!=SQLITE_OK ) goto delmaster_out;
44088   zMasterJournal[nMasterJournal] = 0;
44089 
44090   zJournal = zMasterJournal;
44091   while( (zJournal-zMasterJournal)<nMasterJournal ){
44092     int exists;
44093     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
44094     if( rc!=SQLITE_OK ){
44095       goto delmaster_out;
44096     }
44097     if( exists ){
44098       /* One of the journals pointed to by the master journal exists.
44099       ** Open it and check if it points at the master journal. If
44100       ** so, return without deleting the master journal file.
44101       */
44102       int c;
44103       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
44104       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
44105       if( rc!=SQLITE_OK ){
44106         goto delmaster_out;
44107       }
44108 
44109       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
44110       sqlite3OsClose(pJournal);
44111       if( rc!=SQLITE_OK ){
44112         goto delmaster_out;
44113       }
44114 
44115       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
44116       if( c ){
44117         /* We have a match. Do not delete the master journal file. */
44118         goto delmaster_out;
44119       }
44120     }
44121     zJournal += (sqlite3Strlen30(zJournal)+1);
44122   }
44123 
44124   sqlite3OsClose(pMaster);
44125   rc = sqlite3OsDelete(pVfs, zMaster, 0);
44126 
44127 delmaster_out:
44128   sqlite3_free(zMasterJournal);
44129   if( pMaster ){
44130     sqlite3OsClose(pMaster);
44131     assert( !isOpen(pJournal) );
44132     sqlite3_free(pMaster);
44133   }
44134   return rc;
44135 }
44136 
44137 
44138 /*
44139 ** This function is used to change the actual size of the database
44140 ** file in the file-system. This only happens when committing a transaction,
44141 ** or rolling back a transaction (including rolling back a hot-journal).
44142 **
44143 ** If the main database file is not open, or the pager is not in either
44144 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
44145 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
44146 ** If the file on disk is currently larger than nPage pages, then use the VFS
44147 ** xTruncate() method to truncate it.
44148 **
44149 ** Or, it might be the case that the file on disk is smaller than
44150 ** nPage pages. Some operating system implementations can get confused if
44151 ** you try to truncate a file to some size that is larger than it
44152 ** currently is, so detect this case and write a single zero byte to
44153 ** the end of the new file instead.
44154 **
44155 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
44156 ** the database file, return the error code to the caller.
44157 */
44158 static int pager_truncate(Pager *pPager, Pgno nPage){
44159   int rc = SQLITE_OK;
44160   assert( pPager->eState!=PAGER_ERROR );
44161   assert( pPager->eState!=PAGER_READER );
44162 
44163   if( isOpen(pPager->fd)
44164    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
44165   ){
44166     i64 currentSize, newSize;
44167     int szPage = pPager->pageSize;
44168     assert( pPager->eLock==EXCLUSIVE_LOCK );
44169     /* TODO: Is it safe to use Pager.dbFileSize here? */
44170     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
44171     newSize = szPage*(i64)nPage;
44172     if( rc==SQLITE_OK && currentSize!=newSize ){
44173       if( currentSize>newSize ){
44174         rc = sqlite3OsTruncate(pPager->fd, newSize);
44175       }else if( (currentSize+szPage)<=newSize ){
44176         char *pTmp = pPager->pTmpSpace;
44177         memset(pTmp, 0, szPage);
44178         testcase( (newSize-szPage) == currentSize );
44179         testcase( (newSize-szPage) >  currentSize );
44180         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
44181       }
44182       if( rc==SQLITE_OK ){
44183         pPager->dbFileSize = nPage;
44184       }
44185     }
44186   }
44187   return rc;
44188 }
44189 
44190 /*
44191 ** Return a sanitized version of the sector-size of OS file pFile. The
44192 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
44193 */
44194 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
44195   int iRet = sqlite3OsSectorSize(pFile);
44196   if( iRet<32 ){
44197     iRet = 512;
44198   }else if( iRet>MAX_SECTOR_SIZE ){
44199     assert( MAX_SECTOR_SIZE>=512 );
44200     iRet = MAX_SECTOR_SIZE;
44201   }
44202   return iRet;
44203 }
44204 
44205 /*
44206 ** Set the value of the Pager.sectorSize variable for the given
44207 ** pager based on the value returned by the xSectorSize method
44208 ** of the open database file. The sector size will be used
44209 ** to determine the size and alignment of journal header and
44210 ** master journal pointers within created journal files.
44211 **
44212 ** For temporary files the effective sector size is always 512 bytes.
44213 **
44214 ** Otherwise, for non-temporary files, the effective sector size is
44215 ** the value returned by the xSectorSize() method rounded up to 32 if
44216 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
44217 ** is greater than MAX_SECTOR_SIZE.
44218 **
44219 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
44220 ** the effective sector size to its minimum value (512).  The purpose of
44221 ** pPager->sectorSize is to define the "blast radius" of bytes that
44222 ** might change if a crash occurs while writing to a single byte in
44223 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
44224 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
44225 ** size.  For backwards compatibility of the rollback journal file format,
44226 ** we cannot reduce the effective sector size below 512.
44227 */
44228 static void setSectorSize(Pager *pPager){
44229   assert( isOpen(pPager->fd) || pPager->tempFile );
44230 
44231   if( pPager->tempFile
44232    || (sqlite3OsDeviceCharacteristics(pPager->fd) &
44233               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
44234   ){
44235     /* Sector size doesn't matter for temporary files. Also, the file
44236     ** may not have been opened yet, in which case the OsSectorSize()
44237     ** call will segfault. */
44238     pPager->sectorSize = 512;
44239   }else{
44240     pPager->sectorSize = sqlite3SectorSize(pPager->fd);
44241   }
44242 }
44243 
44244 /*
44245 ** Playback the journal and thus restore the database file to
44246 ** the state it was in before we started making changes.
44247 **
44248 ** The journal file format is as follows:
44249 **
44250 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
44251 **  (2)  4 byte big-endian integer which is the number of valid page records
44252 **       in the journal.  If this value is 0xffffffff, then compute the
44253 **       number of page records from the journal size.
44254 **  (3)  4 byte big-endian integer which is the initial value for the
44255 **       sanity checksum.
44256 **  (4)  4 byte integer which is the number of pages to truncate the
44257 **       database to during a rollback.
44258 **  (5)  4 byte big-endian integer which is the sector size.  The header
44259 **       is this many bytes in size.
44260 **  (6)  4 byte big-endian integer which is the page size.
44261 **  (7)  zero padding out to the next sector size.
44262 **  (8)  Zero or more pages instances, each as follows:
44263 **        +  4 byte page number.
44264 **        +  pPager->pageSize bytes of data.
44265 **        +  4 byte checksum
44266 **
44267 ** When we speak of the journal header, we mean the first 7 items above.
44268 ** Each entry in the journal is an instance of the 8th item.
44269 **
44270 ** Call the value from the second bullet "nRec".  nRec is the number of
44271 ** valid page entries in the journal.  In most cases, you can compute the
44272 ** value of nRec from the size of the journal file.  But if a power
44273 ** failure occurred while the journal was being written, it could be the
44274 ** case that the size of the journal file had already been increased but
44275 ** the extra entries had not yet made it safely to disk.  In such a case,
44276 ** the value of nRec computed from the file size would be too large.  For
44277 ** that reason, we always use the nRec value in the header.
44278 **
44279 ** If the nRec value is 0xffffffff it means that nRec should be computed
44280 ** from the file size.  This value is used when the user selects the
44281 ** no-sync option for the journal.  A power failure could lead to corruption
44282 ** in this case.  But for things like temporary table (which will be
44283 ** deleted when the power is restored) we don't care.
44284 **
44285 ** If the file opened as the journal file is not a well-formed
44286 ** journal file then all pages up to the first corrupted page are rolled
44287 ** back (or no pages if the journal header is corrupted). The journal file
44288 ** is then deleted and SQLITE_OK returned, just as if no corruption had
44289 ** been encountered.
44290 **
44291 ** If an I/O or malloc() error occurs, the journal-file is not deleted
44292 ** and an error code is returned.
44293 **
44294 ** The isHot parameter indicates that we are trying to rollback a journal
44295 ** that might be a hot journal.  Or, it could be that the journal is
44296 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
44297 ** If the journal really is hot, reset the pager cache prior rolling
44298 ** back any content.  If the journal is merely persistent, no reset is
44299 ** needed.
44300 */
44301 static int pager_playback(Pager *pPager, int isHot){
44302   sqlite3_vfs *pVfs = pPager->pVfs;
44303   i64 szJ;                 /* Size of the journal file in bytes */
44304   u32 nRec;                /* Number of Records in the journal */
44305   u32 u;                   /* Unsigned loop counter */
44306   Pgno mxPg = 0;           /* Size of the original file in pages */
44307   int rc;                  /* Result code of a subroutine */
44308   int res = 1;             /* Value returned by sqlite3OsAccess() */
44309   char *zMaster = 0;       /* Name of master journal file if any */
44310   int needPagerReset;      /* True to reset page prior to first page rollback */
44311   int nPlayback = 0;       /* Total number of pages restored from journal */
44312 
44313   /* Figure out how many records are in the journal.  Abort early if
44314   ** the journal is empty.
44315   */
44316   assert( isOpen(pPager->jfd) );
44317   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
44318   if( rc!=SQLITE_OK ){
44319     goto end_playback;
44320   }
44321 
44322   /* Read the master journal name from the journal, if it is present.
44323   ** If a master journal file name is specified, but the file is not
44324   ** present on disk, then the journal is not hot and does not need to be
44325   ** played back.
44326   **
44327   ** TODO: Technically the following is an error because it assumes that
44328   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
44329   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
44330   **  mxPathname is 512, which is the same as the minimum allowable value
44331   ** for pageSize.
44332   */
44333   zMaster = pPager->pTmpSpace;
44334   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
44335   if( rc==SQLITE_OK && zMaster[0] ){
44336     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
44337   }
44338   zMaster = 0;
44339   if( rc!=SQLITE_OK || !res ){
44340     goto end_playback;
44341   }
44342   pPager->journalOff = 0;
44343   needPagerReset = isHot;
44344 
44345   /* This loop terminates either when a readJournalHdr() or
44346   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
44347   ** occurs.
44348   */
44349   while( 1 ){
44350     /* Read the next journal header from the journal file.  If there are
44351     ** not enough bytes left in the journal file for a complete header, or
44352     ** it is corrupted, then a process must have failed while writing it.
44353     ** This indicates nothing more needs to be rolled back.
44354     */
44355     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
44356     if( rc!=SQLITE_OK ){
44357       if( rc==SQLITE_DONE ){
44358         rc = SQLITE_OK;
44359       }
44360       goto end_playback;
44361     }
44362 
44363     /* If nRec is 0xffffffff, then this journal was created by a process
44364     ** working in no-sync mode. This means that the rest of the journal
44365     ** file consists of pages, there are no more journal headers. Compute
44366     ** the value of nRec based on this assumption.
44367     */
44368     if( nRec==0xffffffff ){
44369       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
44370       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
44371     }
44372 
44373     /* If nRec is 0 and this rollback is of a transaction created by this
44374     ** process and if this is the final header in the journal, then it means
44375     ** that this part of the journal was being filled but has not yet been
44376     ** synced to disk.  Compute the number of pages based on the remaining
44377     ** size of the file.
44378     **
44379     ** The third term of the test was added to fix ticket #2565.
44380     ** When rolling back a hot journal, nRec==0 always means that the next
44381     ** chunk of the journal contains zero pages to be rolled back.  But
44382     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
44383     ** the journal, it means that the journal might contain additional
44384     ** pages that need to be rolled back and that the number of pages
44385     ** should be computed based on the journal file size.
44386     */
44387     if( nRec==0 && !isHot &&
44388         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
44389       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
44390     }
44391 
44392     /* If this is the first header read from the journal, truncate the
44393     ** database file back to its original size.
44394     */
44395     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
44396       rc = pager_truncate(pPager, mxPg);
44397       if( rc!=SQLITE_OK ){
44398         goto end_playback;
44399       }
44400       pPager->dbSize = mxPg;
44401     }
44402 
44403     /* Copy original pages out of the journal and back into the
44404     ** database file and/or page cache.
44405     */
44406     for(u=0; u<nRec; u++){
44407       if( needPagerReset ){
44408         pager_reset(pPager);
44409         needPagerReset = 0;
44410       }
44411       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
44412       if( rc==SQLITE_OK ){
44413         nPlayback++;
44414       }else{
44415         if( rc==SQLITE_DONE ){
44416           pPager->journalOff = szJ;
44417           break;
44418         }else if( rc==SQLITE_IOERR_SHORT_READ ){
44419           /* If the journal has been truncated, simply stop reading and
44420           ** processing the journal. This might happen if the journal was
44421           ** not completely written and synced prior to a crash.  In that
44422           ** case, the database should have never been written in the
44423           ** first place so it is OK to simply abandon the rollback. */
44424           rc = SQLITE_OK;
44425           goto end_playback;
44426         }else{
44427           /* If we are unable to rollback, quit and return the error
44428           ** code.  This will cause the pager to enter the error state
44429           ** so that no further harm will be done.  Perhaps the next
44430           ** process to come along will be able to rollback the database.
44431           */
44432           goto end_playback;
44433         }
44434       }
44435     }
44436   }
44437   /*NOTREACHED*/
44438   assert( 0 );
44439 
44440 end_playback:
44441   /* Following a rollback, the database file should be back in its original
44442   ** state prior to the start of the transaction, so invoke the
44443   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
44444   ** assertion that the transaction counter was modified.
44445   */
44446 #ifdef SQLITE_DEBUG
44447   if( pPager->fd->pMethods ){
44448     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
44449   }
44450 #endif
44451 
44452   /* If this playback is happening automatically as a result of an IO or
44453   ** malloc error that occurred after the change-counter was updated but
44454   ** before the transaction was committed, then the change-counter
44455   ** modification may just have been reverted. If this happens in exclusive
44456   ** mode, then subsequent transactions performed by the connection will not
44457   ** update the change-counter at all. This may lead to cache inconsistency
44458   ** problems for other processes at some point in the future. So, just
44459   ** in case this has happened, clear the changeCountDone flag now.
44460   */
44461   pPager->changeCountDone = pPager->tempFile;
44462 
44463   if( rc==SQLITE_OK ){
44464     zMaster = pPager->pTmpSpace;
44465     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
44466     testcase( rc!=SQLITE_OK );
44467   }
44468   if( rc==SQLITE_OK
44469    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
44470   ){
44471     rc = sqlite3PagerSync(pPager, 0);
44472   }
44473   if( rc==SQLITE_OK ){
44474     rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
44475     testcase( rc!=SQLITE_OK );
44476   }
44477   if( rc==SQLITE_OK && zMaster[0] && res ){
44478     /* If there was a master journal and this routine will return success,
44479     ** see if it is possible to delete the master journal.
44480     */
44481     rc = pager_delmaster(pPager, zMaster);
44482     testcase( rc!=SQLITE_OK );
44483   }
44484   if( isHot && nPlayback ){
44485     sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
44486                 nPlayback, pPager->zJournal);
44487   }
44488 
44489   /* The Pager.sectorSize variable may have been updated while rolling
44490   ** back a journal created by a process with a different sector size
44491   ** value. Reset it to the correct value for this process.
44492   */
44493   setSectorSize(pPager);
44494   return rc;
44495 }
44496 
44497 
44498 /*
44499 ** Read the content for page pPg out of the database file and into
44500 ** pPg->pData. A shared lock or greater must be held on the database
44501 ** file before this function is called.
44502 **
44503 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
44504 ** the value read from the database file.
44505 **
44506 ** If an IO error occurs, then the IO error is returned to the caller.
44507 ** Otherwise, SQLITE_OK is returned.
44508 */
44509 static int readDbPage(PgHdr *pPg, u32 iFrame){
44510   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
44511   Pgno pgno = pPg->pgno;       /* Page number to read */
44512   int rc = SQLITE_OK;          /* Return code */
44513   int pgsz = pPager->pageSize; /* Number of bytes to read */
44514 
44515   assert( pPager->eState>=PAGER_READER && !MEMDB );
44516   assert( isOpen(pPager->fd) );
44517 
44518 #ifndef SQLITE_OMIT_WAL
44519   if( iFrame ){
44520     /* Try to pull the page from the write-ahead log. */
44521     rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
44522   }else
44523 #endif
44524   {
44525     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
44526     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
44527     if( rc==SQLITE_IOERR_SHORT_READ ){
44528       rc = SQLITE_OK;
44529     }
44530   }
44531 
44532   if( pgno==1 ){
44533     if( rc ){
44534       /* If the read is unsuccessful, set the dbFileVers[] to something
44535       ** that will never be a valid file version.  dbFileVers[] is a copy
44536       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
44537       ** zero or the size of the database in page. Bytes 32..35 and 35..39
44538       ** should be page numbers which are never 0xffffffff.  So filling
44539       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
44540       **
44541       ** For an encrypted database, the situation is more complex:  bytes
44542       ** 24..39 of the database are white noise.  But the probability of
44543       ** white noise equaling 16 bytes of 0xff is vanishingly small so
44544       ** we should still be ok.
44545       */
44546       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
44547     }else{
44548       u8 *dbFileVers = &((u8*)pPg->pData)[24];
44549       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
44550     }
44551   }
44552   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
44553 
44554   PAGER_INCR(sqlite3_pager_readdb_count);
44555   PAGER_INCR(pPager->nRead);
44556   IOTRACE(("PGIN %p %d\n", pPager, pgno));
44557   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
44558                PAGERID(pPager), pgno, pager_pagehash(pPg)));
44559 
44560   return rc;
44561 }
44562 
44563 /*
44564 ** Update the value of the change-counter at offsets 24 and 92 in
44565 ** the header and the sqlite version number at offset 96.
44566 **
44567 ** This is an unconditional update.  See also the pager_incr_changecounter()
44568 ** routine which only updates the change-counter if the update is actually
44569 ** needed, as determined by the pPager->changeCountDone state variable.
44570 */
44571 static void pager_write_changecounter(PgHdr *pPg){
44572   u32 change_counter;
44573 
44574   /* Increment the value just read and write it back to byte 24. */
44575   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
44576   put32bits(((char*)pPg->pData)+24, change_counter);
44577 
44578   /* Also store the SQLite version number in bytes 96..99 and in
44579   ** bytes 92..95 store the change counter for which the version number
44580   ** is valid. */
44581   put32bits(((char*)pPg->pData)+92, change_counter);
44582   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
44583 }
44584 
44585 #ifndef SQLITE_OMIT_WAL
44586 /*
44587 ** This function is invoked once for each page that has already been
44588 ** written into the log file when a WAL transaction is rolled back.
44589 ** Parameter iPg is the page number of said page. The pCtx argument
44590 ** is actually a pointer to the Pager structure.
44591 **
44592 ** If page iPg is present in the cache, and has no outstanding references,
44593 ** it is discarded. Otherwise, if there are one or more outstanding
44594 ** references, the page content is reloaded from the database. If the
44595 ** attempt to reload content from the database is required and fails,
44596 ** return an SQLite error code. Otherwise, SQLITE_OK.
44597 */
44598 static int pagerUndoCallback(void *pCtx, Pgno iPg){
44599   int rc = SQLITE_OK;
44600   Pager *pPager = (Pager *)pCtx;
44601   PgHdr *pPg;
44602 
44603   assert( pagerUseWal(pPager) );
44604   pPg = sqlite3PagerLookup(pPager, iPg);
44605   if( pPg ){
44606     if( sqlite3PcachePageRefcount(pPg)==1 ){
44607       sqlite3PcacheDrop(pPg);
44608     }else{
44609       u32 iFrame = 0;
44610       rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
44611       if( rc==SQLITE_OK ){
44612         rc = readDbPage(pPg, iFrame);
44613       }
44614       if( rc==SQLITE_OK ){
44615         pPager->xReiniter(pPg);
44616       }
44617       sqlite3PagerUnrefNotNull(pPg);
44618     }
44619   }
44620 
44621   /* Normally, if a transaction is rolled back, any backup processes are
44622   ** updated as data is copied out of the rollback journal and into the
44623   ** database. This is not generally possible with a WAL database, as
44624   ** rollback involves simply truncating the log file. Therefore, if one
44625   ** or more frames have already been written to the log (and therefore
44626   ** also copied into the backup databases) as part of this transaction,
44627   ** the backups must be restarted.
44628   */
44629   sqlite3BackupRestart(pPager->pBackup);
44630 
44631   return rc;
44632 }
44633 
44634 /*
44635 ** This function is called to rollback a transaction on a WAL database.
44636 */
44637 static int pagerRollbackWal(Pager *pPager){
44638   int rc;                         /* Return Code */
44639   PgHdr *pList;                   /* List of dirty pages to revert */
44640 
44641   /* For all pages in the cache that are currently dirty or have already
44642   ** been written (but not committed) to the log file, do one of the
44643   ** following:
44644   **
44645   **   + Discard the cached page (if refcount==0), or
44646   **   + Reload page content from the database (if refcount>0).
44647   */
44648   pPager->dbSize = pPager->dbOrigSize;
44649   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
44650   pList = sqlite3PcacheDirtyList(pPager->pPCache);
44651   while( pList && rc==SQLITE_OK ){
44652     PgHdr *pNext = pList->pDirty;
44653     rc = pagerUndoCallback((void *)pPager, pList->pgno);
44654     pList = pNext;
44655   }
44656 
44657   return rc;
44658 }
44659 
44660 /*
44661 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
44662 ** the contents of the list of pages headed by pList (connected by pDirty),
44663 ** this function notifies any active backup processes that the pages have
44664 ** changed.
44665 **
44666 ** The list of pages passed into this routine is always sorted by page number.
44667 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
44668 */
44669 static int pagerWalFrames(
44670   Pager *pPager,                  /* Pager object */
44671   PgHdr *pList,                   /* List of frames to log */
44672   Pgno nTruncate,                 /* Database size after this commit */
44673   int isCommit                    /* True if this is a commit */
44674 ){
44675   int rc;                         /* Return code */
44676   int nList;                      /* Number of pages in pList */
44677   PgHdr *p;                       /* For looping over pages */
44678 
44679   assert( pPager->pWal );
44680   assert( pList );
44681 #ifdef SQLITE_DEBUG
44682   /* Verify that the page list is in accending order */
44683   for(p=pList; p && p->pDirty; p=p->pDirty){
44684     assert( p->pgno < p->pDirty->pgno );
44685   }
44686 #endif
44687 
44688   assert( pList->pDirty==0 || isCommit );
44689   if( isCommit ){
44690     /* If a WAL transaction is being committed, there is no point in writing
44691     ** any pages with page numbers greater than nTruncate into the WAL file.
44692     ** They will never be read by any client. So remove them from the pDirty
44693     ** list here. */
44694     PgHdr **ppNext = &pList;
44695     nList = 0;
44696     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
44697       if( p->pgno<=nTruncate ){
44698         ppNext = &p->pDirty;
44699         nList++;
44700       }
44701     }
44702     assert( pList );
44703   }else{
44704     nList = 1;
44705   }
44706   pPager->aStat[PAGER_STAT_WRITE] += nList;
44707 
44708   if( pList->pgno==1 ) pager_write_changecounter(pList);
44709   rc = sqlite3WalFrames(pPager->pWal,
44710       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
44711   );
44712   if( rc==SQLITE_OK && pPager->pBackup ){
44713     for(p=pList; p; p=p->pDirty){
44714       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
44715     }
44716   }
44717 
44718 #ifdef SQLITE_CHECK_PAGES
44719   pList = sqlite3PcacheDirtyList(pPager->pPCache);
44720   for(p=pList; p; p=p->pDirty){
44721     pager_set_pagehash(p);
44722   }
44723 #endif
44724 
44725   return rc;
44726 }
44727 
44728 /*
44729 ** Begin a read transaction on the WAL.
44730 **
44731 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
44732 ** makes a snapshot of the database at the current point in time and preserves
44733 ** that snapshot for use by the reader in spite of concurrently changes by
44734 ** other writers or checkpointers.
44735 */
44736 static int pagerBeginReadTransaction(Pager *pPager){
44737   int rc;                         /* Return code */
44738   int changed = 0;                /* True if cache must be reset */
44739 
44740   assert( pagerUseWal(pPager) );
44741   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
44742 
44743   /* sqlite3WalEndReadTransaction() was not called for the previous
44744   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
44745   ** are in locking_mode=NORMAL and EndRead() was previously called,
44746   ** the duplicate call is harmless.
44747   */
44748   sqlite3WalEndReadTransaction(pPager->pWal);
44749 
44750   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
44751   if( rc!=SQLITE_OK || changed ){
44752     pager_reset(pPager);
44753     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
44754   }
44755 
44756   return rc;
44757 }
44758 #endif
44759 
44760 /*
44761 ** This function is called as part of the transition from PAGER_OPEN
44762 ** to PAGER_READER state to determine the size of the database file
44763 ** in pages (assuming the page size currently stored in Pager.pageSize).
44764 **
44765 ** If no error occurs, SQLITE_OK is returned and the size of the database
44766 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
44767 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
44768 */
44769 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
44770   Pgno nPage;                     /* Value to return via *pnPage */
44771 
44772   /* Query the WAL sub-system for the database size. The WalDbsize()
44773   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
44774   ** if the database size is not available. The database size is not
44775   ** available from the WAL sub-system if the log file is empty or
44776   ** contains no valid committed transactions.
44777   */
44778   assert( pPager->eState==PAGER_OPEN );
44779   assert( pPager->eLock>=SHARED_LOCK );
44780   nPage = sqlite3WalDbsize(pPager->pWal);
44781 
44782   /* If the database size was not available from the WAL sub-system,
44783   ** determine it based on the size of the database file. If the size
44784   ** of the database file is not an integer multiple of the page-size,
44785   ** round down to the nearest page. Except, any file larger than 0
44786   ** bytes in size is considered to contain at least one page.
44787   */
44788   if( nPage==0 ){
44789     i64 n = 0;                    /* Size of db file in bytes */
44790     assert( isOpen(pPager->fd) || pPager->tempFile );
44791     if( isOpen(pPager->fd) ){
44792       int rc = sqlite3OsFileSize(pPager->fd, &n);
44793       if( rc!=SQLITE_OK ){
44794         return rc;
44795       }
44796     }
44797     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
44798   }
44799 
44800   /* If the current number of pages in the file is greater than the
44801   ** configured maximum pager number, increase the allowed limit so
44802   ** that the file can be read.
44803   */
44804   if( nPage>pPager->mxPgno ){
44805     pPager->mxPgno = (Pgno)nPage;
44806   }
44807 
44808   *pnPage = nPage;
44809   return SQLITE_OK;
44810 }
44811 
44812 #ifndef SQLITE_OMIT_WAL
44813 /*
44814 ** Check if the *-wal file that corresponds to the database opened by pPager
44815 ** exists if the database is not empy, or verify that the *-wal file does
44816 ** not exist (by deleting it) if the database file is empty.
44817 **
44818 ** If the database is not empty and the *-wal file exists, open the pager
44819 ** in WAL mode.  If the database is empty or if no *-wal file exists and
44820 ** if no error occurs, make sure Pager.journalMode is not set to
44821 ** PAGER_JOURNALMODE_WAL.
44822 **
44823 ** Return SQLITE_OK or an error code.
44824 **
44825 ** The caller must hold a SHARED lock on the database file to call this
44826 ** function. Because an EXCLUSIVE lock on the db file is required to delete
44827 ** a WAL on a none-empty database, this ensures there is no race condition
44828 ** between the xAccess() below and an xDelete() being executed by some
44829 ** other connection.
44830 */
44831 static int pagerOpenWalIfPresent(Pager *pPager){
44832   int rc = SQLITE_OK;
44833   assert( pPager->eState==PAGER_OPEN );
44834   assert( pPager->eLock>=SHARED_LOCK );
44835 
44836   if( !pPager->tempFile ){
44837     int isWal;                    /* True if WAL file exists */
44838     Pgno nPage;                   /* Size of the database file */
44839 
44840     rc = pagerPagecount(pPager, &nPage);
44841     if( rc ) return rc;
44842     if( nPage==0 ){
44843       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
44844       if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
44845       isWal = 0;
44846     }else{
44847       rc = sqlite3OsAccess(
44848           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
44849       );
44850     }
44851     if( rc==SQLITE_OK ){
44852       if( isWal ){
44853         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
44854         rc = sqlite3PagerOpenWal(pPager, 0);
44855       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
44856         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
44857       }
44858     }
44859   }
44860   return rc;
44861 }
44862 #endif
44863 
44864 /*
44865 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
44866 ** the entire master journal file. The case pSavepoint==NULL occurs when
44867 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
44868 ** savepoint.
44869 **
44870 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
44871 ** being rolled back), then the rollback consists of up to three stages,
44872 ** performed in the order specified:
44873 **
44874 **   * Pages are played back from the main journal starting at byte
44875 **     offset PagerSavepoint.iOffset and continuing to
44876 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
44877 **     file if PagerSavepoint.iHdrOffset is zero.
44878 **
44879 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
44880 **     back starting from the journal header immediately following
44881 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
44882 **
44883 **   * Pages are then played back from the sub-journal file, starting
44884 **     with the PagerSavepoint.iSubRec and continuing to the end of
44885 **     the journal file.
44886 **
44887 ** Throughout the rollback process, each time a page is rolled back, the
44888 ** corresponding bit is set in a bitvec structure (variable pDone in the
44889 ** implementation below). This is used to ensure that a page is only
44890 ** rolled back the first time it is encountered in either journal.
44891 **
44892 ** If pSavepoint is NULL, then pages are only played back from the main
44893 ** journal file. There is no need for a bitvec in this case.
44894 **
44895 ** In either case, before playback commences the Pager.dbSize variable
44896 ** is reset to the value that it held at the start of the savepoint
44897 ** (or transaction). No page with a page-number greater than this value
44898 ** is played back. If one is encountered it is simply skipped.
44899 */
44900 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
44901   i64 szJ;                 /* Effective size of the main journal */
44902   i64 iHdrOff;             /* End of first segment of main-journal records */
44903   int rc = SQLITE_OK;      /* Return code */
44904   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
44905 
44906   assert( pPager->eState!=PAGER_ERROR );
44907   assert( pPager->eState>=PAGER_WRITER_LOCKED );
44908 
44909   /* Allocate a bitvec to use to store the set of pages rolled back */
44910   if( pSavepoint ){
44911     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
44912     if( !pDone ){
44913       return SQLITE_NOMEM;
44914     }
44915   }
44916 
44917   /* Set the database size back to the value it was before the savepoint
44918   ** being reverted was opened.
44919   */
44920   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
44921   pPager->changeCountDone = pPager->tempFile;
44922 
44923   if( !pSavepoint && pagerUseWal(pPager) ){
44924     return pagerRollbackWal(pPager);
44925   }
44926 
44927   /* Use pPager->journalOff as the effective size of the main rollback
44928   ** journal.  The actual file might be larger than this in
44929   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
44930   ** past pPager->journalOff is off-limits to us.
44931   */
44932   szJ = pPager->journalOff;
44933   assert( pagerUseWal(pPager)==0 || szJ==0 );
44934 
44935   /* Begin by rolling back records from the main journal starting at
44936   ** PagerSavepoint.iOffset and continuing to the next journal header.
44937   ** There might be records in the main journal that have a page number
44938   ** greater than the current database size (pPager->dbSize) but those
44939   ** will be skipped automatically.  Pages are added to pDone as they
44940   ** are played back.
44941   */
44942   if( pSavepoint && !pagerUseWal(pPager) ){
44943     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
44944     pPager->journalOff = pSavepoint->iOffset;
44945     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
44946       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
44947     }
44948     assert( rc!=SQLITE_DONE );
44949   }else{
44950     pPager->journalOff = 0;
44951   }
44952 
44953   /* Continue rolling back records out of the main journal starting at
44954   ** the first journal header seen and continuing until the effective end
44955   ** of the main journal file.  Continue to skip out-of-range pages and
44956   ** continue adding pages rolled back to pDone.
44957   */
44958   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
44959     u32 ii;            /* Loop counter */
44960     u32 nJRec = 0;     /* Number of Journal Records */
44961     u32 dummy;
44962     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
44963     assert( rc!=SQLITE_DONE );
44964 
44965     /*
44966     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
44967     ** test is related to ticket #2565.  See the discussion in the
44968     ** pager_playback() function for additional information.
44969     */
44970     if( nJRec==0
44971      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
44972     ){
44973       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
44974     }
44975     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
44976       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
44977     }
44978     assert( rc!=SQLITE_DONE );
44979   }
44980   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
44981 
44982   /* Finally,  rollback pages from the sub-journal.  Page that were
44983   ** previously rolled back out of the main journal (and are hence in pDone)
44984   ** will be skipped.  Out-of-range pages are also skipped.
44985   */
44986   if( pSavepoint ){
44987     u32 ii;            /* Loop counter */
44988     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
44989 
44990     if( pagerUseWal(pPager) ){
44991       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
44992     }
44993     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
44994       assert( offset==(i64)ii*(4+pPager->pageSize) );
44995       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
44996     }
44997     assert( rc!=SQLITE_DONE );
44998   }
44999 
45000   sqlite3BitvecDestroy(pDone);
45001   if( rc==SQLITE_OK ){
45002     pPager->journalOff = szJ;
45003   }
45004 
45005   return rc;
45006 }
45007 
45008 /*
45009 ** Change the maximum number of in-memory pages that are allowed.
45010 */
45011 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
45012   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
45013 }
45014 
45015 /*
45016 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
45017 */
45018 static void pagerFixMaplimit(Pager *pPager){
45019 #if SQLITE_MAX_MMAP_SIZE>0
45020   sqlite3_file *fd = pPager->fd;
45021   if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
45022     sqlite3_int64 sz;
45023     sz = pPager->szMmap;
45024     pPager->bUseFetch = (sz>0);
45025     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
45026   }
45027 #endif
45028 }
45029 
45030 /*
45031 ** Change the maximum size of any memory mapping made of the database file.
45032 */
45033 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
45034   pPager->szMmap = szMmap;
45035   pagerFixMaplimit(pPager);
45036 }
45037 
45038 /*
45039 ** Free as much memory as possible from the pager.
45040 */
45041 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
45042   sqlite3PcacheShrink(pPager->pPCache);
45043 }
45044 
45045 /*
45046 ** Adjust settings of the pager to those specified in the pgFlags parameter.
45047 **
45048 ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
45049 ** of the database to damage due to OS crashes or power failures by
45050 ** changing the number of syncs()s when writing the journals.
45051 ** There are three levels:
45052 **
45053 **    OFF       sqlite3OsSync() is never called.  This is the default
45054 **              for temporary and transient files.
45055 **
45056 **    NORMAL    The journal is synced once before writes begin on the
45057 **              database.  This is normally adequate protection, but
45058 **              it is theoretically possible, though very unlikely,
45059 **              that an inopertune power failure could leave the journal
45060 **              in a state which would cause damage to the database
45061 **              when it is rolled back.
45062 **
45063 **    FULL      The journal is synced twice before writes begin on the
45064 **              database (with some additional information - the nRec field
45065 **              of the journal header - being written in between the two
45066 **              syncs).  If we assume that writing a
45067 **              single disk sector is atomic, then this mode provides
45068 **              assurance that the journal will not be corrupted to the
45069 **              point of causing damage to the database during rollback.
45070 **
45071 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
45072 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
45073 ** prior to the start of checkpoint and that the database file is synced
45074 ** at the conclusion of the checkpoint if the entire content of the WAL
45075 ** was written back into the database.  But no sync operations occur for
45076 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
45077 ** file is synced following each commit operation, in addition to the
45078 ** syncs associated with NORMAL.
45079 **
45080 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
45081 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
45082 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
45083 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
45084 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
45085 ** synchronous=FULL versus synchronous=NORMAL setting determines when
45086 ** the xSync primitive is called and is relevant to all platforms.
45087 **
45088 ** Numeric values associated with these states are OFF==1, NORMAL=2,
45089 ** and FULL=3.
45090 */
45091 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
45092 SQLITE_PRIVATE void sqlite3PagerSetFlags(
45093   Pager *pPager,        /* The pager to set safety level for */
45094   unsigned pgFlags      /* Various flags */
45095 ){
45096   unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
45097   assert( level>=1 && level<=3 );
45098   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
45099   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
45100   if( pPager->noSync ){
45101     pPager->syncFlags = 0;
45102     pPager->ckptSyncFlags = 0;
45103   }else if( pgFlags & PAGER_FULLFSYNC ){
45104     pPager->syncFlags = SQLITE_SYNC_FULL;
45105     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
45106   }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
45107     pPager->syncFlags = SQLITE_SYNC_NORMAL;
45108     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
45109   }else{
45110     pPager->syncFlags = SQLITE_SYNC_NORMAL;
45111     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
45112   }
45113   pPager->walSyncFlags = pPager->syncFlags;
45114   if( pPager->fullSync ){
45115     pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
45116   }
45117   if( pgFlags & PAGER_CACHESPILL ){
45118     pPager->doNotSpill &= ~SPILLFLAG_OFF;
45119   }else{
45120     pPager->doNotSpill |= SPILLFLAG_OFF;
45121   }
45122 }
45123 #endif
45124 
45125 /*
45126 ** The following global variable is incremented whenever the library
45127 ** attempts to open a temporary file.  This information is used for
45128 ** testing and analysis only.
45129 */
45130 #ifdef SQLITE_TEST
45131 SQLITE_API int sqlite3_opentemp_count = 0;
45132 #endif
45133 
45134 /*
45135 ** Open a temporary file.
45136 **
45137 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
45138 ** or some other error code if we fail. The OS will automatically
45139 ** delete the temporary file when it is closed.
45140 **
45141 ** The flags passed to the VFS layer xOpen() call are those specified
45142 ** by parameter vfsFlags ORed with the following:
45143 **
45144 **     SQLITE_OPEN_READWRITE
45145 **     SQLITE_OPEN_CREATE
45146 **     SQLITE_OPEN_EXCLUSIVE
45147 **     SQLITE_OPEN_DELETEONCLOSE
45148 */
45149 static int pagerOpentemp(
45150   Pager *pPager,        /* The pager object */
45151   sqlite3_file *pFile,  /* Write the file descriptor here */
45152   int vfsFlags          /* Flags passed through to the VFS */
45153 ){
45154   int rc;               /* Return code */
45155 
45156 #ifdef SQLITE_TEST
45157   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
45158 #endif
45159 
45160   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
45161             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
45162   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
45163   assert( rc!=SQLITE_OK || isOpen(pFile) );
45164   return rc;
45165 }
45166 
45167 /*
45168 ** Set the busy handler function.
45169 **
45170 ** The pager invokes the busy-handler if sqlite3OsLock() returns
45171 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
45172 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
45173 ** lock. It does *not* invoke the busy handler when upgrading from
45174 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
45175 ** (which occurs during hot-journal rollback). Summary:
45176 **
45177 **   Transition                        | Invokes xBusyHandler
45178 **   --------------------------------------------------------
45179 **   NO_LOCK       -> SHARED_LOCK      | Yes
45180 **   SHARED_LOCK   -> RESERVED_LOCK    | No
45181 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
45182 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
45183 **
45184 ** If the busy-handler callback returns non-zero, the lock is
45185 ** retried. If it returns zero, then the SQLITE_BUSY error is
45186 ** returned to the caller of the pager API function.
45187 */
45188 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
45189   Pager *pPager,                       /* Pager object */
45190   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
45191   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
45192 ){
45193   pPager->xBusyHandler = xBusyHandler;
45194   pPager->pBusyHandlerArg = pBusyHandlerArg;
45195 
45196   if( isOpen(pPager->fd) ){
45197     void **ap = (void **)&pPager->xBusyHandler;
45198     assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
45199     assert( ap[1]==pBusyHandlerArg );
45200     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
45201   }
45202 }
45203 
45204 /*
45205 ** Change the page size used by the Pager object. The new page size
45206 ** is passed in *pPageSize.
45207 **
45208 ** If the pager is in the error state when this function is called, it
45209 ** is a no-op. The value returned is the error state error code (i.e.
45210 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
45211 **
45212 ** Otherwise, if all of the following are true:
45213 **
45214 **   * the new page size (value of *pPageSize) is valid (a power
45215 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
45216 **
45217 **   * there are no outstanding page references, and
45218 **
45219 **   * the database is either not an in-memory database or it is
45220 **     an in-memory database that currently consists of zero pages.
45221 **
45222 ** then the pager object page size is set to *pPageSize.
45223 **
45224 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
45225 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
45226 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
45227 ** In all other cases, SQLITE_OK is returned.
45228 **
45229 ** If the page size is not changed, either because one of the enumerated
45230 ** conditions above is not true, the pager was in error state when this
45231 ** function was called, or because the memory allocation attempt failed,
45232 ** then *pPageSize is set to the old, retained page size before returning.
45233 */
45234 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
45235   int rc = SQLITE_OK;
45236 
45237   /* It is not possible to do a full assert_pager_state() here, as this
45238   ** function may be called from within PagerOpen(), before the state
45239   ** of the Pager object is internally consistent.
45240   **
45241   ** At one point this function returned an error if the pager was in
45242   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
45243   ** there is at least one outstanding page reference, this function
45244   ** is a no-op for that case anyhow.
45245   */
45246 
45247   u32 pageSize = *pPageSize;
45248   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
45249   if( (pPager->memDb==0 || pPager->dbSize==0)
45250    && sqlite3PcacheRefCount(pPager->pPCache)==0
45251    && pageSize && pageSize!=(u32)pPager->pageSize
45252   ){
45253     char *pNew = NULL;             /* New temp space */
45254     i64 nByte = 0;
45255 
45256     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
45257       rc = sqlite3OsFileSize(pPager->fd, &nByte);
45258     }
45259     if( rc==SQLITE_OK ){
45260       pNew = (char *)sqlite3PageMalloc(pageSize);
45261       if( !pNew ) rc = SQLITE_NOMEM;
45262     }
45263 
45264     if( rc==SQLITE_OK ){
45265       pager_reset(pPager);
45266       rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
45267     }
45268     if( rc==SQLITE_OK ){
45269       sqlite3PageFree(pPager->pTmpSpace);
45270       pPager->pTmpSpace = pNew;
45271       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
45272       pPager->pageSize = pageSize;
45273     }else{
45274       sqlite3PageFree(pNew);
45275     }
45276   }
45277 
45278   *pPageSize = pPager->pageSize;
45279   if( rc==SQLITE_OK ){
45280     if( nReserve<0 ) nReserve = pPager->nReserve;
45281     assert( nReserve>=0 && nReserve<1000 );
45282     pPager->nReserve = (i16)nReserve;
45283     pagerReportSize(pPager);
45284     pagerFixMaplimit(pPager);
45285   }
45286   return rc;
45287 }
45288 
45289 /*
45290 ** Return a pointer to the "temporary page" buffer held internally
45291 ** by the pager.  This is a buffer that is big enough to hold the
45292 ** entire content of a database page.  This buffer is used internally
45293 ** during rollback and will be overwritten whenever a rollback
45294 ** occurs.  But other modules are free to use it too, as long as
45295 ** no rollbacks are happening.
45296 */
45297 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
45298   return pPager->pTmpSpace;
45299 }
45300 
45301 /*
45302 ** Attempt to set the maximum database page count if mxPage is positive.
45303 ** Make no changes if mxPage is zero or negative.  And never reduce the
45304 ** maximum page count below the current size of the database.
45305 **
45306 ** Regardless of mxPage, return the current maximum page count.
45307 */
45308 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
45309   if( mxPage>0 ){
45310     pPager->mxPgno = mxPage;
45311   }
45312   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
45313   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
45314   return pPager->mxPgno;
45315 }
45316 
45317 /*
45318 ** The following set of routines are used to disable the simulated
45319 ** I/O error mechanism.  These routines are used to avoid simulated
45320 ** errors in places where we do not care about errors.
45321 **
45322 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
45323 ** and generate no code.
45324 */
45325 #ifdef SQLITE_TEST
45326 SQLITE_API extern int sqlite3_io_error_pending;
45327 SQLITE_API extern int sqlite3_io_error_hit;
45328 static int saved_cnt;
45329 void disable_simulated_io_errors(void){
45330   saved_cnt = sqlite3_io_error_pending;
45331   sqlite3_io_error_pending = -1;
45332 }
45333 void enable_simulated_io_errors(void){
45334   sqlite3_io_error_pending = saved_cnt;
45335 }
45336 #else
45337 # define disable_simulated_io_errors()
45338 # define enable_simulated_io_errors()
45339 #endif
45340 
45341 /*
45342 ** Read the first N bytes from the beginning of the file into memory
45343 ** that pDest points to.
45344 **
45345 ** If the pager was opened on a transient file (zFilename==""), or
45346 ** opened on a file less than N bytes in size, the output buffer is
45347 ** zeroed and SQLITE_OK returned. The rationale for this is that this
45348 ** function is used to read database headers, and a new transient or
45349 ** zero sized database has a header than consists entirely of zeroes.
45350 **
45351 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
45352 ** the error code is returned to the caller and the contents of the
45353 ** output buffer undefined.
45354 */
45355 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
45356   int rc = SQLITE_OK;
45357   memset(pDest, 0, N);
45358   assert( isOpen(pPager->fd) || pPager->tempFile );
45359 
45360   /* This routine is only called by btree immediately after creating
45361   ** the Pager object.  There has not been an opportunity to transition
45362   ** to WAL mode yet.
45363   */
45364   assert( !pagerUseWal(pPager) );
45365 
45366   if( isOpen(pPager->fd) ){
45367     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
45368     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
45369     if( rc==SQLITE_IOERR_SHORT_READ ){
45370       rc = SQLITE_OK;
45371     }
45372   }
45373   return rc;
45374 }
45375 
45376 /*
45377 ** This function may only be called when a read-transaction is open on
45378 ** the pager. It returns the total number of pages in the database.
45379 **
45380 ** However, if the file is between 1 and <page-size> bytes in size, then
45381 ** this is considered a 1 page file.
45382 */
45383 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
45384   assert( pPager->eState>=PAGER_READER );
45385   assert( pPager->eState!=PAGER_WRITER_FINISHED );
45386   *pnPage = (int)pPager->dbSize;
45387 }
45388 
45389 
45390 /*
45391 ** Try to obtain a lock of type locktype on the database file. If
45392 ** a similar or greater lock is already held, this function is a no-op
45393 ** (returning SQLITE_OK immediately).
45394 **
45395 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
45396 ** the busy callback if the lock is currently not available. Repeat
45397 ** until the busy callback returns false or until the attempt to
45398 ** obtain the lock succeeds.
45399 **
45400 ** Return SQLITE_OK on success and an error code if we cannot obtain
45401 ** the lock. If the lock is obtained successfully, set the Pager.state
45402 ** variable to locktype before returning.
45403 */
45404 static int pager_wait_on_lock(Pager *pPager, int locktype){
45405   int rc;                              /* Return code */
45406 
45407   /* Check that this is either a no-op (because the requested lock is
45408   ** already held), or one of the transitions that the busy-handler
45409   ** may be invoked during, according to the comment above
45410   ** sqlite3PagerSetBusyhandler().
45411   */
45412   assert( (pPager->eLock>=locktype)
45413        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
45414        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
45415   );
45416 
45417   do {
45418     rc = pagerLockDb(pPager, locktype);
45419   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
45420   return rc;
45421 }
45422 
45423 /*
45424 ** Function assertTruncateConstraint(pPager) checks that one of the
45425 ** following is true for all dirty pages currently in the page-cache:
45426 **
45427 **   a) The page number is less than or equal to the size of the
45428 **      current database image, in pages, OR
45429 **
45430 **   b) if the page content were written at this time, it would not
45431 **      be necessary to write the current content out to the sub-journal
45432 **      (as determined by function subjRequiresPage()).
45433 **
45434 ** If the condition asserted by this function were not true, and the
45435 ** dirty page were to be discarded from the cache via the pagerStress()
45436 ** routine, pagerStress() would not write the current page content to
45437 ** the database file. If a savepoint transaction were rolled back after
45438 ** this happened, the correct behavior would be to restore the current
45439 ** content of the page. However, since this content is not present in either
45440 ** the database file or the portion of the rollback journal and
45441 ** sub-journal rolled back the content could not be restored and the
45442 ** database image would become corrupt. It is therefore fortunate that
45443 ** this circumstance cannot arise.
45444 */
45445 #if defined(SQLITE_DEBUG)
45446 static void assertTruncateConstraintCb(PgHdr *pPg){
45447   assert( pPg->flags&PGHDR_DIRTY );
45448   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
45449 }
45450 static void assertTruncateConstraint(Pager *pPager){
45451   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
45452 }
45453 #else
45454 # define assertTruncateConstraint(pPager)
45455 #endif
45456 
45457 /*
45458 ** Truncate the in-memory database file image to nPage pages. This
45459 ** function does not actually modify the database file on disk. It
45460 ** just sets the internal state of the pager object so that the
45461 ** truncation will be done when the current transaction is committed.
45462 **
45463 ** This function is only called right before committing a transaction.
45464 ** Once this function has been called, the transaction must either be
45465 ** rolled back or committed. It is not safe to call this function and
45466 ** then continue writing to the database.
45467 */
45468 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
45469   assert( pPager->dbSize>=nPage );
45470   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
45471   pPager->dbSize = nPage;
45472 
45473   /* At one point the code here called assertTruncateConstraint() to
45474   ** ensure that all pages being truncated away by this operation are,
45475   ** if one or more savepoints are open, present in the savepoint
45476   ** journal so that they can be restored if the savepoint is rolled
45477   ** back. This is no longer necessary as this function is now only
45478   ** called right before committing a transaction. So although the
45479   ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
45480   ** they cannot be rolled back. So the assertTruncateConstraint() call
45481   ** is no longer correct. */
45482 }
45483 
45484 
45485 /*
45486 ** This function is called before attempting a hot-journal rollback. It
45487 ** syncs the journal file to disk, then sets pPager->journalHdr to the
45488 ** size of the journal file so that the pager_playback() routine knows
45489 ** that the entire journal file has been synced.
45490 **
45491 ** Syncing a hot-journal to disk before attempting to roll it back ensures
45492 ** that if a power-failure occurs during the rollback, the process that
45493 ** attempts rollback following system recovery sees the same journal
45494 ** content as this process.
45495 **
45496 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
45497 ** an SQLite error code.
45498 */
45499 static int pagerSyncHotJournal(Pager *pPager){
45500   int rc = SQLITE_OK;
45501   if( !pPager->noSync ){
45502     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
45503   }
45504   if( rc==SQLITE_OK ){
45505     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
45506   }
45507   return rc;
45508 }
45509 
45510 /*
45511 ** Obtain a reference to a memory mapped page object for page number pgno.
45512 ** The new object will use the pointer pData, obtained from xFetch().
45513 ** If successful, set *ppPage to point to the new page reference
45514 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
45515 ** *ppPage to zero.
45516 **
45517 ** Page references obtained by calling this function should be released
45518 ** by calling pagerReleaseMapPage().
45519 */
45520 static int pagerAcquireMapPage(
45521   Pager *pPager,                  /* Pager object */
45522   Pgno pgno,                      /* Page number */
45523   void *pData,                    /* xFetch()'d data for this page */
45524   PgHdr **ppPage                  /* OUT: Acquired page object */
45525 ){
45526   PgHdr *p;                       /* Memory mapped page to return */
45527 
45528   if( pPager->pMmapFreelist ){
45529     *ppPage = p = pPager->pMmapFreelist;
45530     pPager->pMmapFreelist = p->pDirty;
45531     p->pDirty = 0;
45532     memset(p->pExtra, 0, pPager->nExtra);
45533   }else{
45534     *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
45535     if( p==0 ){
45536       sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
45537       return SQLITE_NOMEM;
45538     }
45539     p->pExtra = (void *)&p[1];
45540     p->flags = PGHDR_MMAP;
45541     p->nRef = 1;
45542     p->pPager = pPager;
45543   }
45544 
45545   assert( p->pExtra==(void *)&p[1] );
45546   assert( p->pPage==0 );
45547   assert( p->flags==PGHDR_MMAP );
45548   assert( p->pPager==pPager );
45549   assert( p->nRef==1 );
45550 
45551   p->pgno = pgno;
45552   p->pData = pData;
45553   pPager->nMmapOut++;
45554 
45555   return SQLITE_OK;
45556 }
45557 
45558 /*
45559 ** Release a reference to page pPg. pPg must have been returned by an
45560 ** earlier call to pagerAcquireMapPage().
45561 */
45562 static void pagerReleaseMapPage(PgHdr *pPg){
45563   Pager *pPager = pPg->pPager;
45564   pPager->nMmapOut--;
45565   pPg->pDirty = pPager->pMmapFreelist;
45566   pPager->pMmapFreelist = pPg;
45567 
45568   assert( pPager->fd->pMethods->iVersion>=3 );
45569   sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
45570 }
45571 
45572 /*
45573 ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
45574 */
45575 static void pagerFreeMapHdrs(Pager *pPager){
45576   PgHdr *p;
45577   PgHdr *pNext;
45578   for(p=pPager->pMmapFreelist; p; p=pNext){
45579     pNext = p->pDirty;
45580     sqlite3_free(p);
45581   }
45582 }
45583 
45584 
45585 /*
45586 ** Shutdown the page cache.  Free all memory and close all files.
45587 **
45588 ** If a transaction was in progress when this routine is called, that
45589 ** transaction is rolled back.  All outstanding pages are invalidated
45590 ** and their memory is freed.  Any attempt to use a page associated
45591 ** with this page cache after this function returns will likely
45592 ** result in a coredump.
45593 **
45594 ** This function always succeeds. If a transaction is active an attempt
45595 ** is made to roll it back. If an error occurs during the rollback
45596 ** a hot journal may be left in the filesystem but no error is returned
45597 ** to the caller.
45598 */
45599 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
45600   u8 *pTmp = (u8 *)pPager->pTmpSpace;
45601 
45602   assert( assert_pager_state(pPager) );
45603   disable_simulated_io_errors();
45604   sqlite3BeginBenignMalloc();
45605   pagerFreeMapHdrs(pPager);
45606   /* pPager->errCode = 0; */
45607   pPager->exclusiveMode = 0;
45608 #ifndef SQLITE_OMIT_WAL
45609   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
45610   pPager->pWal = 0;
45611 #endif
45612   pager_reset(pPager);
45613   if( MEMDB ){
45614     pager_unlock(pPager);
45615   }else{
45616     /* If it is open, sync the journal file before calling UnlockAndRollback.
45617     ** If this is not done, then an unsynced portion of the open journal
45618     ** file may be played back into the database. If a power failure occurs
45619     ** while this is happening, the database could become corrupt.
45620     **
45621     ** If an error occurs while trying to sync the journal, shift the pager
45622     ** into the ERROR state. This causes UnlockAndRollback to unlock the
45623     ** database and close the journal file without attempting to roll it
45624     ** back or finalize it. The next database user will have to do hot-journal
45625     ** rollback before accessing the database file.
45626     */
45627     if( isOpen(pPager->jfd) ){
45628       pager_error(pPager, pagerSyncHotJournal(pPager));
45629     }
45630     pagerUnlockAndRollback(pPager);
45631   }
45632   sqlite3EndBenignMalloc();
45633   enable_simulated_io_errors();
45634   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
45635   IOTRACE(("CLOSE %p\n", pPager))
45636   sqlite3OsClose(pPager->jfd);
45637   sqlite3OsClose(pPager->fd);
45638   sqlite3PageFree(pTmp);
45639   sqlite3PcacheClose(pPager->pPCache);
45640 
45641 #ifdef SQLITE_HAS_CODEC
45642   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
45643 #endif
45644 
45645   assert( !pPager->aSavepoint && !pPager->pInJournal );
45646   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
45647 
45648   sqlite3_free(pPager);
45649   return SQLITE_OK;
45650 }
45651 
45652 #if !defined(NDEBUG) || defined(SQLITE_TEST)
45653 /*
45654 ** Return the page number for page pPg.
45655 */
45656 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
45657   return pPg->pgno;
45658 }
45659 #endif
45660 
45661 /*
45662 ** Increment the reference count for page pPg.
45663 */
45664 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
45665   sqlite3PcacheRef(pPg);
45666 }
45667 
45668 /*
45669 ** Sync the journal. In other words, make sure all the pages that have
45670 ** been written to the journal have actually reached the surface of the
45671 ** disk and can be restored in the event of a hot-journal rollback.
45672 **
45673 ** If the Pager.noSync flag is set, then this function is a no-op.
45674 ** Otherwise, the actions required depend on the journal-mode and the
45675 ** device characteristics of the file-system, as follows:
45676 **
45677 **   * If the journal file is an in-memory journal file, no action need
45678 **     be taken.
45679 **
45680 **   * Otherwise, if the device does not support the SAFE_APPEND property,
45681 **     then the nRec field of the most recently written journal header
45682 **     is updated to contain the number of journal records that have
45683 **     been written following it. If the pager is operating in full-sync
45684 **     mode, then the journal file is synced before this field is updated.
45685 **
45686 **   * If the device does not support the SEQUENTIAL property, then
45687 **     journal file is synced.
45688 **
45689 ** Or, in pseudo-code:
45690 **
45691 **   if( NOT <in-memory journal> ){
45692 **     if( NOT SAFE_APPEND ){
45693 **       if( <full-sync mode> ) xSync(<journal file>);
45694 **       <update nRec field>
45695 **     }
45696 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
45697 **   }
45698 **
45699 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
45700 ** page currently held in memory before returning SQLITE_OK. If an IO
45701 ** error is encountered, then the IO error code is returned to the caller.
45702 */
45703 static int syncJournal(Pager *pPager, int newHdr){
45704   int rc;                         /* Return code */
45705 
45706   assert( pPager->eState==PAGER_WRITER_CACHEMOD
45707        || pPager->eState==PAGER_WRITER_DBMOD
45708   );
45709   assert( assert_pager_state(pPager) );
45710   assert( !pagerUseWal(pPager) );
45711 
45712   rc = sqlite3PagerExclusiveLock(pPager);
45713   if( rc!=SQLITE_OK ) return rc;
45714 
45715   if( !pPager->noSync ){
45716     assert( !pPager->tempFile );
45717     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
45718       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
45719       assert( isOpen(pPager->jfd) );
45720 
45721       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
45722         /* This block deals with an obscure problem. If the last connection
45723         ** that wrote to this database was operating in persistent-journal
45724         ** mode, then the journal file may at this point actually be larger
45725         ** than Pager.journalOff bytes. If the next thing in the journal
45726         ** file happens to be a journal-header (written as part of the
45727         ** previous connection's transaction), and a crash or power-failure
45728         ** occurs after nRec is updated but before this connection writes
45729         ** anything else to the journal file (or commits/rolls back its
45730         ** transaction), then SQLite may become confused when doing the
45731         ** hot-journal rollback following recovery. It may roll back all
45732         ** of this connections data, then proceed to rolling back the old,
45733         ** out-of-date data that follows it. Database corruption.
45734         **
45735         ** To work around this, if the journal file does appear to contain
45736         ** a valid header following Pager.journalOff, then write a 0x00
45737         ** byte to the start of it to prevent it from being recognized.
45738         **
45739         ** Variable iNextHdrOffset is set to the offset at which this
45740         ** problematic header will occur, if it exists. aMagic is used
45741         ** as a temporary buffer to inspect the first couple of bytes of
45742         ** the potential journal header.
45743         */
45744         i64 iNextHdrOffset;
45745         u8 aMagic[8];
45746         u8 zHeader[sizeof(aJournalMagic)+4];
45747 
45748         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
45749         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
45750 
45751         iNextHdrOffset = journalHdrOffset(pPager);
45752         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
45753         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
45754           static const u8 zerobyte = 0;
45755           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
45756         }
45757         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
45758           return rc;
45759         }
45760 
45761         /* Write the nRec value into the journal file header. If in
45762         ** full-synchronous mode, sync the journal first. This ensures that
45763         ** all data has really hit the disk before nRec is updated to mark
45764         ** it as a candidate for rollback.
45765         **
45766         ** This is not required if the persistent media supports the
45767         ** SAFE_APPEND property. Because in this case it is not possible
45768         ** for garbage data to be appended to the file, the nRec field
45769         ** is populated with 0xFFFFFFFF when the journal header is written
45770         ** and never needs to be updated.
45771         */
45772         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
45773           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
45774           IOTRACE(("JSYNC %p\n", pPager))
45775           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
45776           if( rc!=SQLITE_OK ) return rc;
45777         }
45778         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
45779         rc = sqlite3OsWrite(
45780             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
45781         );
45782         if( rc!=SQLITE_OK ) return rc;
45783       }
45784       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
45785         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
45786         IOTRACE(("JSYNC %p\n", pPager))
45787         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
45788           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
45789         );
45790         if( rc!=SQLITE_OK ) return rc;
45791       }
45792 
45793       pPager->journalHdr = pPager->journalOff;
45794       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
45795         pPager->nRec = 0;
45796         rc = writeJournalHdr(pPager);
45797         if( rc!=SQLITE_OK ) return rc;
45798       }
45799     }else{
45800       pPager->journalHdr = pPager->journalOff;
45801     }
45802   }
45803 
45804   /* Unless the pager is in noSync mode, the journal file was just
45805   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
45806   ** all pages.
45807   */
45808   sqlite3PcacheClearSyncFlags(pPager->pPCache);
45809   pPager->eState = PAGER_WRITER_DBMOD;
45810   assert( assert_pager_state(pPager) );
45811   return SQLITE_OK;
45812 }
45813 
45814 /*
45815 ** The argument is the first in a linked list of dirty pages connected
45816 ** by the PgHdr.pDirty pointer. This function writes each one of the
45817 ** in-memory pages in the list to the database file. The argument may
45818 ** be NULL, representing an empty list. In this case this function is
45819 ** a no-op.
45820 **
45821 ** The pager must hold at least a RESERVED lock when this function
45822 ** is called. Before writing anything to the database file, this lock
45823 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
45824 ** SQLITE_BUSY is returned and no data is written to the database file.
45825 **
45826 ** If the pager is a temp-file pager and the actual file-system file
45827 ** is not yet open, it is created and opened before any data is
45828 ** written out.
45829 **
45830 ** Once the lock has been upgraded and, if necessary, the file opened,
45831 ** the pages are written out to the database file in list order. Writing
45832 ** a page is skipped if it meets either of the following criteria:
45833 **
45834 **   * The page number is greater than Pager.dbSize, or
45835 **   * The PGHDR_DONT_WRITE flag is set on the page.
45836 **
45837 ** If writing out a page causes the database file to grow, Pager.dbFileSize
45838 ** is updated accordingly. If page 1 is written out, then the value cached
45839 ** in Pager.dbFileVers[] is updated to match the new value stored in
45840 ** the database file.
45841 **
45842 ** If everything is successful, SQLITE_OK is returned. If an IO error
45843 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
45844 ** be obtained, SQLITE_BUSY is returned.
45845 */
45846 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
45847   int rc = SQLITE_OK;                  /* Return code */
45848 
45849   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
45850   assert( !pagerUseWal(pPager) );
45851   assert( pPager->eState==PAGER_WRITER_DBMOD );
45852   assert( pPager->eLock==EXCLUSIVE_LOCK );
45853 
45854   /* If the file is a temp-file has not yet been opened, open it now. It
45855   ** is not possible for rc to be other than SQLITE_OK if this branch
45856   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
45857   */
45858   if( !isOpen(pPager->fd) ){
45859     assert( pPager->tempFile && rc==SQLITE_OK );
45860     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
45861   }
45862 
45863   /* Before the first write, give the VFS a hint of what the final
45864   ** file size will be.
45865   */
45866   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
45867   if( rc==SQLITE_OK
45868    && pPager->dbHintSize<pPager->dbSize
45869    && (pList->pDirty || pList->pgno>pPager->dbHintSize)
45870   ){
45871     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
45872     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
45873     pPager->dbHintSize = pPager->dbSize;
45874   }
45875 
45876   while( rc==SQLITE_OK && pList ){
45877     Pgno pgno = pList->pgno;
45878 
45879     /* If there are dirty pages in the page cache with page numbers greater
45880     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
45881     ** make the file smaller (presumably by auto-vacuum code). Do not write
45882     ** any such pages to the file.
45883     **
45884     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
45885     ** set (set by sqlite3PagerDontWrite()).
45886     */
45887     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
45888       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
45889       char *pData;                                   /* Data to write */
45890 
45891       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
45892       if( pList->pgno==1 ) pager_write_changecounter(pList);
45893 
45894       /* Encode the database */
45895       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
45896 
45897       /* Write out the page data. */
45898       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
45899 
45900       /* If page 1 was just written, update Pager.dbFileVers to match
45901       ** the value now stored in the database file. If writing this
45902       ** page caused the database file to grow, update dbFileSize.
45903       */
45904       if( pgno==1 ){
45905         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
45906       }
45907       if( pgno>pPager->dbFileSize ){
45908         pPager->dbFileSize = pgno;
45909       }
45910       pPager->aStat[PAGER_STAT_WRITE]++;
45911 
45912       /* Update any backup objects copying the contents of this pager. */
45913       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
45914 
45915       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
45916                    PAGERID(pPager), pgno, pager_pagehash(pList)));
45917       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
45918       PAGER_INCR(sqlite3_pager_writedb_count);
45919     }else{
45920       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
45921     }
45922     pager_set_pagehash(pList);
45923     pList = pList->pDirty;
45924   }
45925 
45926   return rc;
45927 }
45928 
45929 /*
45930 ** Ensure that the sub-journal file is open. If it is already open, this
45931 ** function is a no-op.
45932 **
45933 ** SQLITE_OK is returned if everything goes according to plan. An
45934 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
45935 ** fails.
45936 */
45937 static int openSubJournal(Pager *pPager){
45938   int rc = SQLITE_OK;
45939   if( !isOpen(pPager->sjfd) ){
45940     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
45941       sqlite3MemJournalOpen(pPager->sjfd);
45942     }else{
45943       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
45944     }
45945   }
45946   return rc;
45947 }
45948 
45949 /*
45950 ** Append a record of the current state of page pPg to the sub-journal.
45951 ** It is the callers responsibility to use subjRequiresPage() to check
45952 ** that it is really required before calling this function.
45953 **
45954 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
45955 ** for all open savepoints before returning.
45956 **
45957 ** This function returns SQLITE_OK if everything is successful, an IO
45958 ** error code if the attempt to write to the sub-journal fails, or
45959 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
45960 ** bitvec.
45961 */
45962 static int subjournalPage(PgHdr *pPg){
45963   int rc = SQLITE_OK;
45964   Pager *pPager = pPg->pPager;
45965   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
45966 
45967     /* Open the sub-journal, if it has not already been opened */
45968     assert( pPager->useJournal );
45969     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
45970     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
45971     assert( pagerUseWal(pPager)
45972          || pageInJournal(pPager, pPg)
45973          || pPg->pgno>pPager->dbOrigSize
45974     );
45975     rc = openSubJournal(pPager);
45976 
45977     /* If the sub-journal was opened successfully (or was already open),
45978     ** write the journal record into the file.  */
45979     if( rc==SQLITE_OK ){
45980       void *pData = pPg->pData;
45981       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
45982       char *pData2;
45983 
45984       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
45985       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
45986       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
45987       if( rc==SQLITE_OK ){
45988         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
45989       }
45990     }
45991   }
45992   if( rc==SQLITE_OK ){
45993     pPager->nSubRec++;
45994     assert( pPager->nSavepoint>0 );
45995     rc = addToSavepointBitvecs(pPager, pPg->pgno);
45996   }
45997   return rc;
45998 }
45999 
46000 /*
46001 ** This function is called by the pcache layer when it has reached some
46002 ** soft memory limit. The first argument is a pointer to a Pager object
46003 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
46004 ** database). The second argument is a reference to a page that is
46005 ** currently dirty but has no outstanding references. The page
46006 ** is always associated with the Pager object passed as the first
46007 ** argument.
46008 **
46009 ** The job of this function is to make pPg clean by writing its contents
46010 ** out to the database file, if possible. This may involve syncing the
46011 ** journal file.
46012 **
46013 ** If successful, sqlite3PcacheMakeClean() is called on the page and
46014 ** SQLITE_OK returned. If an IO error occurs while trying to make the
46015 ** page clean, the IO error code is returned. If the page cannot be
46016 ** made clean for some other reason, but no error occurs, then SQLITE_OK
46017 ** is returned by sqlite3PcacheMakeClean() is not called.
46018 */
46019 static int pagerStress(void *p, PgHdr *pPg){
46020   Pager *pPager = (Pager *)p;
46021   int rc = SQLITE_OK;
46022 
46023   assert( pPg->pPager==pPager );
46024   assert( pPg->flags&PGHDR_DIRTY );
46025 
46026   /* The doNotSpill NOSYNC bit is set during times when doing a sync of
46027   ** journal (and adding a new header) is not allowed.  This occurs
46028   ** during calls to sqlite3PagerWrite() while trying to journal multiple
46029   ** pages belonging to the same sector.
46030   **
46031   ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
46032   ** regardless of whether or not a sync is required.  This is set during
46033   ** a rollback or by user request, respectively.
46034   **
46035   ** Spilling is also prohibited when in an error state since that could
46036   ** lead to database corruption.   In the current implementation it
46037   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
46038   ** while in the error state, hence it is impossible for this routine to
46039   ** be called in the error state.  Nevertheless, we include a NEVER()
46040   ** test for the error state as a safeguard against future changes.
46041   */
46042   if( NEVER(pPager->errCode) ) return SQLITE_OK;
46043   testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
46044   testcase( pPager->doNotSpill & SPILLFLAG_OFF );
46045   testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
46046   if( pPager->doNotSpill
46047    && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
46048       || (pPg->flags & PGHDR_NEED_SYNC)!=0)
46049   ){
46050     return SQLITE_OK;
46051   }
46052 
46053   pPg->pDirty = 0;
46054   if( pagerUseWal(pPager) ){
46055     /* Write a single frame for this page to the log. */
46056     if( subjRequiresPage(pPg) ){
46057       rc = subjournalPage(pPg);
46058     }
46059     if( rc==SQLITE_OK ){
46060       rc = pagerWalFrames(pPager, pPg, 0, 0);
46061     }
46062   }else{
46063 
46064     /* Sync the journal file if required. */
46065     if( pPg->flags&PGHDR_NEED_SYNC
46066      || pPager->eState==PAGER_WRITER_CACHEMOD
46067     ){
46068       rc = syncJournal(pPager, 1);
46069     }
46070 
46071     /* If the page number of this page is larger than the current size of
46072     ** the database image, it may need to be written to the sub-journal.
46073     ** This is because the call to pager_write_pagelist() below will not
46074     ** actually write data to the file in this case.
46075     **
46076     ** Consider the following sequence of events:
46077     **
46078     **   BEGIN;
46079     **     <journal page X>
46080     **     <modify page X>
46081     **     SAVEPOINT sp;
46082     **       <shrink database file to Y pages>
46083     **       pagerStress(page X)
46084     **     ROLLBACK TO sp;
46085     **
46086     ** If (X>Y), then when pagerStress is called page X will not be written
46087     ** out to the database file, but will be dropped from the cache. Then,
46088     ** following the "ROLLBACK TO sp" statement, reading page X will read
46089     ** data from the database file. This will be the copy of page X as it
46090     ** was when the transaction started, not as it was when "SAVEPOINT sp"
46091     ** was executed.
46092     **
46093     ** The solution is to write the current data for page X into the
46094     ** sub-journal file now (if it is not already there), so that it will
46095     ** be restored to its current value when the "ROLLBACK TO sp" is
46096     ** executed.
46097     */
46098     if( NEVER(
46099         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
46100     ) ){
46101       rc = subjournalPage(pPg);
46102     }
46103 
46104     /* Write the contents of the page out to the database file. */
46105     if( rc==SQLITE_OK ){
46106       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
46107       rc = pager_write_pagelist(pPager, pPg);
46108     }
46109   }
46110 
46111   /* Mark the page as clean. */
46112   if( rc==SQLITE_OK ){
46113     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
46114     sqlite3PcacheMakeClean(pPg);
46115   }
46116 
46117   return pager_error(pPager, rc);
46118 }
46119 
46120 
46121 /*
46122 ** Allocate and initialize a new Pager object and put a pointer to it
46123 ** in *ppPager. The pager should eventually be freed by passing it
46124 ** to sqlite3PagerClose().
46125 **
46126 ** The zFilename argument is the path to the database file to open.
46127 ** If zFilename is NULL then a randomly-named temporary file is created
46128 ** and used as the file to be cached. Temporary files are be deleted
46129 ** automatically when they are closed. If zFilename is ":memory:" then
46130 ** all information is held in cache. It is never written to disk.
46131 ** This can be used to implement an in-memory database.
46132 **
46133 ** The nExtra parameter specifies the number of bytes of space allocated
46134 ** along with each page reference. This space is available to the user
46135 ** via the sqlite3PagerGetExtra() API.
46136 **
46137 ** The flags argument is used to specify properties that affect the
46138 ** operation of the pager. It should be passed some bitwise combination
46139 ** of the PAGER_* flags.
46140 **
46141 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
46142 ** of the xOpen() method of the supplied VFS when opening files.
46143 **
46144 ** If the pager object is allocated and the specified file opened
46145 ** successfully, SQLITE_OK is returned and *ppPager set to point to
46146 ** the new pager object. If an error occurs, *ppPager is set to NULL
46147 ** and error code returned. This function may return SQLITE_NOMEM
46148 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
46149 ** various SQLITE_IO_XXX errors.
46150 */
46151 SQLITE_PRIVATE int sqlite3PagerOpen(
46152   sqlite3_vfs *pVfs,       /* The virtual file system to use */
46153   Pager **ppPager,         /* OUT: Return the Pager structure here */
46154   const char *zFilename,   /* Name of the database file to open */
46155   int nExtra,              /* Extra bytes append to each in-memory page */
46156   int flags,               /* flags controlling this file */
46157   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
46158   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
46159 ){
46160   u8 *pPtr;
46161   Pager *pPager = 0;       /* Pager object to allocate and return */
46162   int rc = SQLITE_OK;      /* Return code */
46163   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
46164   int memDb = 0;           /* True if this is an in-memory file */
46165   int readOnly = 0;        /* True if this is a read-only file */
46166   int journalFileSize;     /* Bytes to allocate for each journal fd */
46167   char *zPathname = 0;     /* Full path to database file */
46168   int nPathname = 0;       /* Number of bytes in zPathname */
46169   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
46170   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
46171   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
46172   const char *zUri = 0;    /* URI args to copy */
46173   int nUri = 0;            /* Number of bytes of URI args at *zUri */
46174 
46175   /* Figure out how much space is required for each journal file-handle
46176   ** (there are two of them, the main journal and the sub-journal). This
46177   ** is the maximum space required for an in-memory journal file handle
46178   ** and a regular journal file-handle. Note that a "regular journal-handle"
46179   ** may be a wrapper capable of caching the first portion of the journal
46180   ** file in memory to implement the atomic-write optimization (see
46181   ** source file journal.c).
46182   */
46183   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
46184     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
46185   }else{
46186     journalFileSize = ROUND8(sqlite3MemJournalSize());
46187   }
46188 
46189   /* Set the output variable to NULL in case an error occurs. */
46190   *ppPager = 0;
46191 
46192 #ifndef SQLITE_OMIT_MEMORYDB
46193   if( flags & PAGER_MEMORY ){
46194     memDb = 1;
46195     if( zFilename && zFilename[0] ){
46196       zPathname = sqlite3DbStrDup(0, zFilename);
46197       if( zPathname==0  ) return SQLITE_NOMEM;
46198       nPathname = sqlite3Strlen30(zPathname);
46199       zFilename = 0;
46200     }
46201   }
46202 #endif
46203 
46204   /* Compute and store the full pathname in an allocated buffer pointed
46205   ** to by zPathname, length nPathname. Or, if this is a temporary file,
46206   ** leave both nPathname and zPathname set to 0.
46207   */
46208   if( zFilename && zFilename[0] ){
46209     const char *z;
46210     nPathname = pVfs->mxPathname+1;
46211     zPathname = sqlite3DbMallocRaw(0, nPathname*2);
46212     if( zPathname==0 ){
46213       return SQLITE_NOMEM;
46214     }
46215     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
46216     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
46217     nPathname = sqlite3Strlen30(zPathname);
46218     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
46219     while( *z ){
46220       z += sqlite3Strlen30(z)+1;
46221       z += sqlite3Strlen30(z)+1;
46222     }
46223     nUri = (int)(&z[1] - zUri);
46224     assert( nUri>=0 );
46225     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
46226       /* This branch is taken when the journal path required by
46227       ** the database being opened will be more than pVfs->mxPathname
46228       ** bytes in length. This means the database cannot be opened,
46229       ** as it will not be possible to open the journal file or even
46230       ** check for a hot-journal before reading.
46231       */
46232       rc = SQLITE_CANTOPEN_BKPT;
46233     }
46234     if( rc!=SQLITE_OK ){
46235       sqlite3DbFree(0, zPathname);
46236       return rc;
46237     }
46238   }
46239 
46240   /* Allocate memory for the Pager structure, PCache object, the
46241   ** three file descriptors, the database file name and the journal
46242   ** file name. The layout in memory is as follows:
46243   **
46244   **     Pager object                    (sizeof(Pager) bytes)
46245   **     PCache object                   (sqlite3PcacheSize() bytes)
46246   **     Database file handle            (pVfs->szOsFile bytes)
46247   **     Sub-journal file handle         (journalFileSize bytes)
46248   **     Main journal file handle        (journalFileSize bytes)
46249   **     Database file name              (nPathname+1 bytes)
46250   **     Journal file name               (nPathname+8+1 bytes)
46251   */
46252   pPtr = (u8 *)sqlite3MallocZero(
46253     ROUND8(sizeof(*pPager)) +      /* Pager structure */
46254     ROUND8(pcacheSize) +           /* PCache object */
46255     ROUND8(pVfs->szOsFile) +       /* The main db file */
46256     journalFileSize * 2 +          /* The two journal files */
46257     nPathname + 1 + nUri +         /* zFilename */
46258     nPathname + 8 + 2              /* zJournal */
46259 #ifndef SQLITE_OMIT_WAL
46260     + nPathname + 4 + 2            /* zWal */
46261 #endif
46262   );
46263   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
46264   if( !pPtr ){
46265     sqlite3DbFree(0, zPathname);
46266     return SQLITE_NOMEM;
46267   }
46268   pPager =              (Pager*)(pPtr);
46269   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
46270   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
46271   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
46272   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
46273   pPager->zFilename =    (char*)(pPtr += journalFileSize);
46274   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
46275 
46276   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
46277   if( zPathname ){
46278     assert( nPathname>0 );
46279     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
46280     memcpy(pPager->zFilename, zPathname, nPathname);
46281     if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
46282     memcpy(pPager->zJournal, zPathname, nPathname);
46283     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
46284     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
46285 #ifndef SQLITE_OMIT_WAL
46286     pPager->zWal = &pPager->zJournal[nPathname+8+1];
46287     memcpy(pPager->zWal, zPathname, nPathname);
46288     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
46289     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
46290 #endif
46291     sqlite3DbFree(0, zPathname);
46292   }
46293   pPager->pVfs = pVfs;
46294   pPager->vfsFlags = vfsFlags;
46295 
46296   /* Open the pager file.
46297   */
46298   if( zFilename && zFilename[0] ){
46299     int fout = 0;                    /* VFS flags returned by xOpen() */
46300     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
46301     assert( !memDb );
46302     readOnly = (fout&SQLITE_OPEN_READONLY);
46303 
46304     /* If the file was successfully opened for read/write access,
46305     ** choose a default page size in case we have to create the
46306     ** database file. The default page size is the maximum of:
46307     **
46308     **    + SQLITE_DEFAULT_PAGE_SIZE,
46309     **    + The value returned by sqlite3OsSectorSize()
46310     **    + The largest page size that can be written atomically.
46311     */
46312     if( rc==SQLITE_OK ){
46313       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
46314       if( !readOnly ){
46315         setSectorSize(pPager);
46316         assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
46317         if( szPageDflt<pPager->sectorSize ){
46318           if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
46319             szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
46320           }else{
46321             szPageDflt = (u32)pPager->sectorSize;
46322           }
46323         }
46324 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
46325         {
46326           int ii;
46327           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
46328           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
46329           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
46330           for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
46331             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
46332               szPageDflt = ii;
46333             }
46334           }
46335         }
46336 #endif
46337       }
46338       pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
46339       if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
46340        || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
46341           vfsFlags |= SQLITE_OPEN_READONLY;
46342           goto act_like_temp_file;
46343       }
46344     }
46345   }else{
46346     /* If a temporary file is requested, it is not opened immediately.
46347     ** In this case we accept the default page size and delay actually
46348     ** opening the file until the first call to OsWrite().
46349     **
46350     ** This branch is also run for an in-memory database. An in-memory
46351     ** database is the same as a temp-file that is never written out to
46352     ** disk and uses an in-memory rollback journal.
46353     **
46354     ** This branch also runs for files marked as immutable.
46355     */
46356 act_like_temp_file:
46357     tempFile = 1;
46358     pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
46359     pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE locking mode */
46360     pPager->noLock = 1;                /* Do no locking */
46361     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
46362   }
46363 
46364   /* The following call to PagerSetPagesize() serves to set the value of
46365   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
46366   */
46367   if( rc==SQLITE_OK ){
46368     assert( pPager->memDb==0 );
46369     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
46370     testcase( rc!=SQLITE_OK );
46371   }
46372 
46373   /* Initialize the PCache object. */
46374   if( rc==SQLITE_OK ){
46375     assert( nExtra<1000 );
46376     nExtra = ROUND8(nExtra);
46377     rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
46378                            !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
46379   }
46380 
46381   /* If an error occurred above, free the  Pager structure and close the file.
46382   */
46383   if( rc!=SQLITE_OK ){
46384     sqlite3OsClose(pPager->fd);
46385     sqlite3PageFree(pPager->pTmpSpace);
46386     sqlite3_free(pPager);
46387     return rc;
46388   }
46389 
46390   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
46391   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
46392 
46393   pPager->useJournal = (u8)useJournal;
46394   /* pPager->stmtOpen = 0; */
46395   /* pPager->stmtInUse = 0; */
46396   /* pPager->nRef = 0; */
46397   /* pPager->stmtSize = 0; */
46398   /* pPager->stmtJSize = 0; */
46399   /* pPager->nPage = 0; */
46400   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
46401   /* pPager->state = PAGER_UNLOCK; */
46402   /* pPager->errMask = 0; */
46403   pPager->tempFile = (u8)tempFile;
46404   assert( tempFile==PAGER_LOCKINGMODE_NORMAL
46405           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
46406   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
46407   pPager->exclusiveMode = (u8)tempFile;
46408   pPager->changeCountDone = pPager->tempFile;
46409   pPager->memDb = (u8)memDb;
46410   pPager->readOnly = (u8)readOnly;
46411   assert( useJournal || pPager->tempFile );
46412   pPager->noSync = pPager->tempFile;
46413   if( pPager->noSync ){
46414     assert( pPager->fullSync==0 );
46415     assert( pPager->syncFlags==0 );
46416     assert( pPager->walSyncFlags==0 );
46417     assert( pPager->ckptSyncFlags==0 );
46418   }else{
46419     pPager->fullSync = 1;
46420     pPager->syncFlags = SQLITE_SYNC_NORMAL;
46421     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
46422     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
46423   }
46424   /* pPager->pFirst = 0; */
46425   /* pPager->pFirstSynced = 0; */
46426   /* pPager->pLast = 0; */
46427   pPager->nExtra = (u16)nExtra;
46428   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
46429   assert( isOpen(pPager->fd) || tempFile );
46430   setSectorSize(pPager);
46431   if( !useJournal ){
46432     pPager->journalMode = PAGER_JOURNALMODE_OFF;
46433   }else if( memDb ){
46434     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
46435   }
46436   /* pPager->xBusyHandler = 0; */
46437   /* pPager->pBusyHandlerArg = 0; */
46438   pPager->xReiniter = xReinit;
46439   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
46440   /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
46441 
46442   *ppPager = pPager;
46443   return SQLITE_OK;
46444 }
46445 
46446 
46447 /* Verify that the database file has not be deleted or renamed out from
46448 ** under the pager.  Return SQLITE_OK if the database is still were it ought
46449 ** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
46450 ** code from sqlite3OsAccess()) if the database has gone missing.
46451 */
46452 static int databaseIsUnmoved(Pager *pPager){
46453   int bHasMoved = 0;
46454   int rc;
46455 
46456   if( pPager->tempFile ) return SQLITE_OK;
46457   if( pPager->dbSize==0 ) return SQLITE_OK;
46458   assert( pPager->zFilename && pPager->zFilename[0] );
46459   rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
46460   if( rc==SQLITE_NOTFOUND ){
46461     /* If the HAS_MOVED file-control is unimplemented, assume that the file
46462     ** has not been moved.  That is the historical behavior of SQLite: prior to
46463     ** version 3.8.3, it never checked */
46464     rc = SQLITE_OK;
46465   }else if( rc==SQLITE_OK && bHasMoved ){
46466     rc = SQLITE_READONLY_DBMOVED;
46467   }
46468   return rc;
46469 }
46470 
46471 
46472 /*
46473 ** This function is called after transitioning from PAGER_UNLOCK to
46474 ** PAGER_SHARED state. It tests if there is a hot journal present in
46475 ** the file-system for the given pager. A hot journal is one that
46476 ** needs to be played back. According to this function, a hot-journal
46477 ** file exists if the following criteria are met:
46478 **
46479 **   * The journal file exists in the file system, and
46480 **   * No process holds a RESERVED or greater lock on the database file, and
46481 **   * The database file itself is greater than 0 bytes in size, and
46482 **   * The first byte of the journal file exists and is not 0x00.
46483 **
46484 ** If the current size of the database file is 0 but a journal file
46485 ** exists, that is probably an old journal left over from a prior
46486 ** database with the same name. In this case the journal file is
46487 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
46488 ** is returned.
46489 **
46490 ** This routine does not check if there is a master journal filename
46491 ** at the end of the file. If there is, and that master journal file
46492 ** does not exist, then the journal file is not really hot. In this
46493 ** case this routine will return a false-positive. The pager_playback()
46494 ** routine will discover that the journal file is not really hot and
46495 ** will not roll it back.
46496 **
46497 ** If a hot-journal file is found to exist, *pExists is set to 1 and
46498 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
46499 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
46500 ** to determine whether or not a hot-journal file exists, the IO error
46501 ** code is returned and the value of *pExists is undefined.
46502 */
46503 static int hasHotJournal(Pager *pPager, int *pExists){
46504   sqlite3_vfs * const pVfs = pPager->pVfs;
46505   int rc = SQLITE_OK;           /* Return code */
46506   int exists = 1;               /* True if a journal file is present */
46507   int jrnlOpen = !!isOpen(pPager->jfd);
46508 
46509   assert( pPager->useJournal );
46510   assert( isOpen(pPager->fd) );
46511   assert( pPager->eState==PAGER_OPEN );
46512 
46513   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
46514     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
46515   ));
46516 
46517   *pExists = 0;
46518   if( !jrnlOpen ){
46519     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
46520   }
46521   if( rc==SQLITE_OK && exists ){
46522     int locked = 0;             /* True if some process holds a RESERVED lock */
46523 
46524     /* Race condition here:  Another process might have been holding the
46525     ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
46526     ** call above, but then delete the journal and drop the lock before
46527     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
46528     ** is the case, this routine might think there is a hot journal when
46529     ** in fact there is none.  This results in a false-positive which will
46530     ** be dealt with by the playback routine.  Ticket #3883.
46531     */
46532     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
46533     if( rc==SQLITE_OK && !locked ){
46534       Pgno nPage;                 /* Number of pages in database file */
46535 
46536       rc = pagerPagecount(pPager, &nPage);
46537       if( rc==SQLITE_OK ){
46538         /* If the database is zero pages in size, that means that either (1) the
46539         ** journal is a remnant from a prior database with the same name where
46540         ** the database file but not the journal was deleted, or (2) the initial
46541         ** transaction that populates a new database is being rolled back.
46542         ** In either case, the journal file can be deleted.  However, take care
46543         ** not to delete the journal file if it is already open due to
46544         ** journal_mode=PERSIST.
46545         */
46546         if( nPage==0 && !jrnlOpen ){
46547           sqlite3BeginBenignMalloc();
46548           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
46549             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
46550             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
46551           }
46552           sqlite3EndBenignMalloc();
46553         }else{
46554           /* The journal file exists and no other connection has a reserved
46555           ** or greater lock on the database file. Now check that there is
46556           ** at least one non-zero bytes at the start of the journal file.
46557           ** If there is, then we consider this journal to be hot. If not,
46558           ** it can be ignored.
46559           */
46560           if( !jrnlOpen ){
46561             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
46562             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
46563           }
46564           if( rc==SQLITE_OK ){
46565             u8 first = 0;
46566             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
46567             if( rc==SQLITE_IOERR_SHORT_READ ){
46568               rc = SQLITE_OK;
46569             }
46570             if( !jrnlOpen ){
46571               sqlite3OsClose(pPager->jfd);
46572             }
46573             *pExists = (first!=0);
46574           }else if( rc==SQLITE_CANTOPEN ){
46575             /* If we cannot open the rollback journal file in order to see if
46576             ** it has a zero header, that might be due to an I/O error, or
46577             ** it might be due to the race condition described above and in
46578             ** ticket #3883.  Either way, assume that the journal is hot.
46579             ** This might be a false positive.  But if it is, then the
46580             ** automatic journal playback and recovery mechanism will deal
46581             ** with it under an EXCLUSIVE lock where we do not need to
46582             ** worry so much with race conditions.
46583             */
46584             *pExists = 1;
46585             rc = SQLITE_OK;
46586           }
46587         }
46588       }
46589     }
46590   }
46591 
46592   return rc;
46593 }
46594 
46595 /*
46596 ** This function is called to obtain a shared lock on the database file.
46597 ** It is illegal to call sqlite3PagerAcquire() until after this function
46598 ** has been successfully called. If a shared-lock is already held when
46599 ** this function is called, it is a no-op.
46600 **
46601 ** The following operations are also performed by this function.
46602 **
46603 **   1) If the pager is currently in PAGER_OPEN state (no lock held
46604 **      on the database file), then an attempt is made to obtain a
46605 **      SHARED lock on the database file. Immediately after obtaining
46606 **      the SHARED lock, the file-system is checked for a hot-journal,
46607 **      which is played back if present. Following any hot-journal
46608 **      rollback, the contents of the cache are validated by checking
46609 **      the 'change-counter' field of the database file header and
46610 **      discarded if they are found to be invalid.
46611 **
46612 **   2) If the pager is running in exclusive-mode, and there are currently
46613 **      no outstanding references to any pages, and is in the error state,
46614 **      then an attempt is made to clear the error state by discarding
46615 **      the contents of the page cache and rolling back any open journal
46616 **      file.
46617 **
46618 ** If everything is successful, SQLITE_OK is returned. If an IO error
46619 ** occurs while locking the database, checking for a hot-journal file or
46620 ** rolling back a journal file, the IO error code is returned.
46621 */
46622 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
46623   int rc = SQLITE_OK;                /* Return code */
46624 
46625   /* This routine is only called from b-tree and only when there are no
46626   ** outstanding pages. This implies that the pager state should either
46627   ** be OPEN or READER. READER is only possible if the pager is or was in
46628   ** exclusive access mode.
46629   */
46630   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
46631   assert( assert_pager_state(pPager) );
46632   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
46633   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
46634 
46635   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
46636     int bHotJournal = 1;          /* True if there exists a hot journal-file */
46637 
46638     assert( !MEMDB );
46639 
46640     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
46641     if( rc!=SQLITE_OK ){
46642       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
46643       goto failed;
46644     }
46645 
46646     /* If a journal file exists, and there is no RESERVED lock on the
46647     ** database file, then it either needs to be played back or deleted.
46648     */
46649     if( pPager->eLock<=SHARED_LOCK ){
46650       rc = hasHotJournal(pPager, &bHotJournal);
46651     }
46652     if( rc!=SQLITE_OK ){
46653       goto failed;
46654     }
46655     if( bHotJournal ){
46656       if( pPager->readOnly ){
46657         rc = SQLITE_READONLY_ROLLBACK;
46658         goto failed;
46659       }
46660 
46661       /* Get an EXCLUSIVE lock on the database file. At this point it is
46662       ** important that a RESERVED lock is not obtained on the way to the
46663       ** EXCLUSIVE lock. If it were, another process might open the
46664       ** database file, detect the RESERVED lock, and conclude that the
46665       ** database is safe to read while this process is still rolling the
46666       ** hot-journal back.
46667       **
46668       ** Because the intermediate RESERVED lock is not requested, any
46669       ** other process attempting to access the database file will get to
46670       ** this point in the code and fail to obtain its own EXCLUSIVE lock
46671       ** on the database file.
46672       **
46673       ** Unless the pager is in locking_mode=exclusive mode, the lock is
46674       ** downgraded to SHARED_LOCK before this function returns.
46675       */
46676       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
46677       if( rc!=SQLITE_OK ){
46678         goto failed;
46679       }
46680 
46681       /* If it is not already open and the file exists on disk, open the
46682       ** journal for read/write access. Write access is required because
46683       ** in exclusive-access mode the file descriptor will be kept open
46684       ** and possibly used for a transaction later on. Also, write-access
46685       ** is usually required to finalize the journal in journal_mode=persist
46686       ** mode (and also for journal_mode=truncate on some systems).
46687       **
46688       ** If the journal does not exist, it usually means that some
46689       ** other connection managed to get in and roll it back before
46690       ** this connection obtained the exclusive lock above. Or, it
46691       ** may mean that the pager was in the error-state when this
46692       ** function was called and the journal file does not exist.
46693       */
46694       if( !isOpen(pPager->jfd) ){
46695         sqlite3_vfs * const pVfs = pPager->pVfs;
46696         int bExists;              /* True if journal file exists */
46697         rc = sqlite3OsAccess(
46698             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
46699         if( rc==SQLITE_OK && bExists ){
46700           int fout = 0;
46701           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
46702           assert( !pPager->tempFile );
46703           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
46704           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
46705           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
46706             rc = SQLITE_CANTOPEN_BKPT;
46707             sqlite3OsClose(pPager->jfd);
46708           }
46709         }
46710       }
46711 
46712       /* Playback and delete the journal.  Drop the database write
46713       ** lock and reacquire the read lock. Purge the cache before
46714       ** playing back the hot-journal so that we don't end up with
46715       ** an inconsistent cache.  Sync the hot journal before playing
46716       ** it back since the process that crashed and left the hot journal
46717       ** probably did not sync it and we are required to always sync
46718       ** the journal before playing it back.
46719       */
46720       if( isOpen(pPager->jfd) ){
46721         assert( rc==SQLITE_OK );
46722         rc = pagerSyncHotJournal(pPager);
46723         if( rc==SQLITE_OK ){
46724           rc = pager_playback(pPager, 1);
46725           pPager->eState = PAGER_OPEN;
46726         }
46727       }else if( !pPager->exclusiveMode ){
46728         pagerUnlockDb(pPager, SHARED_LOCK);
46729       }
46730 
46731       if( rc!=SQLITE_OK ){
46732         /* This branch is taken if an error occurs while trying to open
46733         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
46734         ** pager_unlock() routine will be called before returning to unlock
46735         ** the file. If the unlock attempt fails, then Pager.eLock must be
46736         ** set to UNKNOWN_LOCK (see the comment above the #define for
46737         ** UNKNOWN_LOCK above for an explanation).
46738         **
46739         ** In order to get pager_unlock() to do this, set Pager.eState to
46740         ** PAGER_ERROR now. This is not actually counted as a transition
46741         ** to ERROR state in the state diagram at the top of this file,
46742         ** since we know that the same call to pager_unlock() will very
46743         ** shortly transition the pager object to the OPEN state. Calling
46744         ** assert_pager_state() would fail now, as it should not be possible
46745         ** to be in ERROR state when there are zero outstanding page
46746         ** references.
46747         */
46748         pager_error(pPager, rc);
46749         goto failed;
46750       }
46751 
46752       assert( pPager->eState==PAGER_OPEN );
46753       assert( (pPager->eLock==SHARED_LOCK)
46754            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
46755       );
46756     }
46757 
46758     if( !pPager->tempFile && pPager->hasBeenUsed ){
46759       /* The shared-lock has just been acquired then check to
46760       ** see if the database has been modified.  If the database has changed,
46761       ** flush the cache.  The pPager->hasBeenUsed flag prevents this from
46762       ** occurring on the very first access to a file, in order to save a
46763       ** single unnecessary sqlite3OsRead() call at the start-up.
46764       **
46765       ** Database changes is detected by looking at 15 bytes beginning
46766       ** at offset 24 into the file.  The first 4 of these 16 bytes are
46767       ** a 32-bit counter that is incremented with each change.  The
46768       ** other bytes change randomly with each file change when
46769       ** a codec is in use.
46770       **
46771       ** There is a vanishingly small chance that a change will not be
46772       ** detected.  The chance of an undetected change is so small that
46773       ** it can be neglected.
46774       */
46775       Pgno nPage = 0;
46776       char dbFileVers[sizeof(pPager->dbFileVers)];
46777 
46778       rc = pagerPagecount(pPager, &nPage);
46779       if( rc ) goto failed;
46780 
46781       if( nPage>0 ){
46782         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
46783         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
46784         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
46785           goto failed;
46786         }
46787       }else{
46788         memset(dbFileVers, 0, sizeof(dbFileVers));
46789       }
46790 
46791       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
46792         pager_reset(pPager);
46793 
46794         /* Unmap the database file. It is possible that external processes
46795         ** may have truncated the database file and then extended it back
46796         ** to its original size while this process was not holding a lock.
46797         ** In this case there may exist a Pager.pMap mapping that appears
46798         ** to be the right size but is not actually valid. Avoid this
46799         ** possibility by unmapping the db here. */
46800         if( USEFETCH(pPager) ){
46801           sqlite3OsUnfetch(pPager->fd, 0, 0);
46802         }
46803       }
46804     }
46805 
46806     /* If there is a WAL file in the file-system, open this database in WAL
46807     ** mode. Otherwise, the following function call is a no-op.
46808     */
46809     rc = pagerOpenWalIfPresent(pPager);
46810 #ifndef SQLITE_OMIT_WAL
46811     assert( pPager->pWal==0 || rc==SQLITE_OK );
46812 #endif
46813   }
46814 
46815   if( pagerUseWal(pPager) ){
46816     assert( rc==SQLITE_OK );
46817     rc = pagerBeginReadTransaction(pPager);
46818   }
46819 
46820   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
46821     rc = pagerPagecount(pPager, &pPager->dbSize);
46822   }
46823 
46824  failed:
46825   if( rc!=SQLITE_OK ){
46826     assert( !MEMDB );
46827     pager_unlock(pPager);
46828     assert( pPager->eState==PAGER_OPEN );
46829   }else{
46830     pPager->eState = PAGER_READER;
46831   }
46832   return rc;
46833 }
46834 
46835 /*
46836 ** If the reference count has reached zero, rollback any active
46837 ** transaction and unlock the pager.
46838 **
46839 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
46840 ** the rollback journal, the unlock is not performed and there is
46841 ** nothing to rollback, so this routine is a no-op.
46842 */
46843 static void pagerUnlockIfUnused(Pager *pPager){
46844   if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
46845     pagerUnlockAndRollback(pPager);
46846   }
46847 }
46848 
46849 /*
46850 ** Acquire a reference to page number pgno in pager pPager (a page
46851 ** reference has type DbPage*). If the requested reference is
46852 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
46853 **
46854 ** If the requested page is already in the cache, it is returned.
46855 ** Otherwise, a new page object is allocated and populated with data
46856 ** read from the database file. In some cases, the pcache module may
46857 ** choose not to allocate a new page object and may reuse an existing
46858 ** object with no outstanding references.
46859 **
46860 ** The extra data appended to a page is always initialized to zeros the
46861 ** first time a page is loaded into memory. If the page requested is
46862 ** already in the cache when this function is called, then the extra
46863 ** data is left as it was when the page object was last used.
46864 **
46865 ** If the database image is smaller than the requested page or if a
46866 ** non-zero value is passed as the noContent parameter and the
46867 ** requested page is not already stored in the cache, then no
46868 ** actual disk read occurs. In this case the memory image of the
46869 ** page is initialized to all zeros.
46870 **
46871 ** If noContent is true, it means that we do not care about the contents
46872 ** of the page. This occurs in two scenarios:
46873 **
46874 **   a) When reading a free-list leaf page from the database, and
46875 **
46876 **   b) When a savepoint is being rolled back and we need to load
46877 **      a new page into the cache to be filled with the data read
46878 **      from the savepoint journal.
46879 **
46880 ** If noContent is true, then the data returned is zeroed instead of
46881 ** being read from the database. Additionally, the bits corresponding
46882 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
46883 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
46884 ** savepoints are set. This means if the page is made writable at any
46885 ** point in the future, using a call to sqlite3PagerWrite(), its contents
46886 ** will not be journaled. This saves IO.
46887 **
46888 ** The acquisition might fail for several reasons.  In all cases,
46889 ** an appropriate error code is returned and *ppPage is set to NULL.
46890 **
46891 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
46892 ** to find a page in the in-memory cache first.  If the page is not already
46893 ** in memory, this routine goes to disk to read it in whereas Lookup()
46894 ** just returns 0.  This routine acquires a read-lock the first time it
46895 ** has to go to disk, and could also playback an old journal if necessary.
46896 ** Since Lookup() never goes to disk, it never has to deal with locks
46897 ** or journal files.
46898 */
46899 SQLITE_PRIVATE int sqlite3PagerAcquire(
46900   Pager *pPager,      /* The pager open on the database file */
46901   Pgno pgno,          /* Page number to fetch */
46902   DbPage **ppPage,    /* Write a pointer to the page here */
46903   int flags           /* PAGER_GET_XXX flags */
46904 ){
46905   int rc = SQLITE_OK;
46906   PgHdr *pPg = 0;
46907   u32 iFrame = 0;                 /* Frame to read from WAL file */
46908   const int noContent = (flags & PAGER_GET_NOCONTENT);
46909 
46910   /* It is acceptable to use a read-only (mmap) page for any page except
46911   ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
46912   ** flag was specified by the caller. And so long as the db is not a
46913   ** temporary or in-memory database.  */
46914   const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
46915    && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
46916 #ifdef SQLITE_HAS_CODEC
46917    && pPager->xCodec==0
46918 #endif
46919   );
46920 
46921   assert( pPager->eState>=PAGER_READER );
46922   assert( assert_pager_state(pPager) );
46923   assert( noContent==0 || bMmapOk==0 );
46924 
46925   if( pgno==0 ){
46926     return SQLITE_CORRUPT_BKPT;
46927   }
46928   pPager->hasBeenUsed = 1;
46929 
46930   /* If the pager is in the error state, return an error immediately.
46931   ** Otherwise, request the page from the PCache layer. */
46932   if( pPager->errCode!=SQLITE_OK ){
46933     rc = pPager->errCode;
46934   }else{
46935     if( bMmapOk && pagerUseWal(pPager) ){
46936       rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
46937       if( rc!=SQLITE_OK ) goto pager_acquire_err;
46938     }
46939 
46940     if( bMmapOk && iFrame==0 ){
46941       void *pData = 0;
46942 
46943       rc = sqlite3OsFetch(pPager->fd,
46944           (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
46945       );
46946 
46947       if( rc==SQLITE_OK && pData ){
46948         if( pPager->eState>PAGER_READER ){
46949           pPg = sqlite3PagerLookup(pPager, pgno);
46950         }
46951         if( pPg==0 ){
46952           rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
46953         }else{
46954           sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
46955         }
46956         if( pPg ){
46957           assert( rc==SQLITE_OK );
46958           *ppPage = pPg;
46959           return SQLITE_OK;
46960         }
46961       }
46962       if( rc!=SQLITE_OK ){
46963         goto pager_acquire_err;
46964       }
46965     }
46966 
46967     {
46968       sqlite3_pcache_page *pBase;
46969       pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
46970       if( pBase==0 ){
46971         rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
46972         if( rc!=SQLITE_OK ) goto pager_acquire_err;
46973       }
46974       pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
46975       if( pPg==0 ) rc = SQLITE_NOMEM;
46976     }
46977   }
46978 
46979   if( rc!=SQLITE_OK ){
46980     /* Either the call to sqlite3PcacheFetch() returned an error or the
46981     ** pager was already in the error-state when this function was called.
46982     ** Set pPg to 0 and jump to the exception handler.  */
46983     pPg = 0;
46984     goto pager_acquire_err;
46985   }
46986   assert( (*ppPage)->pgno==pgno );
46987   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
46988 
46989   if( (*ppPage)->pPager && !noContent ){
46990     /* In this case the pcache already contains an initialized copy of
46991     ** the page. Return without further ado.  */
46992     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
46993     pPager->aStat[PAGER_STAT_HIT]++;
46994     return SQLITE_OK;
46995 
46996   }else{
46997     /* The pager cache has created a new page. Its content needs to
46998     ** be initialized.  */
46999 
47000     pPg = *ppPage;
47001     pPg->pPager = pPager;
47002 
47003     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
47004     ** number greater than this, or the unused locking-page, is requested. */
47005     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
47006       rc = SQLITE_CORRUPT_BKPT;
47007       goto pager_acquire_err;
47008     }
47009 
47010     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
47011       if( pgno>pPager->mxPgno ){
47012         rc = SQLITE_FULL;
47013         goto pager_acquire_err;
47014       }
47015       if( noContent ){
47016         /* Failure to set the bits in the InJournal bit-vectors is benign.
47017         ** It merely means that we might do some extra work to journal a
47018         ** page that does not need to be journaled.  Nevertheless, be sure
47019         ** to test the case where a malloc error occurs while trying to set
47020         ** a bit in a bit vector.
47021         */
47022         sqlite3BeginBenignMalloc();
47023         if( pgno<=pPager->dbOrigSize ){
47024           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
47025           testcase( rc==SQLITE_NOMEM );
47026         }
47027         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
47028         testcase( rc==SQLITE_NOMEM );
47029         sqlite3EndBenignMalloc();
47030       }
47031       memset(pPg->pData, 0, pPager->pageSize);
47032       IOTRACE(("ZERO %p %d\n", pPager, pgno));
47033     }else{
47034       if( pagerUseWal(pPager) && bMmapOk==0 ){
47035         rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
47036         if( rc!=SQLITE_OK ) goto pager_acquire_err;
47037       }
47038       assert( pPg->pPager==pPager );
47039       pPager->aStat[PAGER_STAT_MISS]++;
47040       rc = readDbPage(pPg, iFrame);
47041       if( rc!=SQLITE_OK ){
47042         goto pager_acquire_err;
47043       }
47044     }
47045     pager_set_pagehash(pPg);
47046   }
47047 
47048   return SQLITE_OK;
47049 
47050 pager_acquire_err:
47051   assert( rc!=SQLITE_OK );
47052   if( pPg ){
47053     sqlite3PcacheDrop(pPg);
47054   }
47055   pagerUnlockIfUnused(pPager);
47056 
47057   *ppPage = 0;
47058   return rc;
47059 }
47060 
47061 /*
47062 ** Acquire a page if it is already in the in-memory cache.  Do
47063 ** not read the page from disk.  Return a pointer to the page,
47064 ** or 0 if the page is not in cache.
47065 **
47066 ** See also sqlite3PagerGet().  The difference between this routine
47067 ** and sqlite3PagerGet() is that _get() will go to the disk and read
47068 ** in the page if the page is not already in cache.  This routine
47069 ** returns NULL if the page is not in cache or if a disk I/O error
47070 ** has ever happened.
47071 */
47072 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
47073   sqlite3_pcache_page *pPage;
47074   assert( pPager!=0 );
47075   assert( pgno!=0 );
47076   assert( pPager->pPCache!=0 );
47077   pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
47078   assert( pPage==0 || pPager->hasBeenUsed );
47079   return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
47080 }
47081 
47082 /*
47083 ** Release a page reference.
47084 **
47085 ** If the number of references to the page drop to zero, then the
47086 ** page is added to the LRU list.  When all references to all pages
47087 ** are released, a rollback occurs and the lock on the database is
47088 ** removed.
47089 */
47090 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
47091   Pager *pPager;
47092   assert( pPg!=0 );
47093   pPager = pPg->pPager;
47094   if( pPg->flags & PGHDR_MMAP ){
47095     pagerReleaseMapPage(pPg);
47096   }else{
47097     sqlite3PcacheRelease(pPg);
47098   }
47099   pagerUnlockIfUnused(pPager);
47100 }
47101 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
47102   if( pPg ) sqlite3PagerUnrefNotNull(pPg);
47103 }
47104 
47105 /*
47106 ** This function is called at the start of every write transaction.
47107 ** There must already be a RESERVED or EXCLUSIVE lock on the database
47108 ** file when this routine is called.
47109 **
47110 ** Open the journal file for pager pPager and write a journal header
47111 ** to the start of it. If there are active savepoints, open the sub-journal
47112 ** as well. This function is only used when the journal file is being
47113 ** opened to write a rollback log for a transaction. It is not used
47114 ** when opening a hot journal file to roll it back.
47115 **
47116 ** If the journal file is already open (as it may be in exclusive mode),
47117 ** then this function just writes a journal header to the start of the
47118 ** already open file.
47119 **
47120 ** Whether or not the journal file is opened by this function, the
47121 ** Pager.pInJournal bitvec structure is allocated.
47122 **
47123 ** Return SQLITE_OK if everything is successful. Otherwise, return
47124 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
47125 ** an IO error code if opening or writing the journal file fails.
47126 */
47127 static int pager_open_journal(Pager *pPager){
47128   int rc = SQLITE_OK;                        /* Return code */
47129   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
47130 
47131   assert( pPager->eState==PAGER_WRITER_LOCKED );
47132   assert( assert_pager_state(pPager) );
47133   assert( pPager->pInJournal==0 );
47134 
47135   /* If already in the error state, this function is a no-op.  But on
47136   ** the other hand, this routine is never called if we are already in
47137   ** an error state. */
47138   if( NEVER(pPager->errCode) ) return pPager->errCode;
47139 
47140   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
47141     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
47142     if( pPager->pInJournal==0 ){
47143       return SQLITE_NOMEM;
47144     }
47145 
47146     /* Open the journal file if it is not already open. */
47147     if( !isOpen(pPager->jfd) ){
47148       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
47149         sqlite3MemJournalOpen(pPager->jfd);
47150       }else{
47151         const int flags =                   /* VFS flags to open journal file */
47152           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
47153           (pPager->tempFile ?
47154             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
47155             (SQLITE_OPEN_MAIN_JOURNAL)
47156           );
47157 
47158         /* Verify that the database still has the same name as it did when
47159         ** it was originally opened. */
47160         rc = databaseIsUnmoved(pPager);
47161         if( rc==SQLITE_OK ){
47162 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
47163           rc = sqlite3JournalOpen(
47164               pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
47165           );
47166 #else
47167           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
47168 #endif
47169         }
47170       }
47171       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
47172     }
47173 
47174 
47175     /* Write the first journal header to the journal file and open
47176     ** the sub-journal if necessary.
47177     */
47178     if( rc==SQLITE_OK ){
47179       /* TODO: Check if all of these are really required. */
47180       pPager->nRec = 0;
47181       pPager->journalOff = 0;
47182       pPager->setMaster = 0;
47183       pPager->journalHdr = 0;
47184       rc = writeJournalHdr(pPager);
47185     }
47186   }
47187 
47188   if( rc!=SQLITE_OK ){
47189     sqlite3BitvecDestroy(pPager->pInJournal);
47190     pPager->pInJournal = 0;
47191   }else{
47192     assert( pPager->eState==PAGER_WRITER_LOCKED );
47193     pPager->eState = PAGER_WRITER_CACHEMOD;
47194   }
47195 
47196   return rc;
47197 }
47198 
47199 /*
47200 ** Begin a write-transaction on the specified pager object. If a
47201 ** write-transaction has already been opened, this function is a no-op.
47202 **
47203 ** If the exFlag argument is false, then acquire at least a RESERVED
47204 ** lock on the database file. If exFlag is true, then acquire at least
47205 ** an EXCLUSIVE lock. If such a lock is already held, no locking
47206 ** functions need be called.
47207 **
47208 ** If the subjInMemory argument is non-zero, then any sub-journal opened
47209 ** within this transaction will be opened as an in-memory file. This
47210 ** has no effect if the sub-journal is already opened (as it may be when
47211 ** running in exclusive mode) or if the transaction does not require a
47212 ** sub-journal. If the subjInMemory argument is zero, then any required
47213 ** sub-journal is implemented in-memory if pPager is an in-memory database,
47214 ** or using a temporary file otherwise.
47215 */
47216 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
47217   int rc = SQLITE_OK;
47218 
47219   if( pPager->errCode ) return pPager->errCode;
47220   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
47221   pPager->subjInMemory = (u8)subjInMemory;
47222 
47223   if( ALWAYS(pPager->eState==PAGER_READER) ){
47224     assert( pPager->pInJournal==0 );
47225 
47226     if( pagerUseWal(pPager) ){
47227       /* If the pager is configured to use locking_mode=exclusive, and an
47228       ** exclusive lock on the database is not already held, obtain it now.
47229       */
47230       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
47231         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
47232         if( rc!=SQLITE_OK ){
47233           return rc;
47234         }
47235         sqlite3WalExclusiveMode(pPager->pWal, 1);
47236       }
47237 
47238       /* Grab the write lock on the log file. If successful, upgrade to
47239       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
47240       ** The busy-handler is not invoked if another connection already
47241       ** holds the write-lock. If possible, the upper layer will call it.
47242       */
47243       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
47244     }else{
47245       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
47246       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
47247       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
47248       ** lock, but not when obtaining the RESERVED lock.
47249       */
47250       rc = pagerLockDb(pPager, RESERVED_LOCK);
47251       if( rc==SQLITE_OK && exFlag ){
47252         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
47253       }
47254     }
47255 
47256     if( rc==SQLITE_OK ){
47257       /* Change to WRITER_LOCKED state.
47258       **
47259       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
47260       ** when it has an open transaction, but never to DBMOD or FINISHED.
47261       ** This is because in those states the code to roll back savepoint
47262       ** transactions may copy data from the sub-journal into the database
47263       ** file as well as into the page cache. Which would be incorrect in
47264       ** WAL mode.
47265       */
47266       pPager->eState = PAGER_WRITER_LOCKED;
47267       pPager->dbHintSize = pPager->dbSize;
47268       pPager->dbFileSize = pPager->dbSize;
47269       pPager->dbOrigSize = pPager->dbSize;
47270       pPager->journalOff = 0;
47271     }
47272 
47273     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
47274     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
47275     assert( assert_pager_state(pPager) );
47276   }
47277 
47278   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
47279   return rc;
47280 }
47281 
47282 /*
47283 ** Mark a single data page as writeable. The page is written into the
47284 ** main journal or sub-journal as required. If the page is written into
47285 ** one of the journals, the corresponding bit is set in the
47286 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
47287 ** of any open savepoints as appropriate.
47288 */
47289 static int pager_write(PgHdr *pPg){
47290   Pager *pPager = pPg->pPager;
47291   int rc = SQLITE_OK;
47292   int inJournal;
47293 
47294   /* This routine is not called unless a write-transaction has already
47295   ** been started. The journal file may or may not be open at this point.
47296   ** It is never called in the ERROR state.
47297   */
47298   assert( pPager->eState==PAGER_WRITER_LOCKED
47299        || pPager->eState==PAGER_WRITER_CACHEMOD
47300        || pPager->eState==PAGER_WRITER_DBMOD
47301   );
47302   assert( assert_pager_state(pPager) );
47303   assert( pPager->errCode==0 );
47304   assert( pPager->readOnly==0 );
47305 
47306   CHECK_PAGE(pPg);
47307 
47308   /* The journal file needs to be opened. Higher level routines have already
47309   ** obtained the necessary locks to begin the write-transaction, but the
47310   ** rollback journal might not yet be open. Open it now if this is the case.
47311   **
47312   ** This is done before calling sqlite3PcacheMakeDirty() on the page.
47313   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
47314   ** an error might occur and the pager would end up in WRITER_LOCKED state
47315   ** with pages marked as dirty in the cache.
47316   */
47317   if( pPager->eState==PAGER_WRITER_LOCKED ){
47318     rc = pager_open_journal(pPager);
47319     if( rc!=SQLITE_OK ) return rc;
47320   }
47321   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
47322   assert( assert_pager_state(pPager) );
47323 
47324   /* Mark the page as dirty.  If the page has already been written
47325   ** to the journal then we can return right away.
47326   */
47327   sqlite3PcacheMakeDirty(pPg);
47328   inJournal = pageInJournal(pPager, pPg);
47329   if( inJournal && (pPager->nSavepoint==0 || !subjRequiresPage(pPg)) ){
47330     assert( !pagerUseWal(pPager) );
47331   }else{
47332 
47333     /* The transaction journal now exists and we have a RESERVED or an
47334     ** EXCLUSIVE lock on the main database file.  Write the current page to
47335     ** the transaction journal if it is not there already.
47336     */
47337     if( !inJournal && !pagerUseWal(pPager) ){
47338       assert( pagerUseWal(pPager)==0 );
47339       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
47340         u32 cksum;
47341         char *pData2;
47342         i64 iOff = pPager->journalOff;
47343 
47344         /* We should never write to the journal file the page that
47345         ** contains the database locks.  The following assert verifies
47346         ** that we do not. */
47347         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
47348 
47349         assert( pPager->journalHdr<=pPager->journalOff );
47350         CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
47351         cksum = pager_cksum(pPager, (u8*)pData2);
47352 
47353         /* Even if an IO or diskfull error occurs while journalling the
47354         ** page in the block above, set the need-sync flag for the page.
47355         ** Otherwise, when the transaction is rolled back, the logic in
47356         ** playback_one_page() will think that the page needs to be restored
47357         ** in the database file. And if an IO error occurs while doing so,
47358         ** then corruption may follow.
47359         */
47360         pPg->flags |= PGHDR_NEED_SYNC;
47361 
47362         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
47363         if( rc!=SQLITE_OK ) return rc;
47364         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
47365         if( rc!=SQLITE_OK ) return rc;
47366         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
47367         if( rc!=SQLITE_OK ) return rc;
47368 
47369         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
47370                  pPager->journalOff, pPager->pageSize));
47371         PAGER_INCR(sqlite3_pager_writej_count);
47372         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
47373              PAGERID(pPager), pPg->pgno,
47374              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
47375 
47376         pPager->journalOff += 8 + pPager->pageSize;
47377         pPager->nRec++;
47378         assert( pPager->pInJournal!=0 );
47379         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
47380         testcase( rc==SQLITE_NOMEM );
47381         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
47382         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
47383         if( rc!=SQLITE_OK ){
47384           assert( rc==SQLITE_NOMEM );
47385           return rc;
47386         }
47387       }else{
47388         if( pPager->eState!=PAGER_WRITER_DBMOD ){
47389           pPg->flags |= PGHDR_NEED_SYNC;
47390         }
47391         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
47392                 PAGERID(pPager), pPg->pgno,
47393                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
47394       }
47395     }
47396 
47397     /* If the statement journal is open and the page is not in it,
47398     ** then write the current page to the statement journal.  Note that
47399     ** the statement journal format differs from the standard journal format
47400     ** in that it omits the checksums and the header.
47401     */
47402     if( pPager->nSavepoint>0 && subjRequiresPage(pPg) ){
47403       rc = subjournalPage(pPg);
47404     }
47405   }
47406 
47407   /* Update the database size and return.
47408   */
47409   if( pPager->dbSize<pPg->pgno ){
47410     pPager->dbSize = pPg->pgno;
47411   }
47412   return rc;
47413 }
47414 
47415 /*
47416 ** This is a variant of sqlite3PagerWrite() that runs when the sector size
47417 ** is larger than the page size.  SQLite makes the (reasonable) assumption that
47418 ** all bytes of a sector are written together by hardware.  Hence, all bytes of
47419 ** a sector need to be journalled in case of a power loss in the middle of
47420 ** a write.
47421 **
47422 ** Usually, the sector size is less than or equal to the page size, in which
47423 ** case pages can be individually written.  This routine only runs in the exceptional
47424 ** case where the page size is smaller than the sector size.
47425 */
47426 static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
47427   int rc = SQLITE_OK;            /* Return code */
47428   Pgno nPageCount;               /* Total number of pages in database file */
47429   Pgno pg1;                      /* First page of the sector pPg is located on. */
47430   int nPage = 0;                 /* Number of pages starting at pg1 to journal */
47431   int ii;                        /* Loop counter */
47432   int needSync = 0;              /* True if any page has PGHDR_NEED_SYNC */
47433   Pager *pPager = pPg->pPager;   /* The pager that owns pPg */
47434   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
47435 
47436   /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
47437   ** a journal header to be written between the pages journaled by
47438   ** this function.
47439   */
47440   assert( !MEMDB );
47441   assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
47442   pPager->doNotSpill |= SPILLFLAG_NOSYNC;
47443 
47444   /* This trick assumes that both the page-size and sector-size are
47445   ** an integer power of 2. It sets variable pg1 to the identifier
47446   ** of the first page of the sector pPg is located on.
47447   */
47448   pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
47449 
47450   nPageCount = pPager->dbSize;
47451   if( pPg->pgno>nPageCount ){
47452     nPage = (pPg->pgno - pg1)+1;
47453   }else if( (pg1+nPagePerSector-1)>nPageCount ){
47454     nPage = nPageCount+1-pg1;
47455   }else{
47456     nPage = nPagePerSector;
47457   }
47458   assert(nPage>0);
47459   assert(pg1<=pPg->pgno);
47460   assert((pg1+nPage)>pPg->pgno);
47461 
47462   for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
47463     Pgno pg = pg1+ii;
47464     PgHdr *pPage;
47465     if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
47466       if( pg!=PAGER_MJ_PGNO(pPager) ){
47467         rc = sqlite3PagerGet(pPager, pg, &pPage);
47468         if( rc==SQLITE_OK ){
47469           rc = pager_write(pPage);
47470           if( pPage->flags&PGHDR_NEED_SYNC ){
47471             needSync = 1;
47472           }
47473           sqlite3PagerUnrefNotNull(pPage);
47474         }
47475       }
47476     }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
47477       if( pPage->flags&PGHDR_NEED_SYNC ){
47478         needSync = 1;
47479       }
47480       sqlite3PagerUnrefNotNull(pPage);
47481     }
47482   }
47483 
47484   /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
47485   ** starting at pg1, then it needs to be set for all of them. Because
47486   ** writing to any of these nPage pages may damage the others, the
47487   ** journal file must contain sync()ed copies of all of them
47488   ** before any of them can be written out to the database file.
47489   */
47490   if( rc==SQLITE_OK && needSync ){
47491     assert( !MEMDB );
47492     for(ii=0; ii<nPage; ii++){
47493       PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
47494       if( pPage ){
47495         pPage->flags |= PGHDR_NEED_SYNC;
47496         sqlite3PagerUnrefNotNull(pPage);
47497       }
47498     }
47499   }
47500 
47501   assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
47502   pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
47503   return rc;
47504 }
47505 
47506 /*
47507 ** Mark a data page as writeable. This routine must be called before
47508 ** making changes to a page. The caller must check the return value
47509 ** of this function and be careful not to change any page data unless
47510 ** this routine returns SQLITE_OK.
47511 **
47512 ** The difference between this function and pager_write() is that this
47513 ** function also deals with the special case where 2 or more pages
47514 ** fit on a single disk sector. In this case all co-resident pages
47515 ** must have been written to the journal file before returning.
47516 **
47517 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
47518 ** as appropriate. Otherwise, SQLITE_OK.
47519 */
47520 SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
47521   assert( (pPg->flags & PGHDR_MMAP)==0 );
47522   assert( pPg->pPager->eState>=PAGER_WRITER_LOCKED );
47523   assert( pPg->pPager->eState!=PAGER_ERROR );
47524   assert( assert_pager_state(pPg->pPager) );
47525   if( pPg->pPager->sectorSize > (u32)pPg->pPager->pageSize ){
47526     return pagerWriteLargeSector(pPg);
47527   }else{
47528     return pager_write(pPg);
47529   }
47530 }
47531 
47532 /*
47533 ** Return TRUE if the page given in the argument was previously passed
47534 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
47535 ** to change the content of the page.
47536 */
47537 #ifndef NDEBUG
47538 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
47539   return pPg->flags&PGHDR_DIRTY;
47540 }
47541 #endif
47542 
47543 /*
47544 ** A call to this routine tells the pager that it is not necessary to
47545 ** write the information on page pPg back to the disk, even though
47546 ** that page might be marked as dirty.  This happens, for example, when
47547 ** the page has been added as a leaf of the freelist and so its
47548 ** content no longer matters.
47549 **
47550 ** The overlying software layer calls this routine when all of the data
47551 ** on the given page is unused. The pager marks the page as clean so
47552 ** that it does not get written to disk.
47553 **
47554 ** Tests show that this optimization can quadruple the speed of large
47555 ** DELETE operations.
47556 */
47557 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
47558   Pager *pPager = pPg->pPager;
47559   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
47560     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
47561     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
47562     pPg->flags |= PGHDR_DONT_WRITE;
47563     pager_set_pagehash(pPg);
47564   }
47565 }
47566 
47567 /*
47568 ** This routine is called to increment the value of the database file
47569 ** change-counter, stored as a 4-byte big-endian integer starting at
47570 ** byte offset 24 of the pager file.  The secondary change counter at
47571 ** 92 is also updated, as is the SQLite version number at offset 96.
47572 **
47573 ** But this only happens if the pPager->changeCountDone flag is false.
47574 ** To avoid excess churning of page 1, the update only happens once.
47575 ** See also the pager_write_changecounter() routine that does an
47576 ** unconditional update of the change counters.
47577 **
47578 ** If the isDirectMode flag is zero, then this is done by calling
47579 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
47580 ** page data. In this case the file will be updated when the current
47581 ** transaction is committed.
47582 **
47583 ** The isDirectMode flag may only be non-zero if the library was compiled
47584 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
47585 ** if isDirect is non-zero, then the database file is updated directly
47586 ** by writing an updated version of page 1 using a call to the
47587 ** sqlite3OsWrite() function.
47588 */
47589 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
47590   int rc = SQLITE_OK;
47591 
47592   assert( pPager->eState==PAGER_WRITER_CACHEMOD
47593        || pPager->eState==PAGER_WRITER_DBMOD
47594   );
47595   assert( assert_pager_state(pPager) );
47596 
47597   /* Declare and initialize constant integer 'isDirect'. If the
47598   ** atomic-write optimization is enabled in this build, then isDirect
47599   ** is initialized to the value passed as the isDirectMode parameter
47600   ** to this function. Otherwise, it is always set to zero.
47601   **
47602   ** The idea is that if the atomic-write optimization is not
47603   ** enabled at compile time, the compiler can omit the tests of
47604   ** 'isDirect' below, as well as the block enclosed in the
47605   ** "if( isDirect )" condition.
47606   */
47607 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
47608 # define DIRECT_MODE 0
47609   assert( isDirectMode==0 );
47610   UNUSED_PARAMETER(isDirectMode);
47611 #else
47612 # define DIRECT_MODE isDirectMode
47613 #endif
47614 
47615   if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
47616     PgHdr *pPgHdr;                /* Reference to page 1 */
47617 
47618     assert( !pPager->tempFile && isOpen(pPager->fd) );
47619 
47620     /* Open page 1 of the file for writing. */
47621     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
47622     assert( pPgHdr==0 || rc==SQLITE_OK );
47623 
47624     /* If page one was fetched successfully, and this function is not
47625     ** operating in direct-mode, make page 1 writable.  When not in
47626     ** direct mode, page 1 is always held in cache and hence the PagerGet()
47627     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
47628     */
47629     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
47630       rc = sqlite3PagerWrite(pPgHdr);
47631     }
47632 
47633     if( rc==SQLITE_OK ){
47634       /* Actually do the update of the change counter */
47635       pager_write_changecounter(pPgHdr);
47636 
47637       /* If running in direct mode, write the contents of page 1 to the file. */
47638       if( DIRECT_MODE ){
47639         const void *zBuf;
47640         assert( pPager->dbFileSize>0 );
47641         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
47642         if( rc==SQLITE_OK ){
47643           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
47644           pPager->aStat[PAGER_STAT_WRITE]++;
47645         }
47646         if( rc==SQLITE_OK ){
47647           /* Update the pager's copy of the change-counter. Otherwise, the
47648           ** next time a read transaction is opened the cache will be
47649           ** flushed (as the change-counter values will not match).  */
47650           const void *pCopy = (const void *)&((const char *)zBuf)[24];
47651           memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
47652           pPager->changeCountDone = 1;
47653         }
47654       }else{
47655         pPager->changeCountDone = 1;
47656       }
47657     }
47658 
47659     /* Release the page reference. */
47660     sqlite3PagerUnref(pPgHdr);
47661   }
47662   return rc;
47663 }
47664 
47665 /*
47666 ** Sync the database file to disk. This is a no-op for in-memory databases
47667 ** or pages with the Pager.noSync flag set.
47668 **
47669 ** If successful, or if called on a pager for which it is a no-op, this
47670 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
47671 */
47672 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
47673   int rc = SQLITE_OK;
47674 
47675   if( isOpen(pPager->fd) ){
47676     void *pArg = (void*)zMaster;
47677     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
47678     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
47679   }
47680   if( rc==SQLITE_OK && !pPager->noSync ){
47681     assert( !MEMDB );
47682     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
47683   }
47684   return rc;
47685 }
47686 
47687 /*
47688 ** This function may only be called while a write-transaction is active in
47689 ** rollback. If the connection is in WAL mode, this call is a no-op.
47690 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
47691 ** the database file, an attempt is made to obtain one.
47692 **
47693 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
47694 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
47695 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
47696 ** returned.
47697 */
47698 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
47699   int rc = SQLITE_OK;
47700   assert( pPager->eState==PAGER_WRITER_CACHEMOD
47701        || pPager->eState==PAGER_WRITER_DBMOD
47702        || pPager->eState==PAGER_WRITER_LOCKED
47703   );
47704   assert( assert_pager_state(pPager) );
47705   if( 0==pagerUseWal(pPager) ){
47706     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
47707   }
47708   return rc;
47709 }
47710 
47711 /*
47712 ** Sync the database file for the pager pPager. zMaster points to the name
47713 ** of a master journal file that should be written into the individual
47714 ** journal file. zMaster may be NULL, which is interpreted as no master
47715 ** journal (a single database transaction).
47716 **
47717 ** This routine ensures that:
47718 **
47719 **   * The database file change-counter is updated,
47720 **   * the journal is synced (unless the atomic-write optimization is used),
47721 **   * all dirty pages are written to the database file,
47722 **   * the database file is truncated (if required), and
47723 **   * the database file synced.
47724 **
47725 ** The only thing that remains to commit the transaction is to finalize
47726 ** (delete, truncate or zero the first part of) the journal file (or
47727 ** delete the master journal file if specified).
47728 **
47729 ** Note that if zMaster==NULL, this does not overwrite a previous value
47730 ** passed to an sqlite3PagerCommitPhaseOne() call.
47731 **
47732 ** If the final parameter - noSync - is true, then the database file itself
47733 ** is not synced. The caller must call sqlite3PagerSync() directly to
47734 ** sync the database file before calling CommitPhaseTwo() to delete the
47735 ** journal file in this case.
47736 */
47737 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
47738   Pager *pPager,                  /* Pager object */
47739   const char *zMaster,            /* If not NULL, the master journal name */
47740   int noSync                      /* True to omit the xSync on the db file */
47741 ){
47742   int rc = SQLITE_OK;             /* Return code */
47743 
47744   assert( pPager->eState==PAGER_WRITER_LOCKED
47745        || pPager->eState==PAGER_WRITER_CACHEMOD
47746        || pPager->eState==PAGER_WRITER_DBMOD
47747        || pPager->eState==PAGER_ERROR
47748   );
47749   assert( assert_pager_state(pPager) );
47750 
47751   /* If a prior error occurred, report that error again. */
47752   if( NEVER(pPager->errCode) ) return pPager->errCode;
47753 
47754   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
47755       pPager->zFilename, zMaster, pPager->dbSize));
47756 
47757   /* If no database changes have been made, return early. */
47758   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
47759 
47760   if( MEMDB ){
47761     /* If this is an in-memory db, or no pages have been written to, or this
47762     ** function has already been called, it is mostly a no-op.  However, any
47763     ** backup in progress needs to be restarted.
47764     */
47765     sqlite3BackupRestart(pPager->pBackup);
47766   }else{
47767     if( pagerUseWal(pPager) ){
47768       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
47769       PgHdr *pPageOne = 0;
47770       if( pList==0 ){
47771         /* Must have at least one page for the WAL commit flag.
47772         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
47773         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
47774         pList = pPageOne;
47775         pList->pDirty = 0;
47776       }
47777       assert( rc==SQLITE_OK );
47778       if( ALWAYS(pList) ){
47779         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
47780       }
47781       sqlite3PagerUnref(pPageOne);
47782       if( rc==SQLITE_OK ){
47783         sqlite3PcacheCleanAll(pPager->pPCache);
47784       }
47785     }else{
47786       /* The following block updates the change-counter. Exactly how it
47787       ** does this depends on whether or not the atomic-update optimization
47788       ** was enabled at compile time, and if this transaction meets the
47789       ** runtime criteria to use the operation:
47790       **
47791       **    * The file-system supports the atomic-write property for
47792       **      blocks of size page-size, and
47793       **    * This commit is not part of a multi-file transaction, and
47794       **    * Exactly one page has been modified and store in the journal file.
47795       **
47796       ** If the optimization was not enabled at compile time, then the
47797       ** pager_incr_changecounter() function is called to update the change
47798       ** counter in 'indirect-mode'. If the optimization is compiled in but
47799       ** is not applicable to this transaction, call sqlite3JournalCreate()
47800       ** to make sure the journal file has actually been created, then call
47801       ** pager_incr_changecounter() to update the change-counter in indirect
47802       ** mode.
47803       **
47804       ** Otherwise, if the optimization is both enabled and applicable,
47805       ** then call pager_incr_changecounter() to update the change-counter
47806       ** in 'direct' mode. In this case the journal file will never be
47807       ** created for this transaction.
47808       */
47809   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
47810       PgHdr *pPg;
47811       assert( isOpen(pPager->jfd)
47812            || pPager->journalMode==PAGER_JOURNALMODE_OFF
47813            || pPager->journalMode==PAGER_JOURNALMODE_WAL
47814       );
47815       if( !zMaster && isOpen(pPager->jfd)
47816        && pPager->journalOff==jrnlBufferSize(pPager)
47817        && pPager->dbSize>=pPager->dbOrigSize
47818        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
47819       ){
47820         /* Update the db file change counter via the direct-write method. The
47821         ** following call will modify the in-memory representation of page 1
47822         ** to include the updated change counter and then write page 1
47823         ** directly to the database file. Because of the atomic-write
47824         ** property of the host file-system, this is safe.
47825         */
47826         rc = pager_incr_changecounter(pPager, 1);
47827       }else{
47828         rc = sqlite3JournalCreate(pPager->jfd);
47829         if( rc==SQLITE_OK ){
47830           rc = pager_incr_changecounter(pPager, 0);
47831         }
47832       }
47833   #else
47834       rc = pager_incr_changecounter(pPager, 0);
47835   #endif
47836       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47837 
47838       /* Write the master journal name into the journal file. If a master
47839       ** journal file name has already been written to the journal file,
47840       ** or if zMaster is NULL (no master journal), then this call is a no-op.
47841       */
47842       rc = writeMasterJournal(pPager, zMaster);
47843       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47844 
47845       /* Sync the journal file and write all dirty pages to the database.
47846       ** If the atomic-update optimization is being used, this sync will not
47847       ** create the journal file or perform any real IO.
47848       **
47849       ** Because the change-counter page was just modified, unless the
47850       ** atomic-update optimization is used it is almost certain that the
47851       ** journal requires a sync here. However, in locking_mode=exclusive
47852       ** on a system under memory pressure it is just possible that this is
47853       ** not the case. In this case it is likely enough that the redundant
47854       ** xSync() call will be changed to a no-op by the OS anyhow.
47855       */
47856       rc = syncJournal(pPager, 0);
47857       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47858 
47859       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
47860       if( rc!=SQLITE_OK ){
47861         assert( rc!=SQLITE_IOERR_BLOCKED );
47862         goto commit_phase_one_exit;
47863       }
47864       sqlite3PcacheCleanAll(pPager->pPCache);
47865 
47866       /* If the file on disk is smaller than the database image, use
47867       ** pager_truncate to grow the file here. This can happen if the database
47868       ** image was extended as part of the current transaction and then the
47869       ** last page in the db image moved to the free-list. In this case the
47870       ** last page is never written out to disk, leaving the database file
47871       ** undersized. Fix this now if it is the case.  */
47872       if( pPager->dbSize>pPager->dbFileSize ){
47873         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
47874         assert( pPager->eState==PAGER_WRITER_DBMOD );
47875         rc = pager_truncate(pPager, nNew);
47876         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47877       }
47878 
47879       /* Finally, sync the database file. */
47880       if( !noSync ){
47881         rc = sqlite3PagerSync(pPager, zMaster);
47882       }
47883       IOTRACE(("DBSYNC %p\n", pPager))
47884     }
47885   }
47886 
47887 commit_phase_one_exit:
47888   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
47889     pPager->eState = PAGER_WRITER_FINISHED;
47890   }
47891   return rc;
47892 }
47893 
47894 
47895 /*
47896 ** When this function is called, the database file has been completely
47897 ** updated to reflect the changes made by the current transaction and
47898 ** synced to disk. The journal file still exists in the file-system
47899 ** though, and if a failure occurs at this point it will eventually
47900 ** be used as a hot-journal and the current transaction rolled back.
47901 **
47902 ** This function finalizes the journal file, either by deleting,
47903 ** truncating or partially zeroing it, so that it cannot be used
47904 ** for hot-journal rollback. Once this is done the transaction is
47905 ** irrevocably committed.
47906 **
47907 ** If an error occurs, an IO error code is returned and the pager
47908 ** moves into the error state. Otherwise, SQLITE_OK is returned.
47909 */
47910 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
47911   int rc = SQLITE_OK;                  /* Return code */
47912 
47913   /* This routine should not be called if a prior error has occurred.
47914   ** But if (due to a coding error elsewhere in the system) it does get
47915   ** called, just return the same error code without doing anything. */
47916   if( NEVER(pPager->errCode) ) return pPager->errCode;
47917 
47918   assert( pPager->eState==PAGER_WRITER_LOCKED
47919        || pPager->eState==PAGER_WRITER_FINISHED
47920        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
47921   );
47922   assert( assert_pager_state(pPager) );
47923 
47924   /* An optimization. If the database was not actually modified during
47925   ** this transaction, the pager is running in exclusive-mode and is
47926   ** using persistent journals, then this function is a no-op.
47927   **
47928   ** The start of the journal file currently contains a single journal
47929   ** header with the nRec field set to 0. If such a journal is used as
47930   ** a hot-journal during hot-journal rollback, 0 changes will be made
47931   ** to the database file. So there is no need to zero the journal
47932   ** header. Since the pager is in exclusive mode, there is no need
47933   ** to drop any locks either.
47934   */
47935   if( pPager->eState==PAGER_WRITER_LOCKED
47936    && pPager->exclusiveMode
47937    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
47938   ){
47939     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
47940     pPager->eState = PAGER_READER;
47941     return SQLITE_OK;
47942   }
47943 
47944   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
47945   pPager->iDataVersion++;
47946   rc = pager_end_transaction(pPager, pPager->setMaster, 1);
47947   return pager_error(pPager, rc);
47948 }
47949 
47950 /*
47951 ** If a write transaction is open, then all changes made within the
47952 ** transaction are reverted and the current write-transaction is closed.
47953 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
47954 ** state if an error occurs.
47955 **
47956 ** If the pager is already in PAGER_ERROR state when this function is called,
47957 ** it returns Pager.errCode immediately. No work is performed in this case.
47958 **
47959 ** Otherwise, in rollback mode, this function performs two functions:
47960 **
47961 **   1) It rolls back the journal file, restoring all database file and
47962 **      in-memory cache pages to the state they were in when the transaction
47963 **      was opened, and
47964 **
47965 **   2) It finalizes the journal file, so that it is not used for hot
47966 **      rollback at any point in the future.
47967 **
47968 ** Finalization of the journal file (task 2) is only performed if the
47969 ** rollback is successful.
47970 **
47971 ** In WAL mode, all cache-entries containing data modified within the
47972 ** current transaction are either expelled from the cache or reverted to
47973 ** their pre-transaction state by re-reading data from the database or
47974 ** WAL files. The WAL transaction is then closed.
47975 */
47976 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
47977   int rc = SQLITE_OK;                  /* Return code */
47978   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
47979 
47980   /* PagerRollback() is a no-op if called in READER or OPEN state. If
47981   ** the pager is already in the ERROR state, the rollback is not
47982   ** attempted here. Instead, the error code is returned to the caller.
47983   */
47984   assert( assert_pager_state(pPager) );
47985   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
47986   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
47987 
47988   if( pagerUseWal(pPager) ){
47989     int rc2;
47990     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
47991     rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
47992     if( rc==SQLITE_OK ) rc = rc2;
47993   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
47994     int eState = pPager->eState;
47995     rc = pager_end_transaction(pPager, 0, 0);
47996     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
47997       /* This can happen using journal_mode=off. Move the pager to the error
47998       ** state to indicate that the contents of the cache may not be trusted.
47999       ** Any active readers will get SQLITE_ABORT.
48000       */
48001       pPager->errCode = SQLITE_ABORT;
48002       pPager->eState = PAGER_ERROR;
48003       return rc;
48004     }
48005   }else{
48006     rc = pager_playback(pPager, 0);
48007   }
48008 
48009   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
48010   assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
48011           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
48012           || rc==SQLITE_CANTOPEN
48013   );
48014 
48015   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
48016   ** cache. So call pager_error() on the way out to make any error persistent.
48017   */
48018   return pager_error(pPager, rc);
48019 }
48020 
48021 /*
48022 ** Return TRUE if the database file is opened read-only.  Return FALSE
48023 ** if the database is (in theory) writable.
48024 */
48025 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
48026   return pPager->readOnly;
48027 }
48028 
48029 /*
48030 ** Return the number of references to the pager.
48031 */
48032 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
48033   return sqlite3PcacheRefCount(pPager->pPCache);
48034 }
48035 
48036 /*
48037 ** Return the approximate number of bytes of memory currently
48038 ** used by the pager and its associated cache.
48039 */
48040 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
48041   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
48042                                      + 5*sizeof(void*);
48043   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
48044            + sqlite3MallocSize(pPager)
48045            + pPager->pageSize;
48046 }
48047 
48048 /*
48049 ** Return the number of references to the specified page.
48050 */
48051 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
48052   return sqlite3PcachePageRefcount(pPage);
48053 }
48054 
48055 #ifdef SQLITE_TEST
48056 /*
48057 ** This routine is used for testing and analysis only.
48058 */
48059 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
48060   static int a[11];
48061   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
48062   a[1] = sqlite3PcachePagecount(pPager->pPCache);
48063   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
48064   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
48065   a[4] = pPager->eState;
48066   a[5] = pPager->errCode;
48067   a[6] = pPager->aStat[PAGER_STAT_HIT];
48068   a[7] = pPager->aStat[PAGER_STAT_MISS];
48069   a[8] = 0;  /* Used to be pPager->nOvfl */
48070   a[9] = pPager->nRead;
48071   a[10] = pPager->aStat[PAGER_STAT_WRITE];
48072   return a;
48073 }
48074 #endif
48075 
48076 /*
48077 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
48078 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
48079 ** current cache hit or miss count, according to the value of eStat. If the
48080 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
48081 ** returning.
48082 */
48083 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
48084 
48085   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
48086        || eStat==SQLITE_DBSTATUS_CACHE_MISS
48087        || eStat==SQLITE_DBSTATUS_CACHE_WRITE
48088   );
48089 
48090   assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
48091   assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
48092   assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
48093 
48094   *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
48095   if( reset ){
48096     pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
48097   }
48098 }
48099 
48100 /*
48101 ** Return true if this is an in-memory pager.
48102 */
48103 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
48104   return MEMDB;
48105 }
48106 
48107 /*
48108 ** Check that there are at least nSavepoint savepoints open. If there are
48109 ** currently less than nSavepoints open, then open one or more savepoints
48110 ** to make up the difference. If the number of savepoints is already
48111 ** equal to nSavepoint, then this function is a no-op.
48112 **
48113 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
48114 ** occurs while opening the sub-journal file, then an IO error code is
48115 ** returned. Otherwise, SQLITE_OK.
48116 */
48117 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
48118   int rc = SQLITE_OK;                       /* Return code */
48119   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
48120 
48121   assert( pPager->eState>=PAGER_WRITER_LOCKED );
48122   assert( assert_pager_state(pPager) );
48123 
48124   if( nSavepoint>nCurrent && pPager->useJournal ){
48125     int ii;                                 /* Iterator variable */
48126     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
48127 
48128     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
48129     ** if the allocation fails. Otherwise, zero the new portion in case a
48130     ** malloc failure occurs while populating it in the for(...) loop below.
48131     */
48132     aNew = (PagerSavepoint *)sqlite3Realloc(
48133         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
48134     );
48135     if( !aNew ){
48136       return SQLITE_NOMEM;
48137     }
48138     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
48139     pPager->aSavepoint = aNew;
48140 
48141     /* Populate the PagerSavepoint structures just allocated. */
48142     for(ii=nCurrent; ii<nSavepoint; ii++){
48143       aNew[ii].nOrig = pPager->dbSize;
48144       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
48145         aNew[ii].iOffset = pPager->journalOff;
48146       }else{
48147         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
48148       }
48149       aNew[ii].iSubRec = pPager->nSubRec;
48150       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
48151       if( !aNew[ii].pInSavepoint ){
48152         return SQLITE_NOMEM;
48153       }
48154       if( pagerUseWal(pPager) ){
48155         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
48156       }
48157       pPager->nSavepoint = ii+1;
48158     }
48159     assert( pPager->nSavepoint==nSavepoint );
48160     assertTruncateConstraint(pPager);
48161   }
48162 
48163   return rc;
48164 }
48165 
48166 /*
48167 ** This function is called to rollback or release (commit) a savepoint.
48168 ** The savepoint to release or rollback need not be the most recently
48169 ** created savepoint.
48170 **
48171 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
48172 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
48173 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
48174 ** that have occurred since the specified savepoint was created.
48175 **
48176 ** The savepoint to rollback or release is identified by parameter
48177 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
48178 ** (the first created). A value of (Pager.nSavepoint-1) means operate
48179 ** on the most recently created savepoint. If iSavepoint is greater than
48180 ** (Pager.nSavepoint-1), then this function is a no-op.
48181 **
48182 ** If a negative value is passed to this function, then the current
48183 ** transaction is rolled back. This is different to calling
48184 ** sqlite3PagerRollback() because this function does not terminate
48185 ** the transaction or unlock the database, it just restores the
48186 ** contents of the database to its original state.
48187 **
48188 ** In any case, all savepoints with an index greater than iSavepoint
48189 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
48190 ** then savepoint iSavepoint is also destroyed.
48191 **
48192 ** This function may return SQLITE_NOMEM if a memory allocation fails,
48193 ** or an IO error code if an IO error occurs while rolling back a
48194 ** savepoint. If no errors occur, SQLITE_OK is returned.
48195 */
48196 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
48197   int rc = pPager->errCode;       /* Return code */
48198 
48199   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
48200   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
48201 
48202   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
48203     int ii;            /* Iterator variable */
48204     int nNew;          /* Number of remaining savepoints after this op. */
48205 
48206     /* Figure out how many savepoints will still be active after this
48207     ** operation. Store this value in nNew. Then free resources associated
48208     ** with any savepoints that are destroyed by this operation.
48209     */
48210     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
48211     for(ii=nNew; ii<pPager->nSavepoint; ii++){
48212       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
48213     }
48214     pPager->nSavepoint = nNew;
48215 
48216     /* If this is a release of the outermost savepoint, truncate
48217     ** the sub-journal to zero bytes in size. */
48218     if( op==SAVEPOINT_RELEASE ){
48219       if( nNew==0 && isOpen(pPager->sjfd) ){
48220         /* Only truncate if it is an in-memory sub-journal. */
48221         if( sqlite3IsMemJournal(pPager->sjfd) ){
48222           rc = sqlite3OsTruncate(pPager->sjfd, 0);
48223           assert( rc==SQLITE_OK );
48224         }
48225         pPager->nSubRec = 0;
48226       }
48227     }
48228     /* Else this is a rollback operation, playback the specified savepoint.
48229     ** If this is a temp-file, it is possible that the journal file has
48230     ** not yet been opened. In this case there have been no changes to
48231     ** the database file, so the playback operation can be skipped.
48232     */
48233     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
48234       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
48235       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
48236       assert(rc!=SQLITE_DONE);
48237     }
48238   }
48239 
48240   return rc;
48241 }
48242 
48243 /*
48244 ** Return the full pathname of the database file.
48245 **
48246 ** Except, if the pager is in-memory only, then return an empty string if
48247 ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
48248 ** used to report the filename to the user, for compatibility with legacy
48249 ** behavior.  But when the Btree needs to know the filename for matching to
48250 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
48251 ** participate in shared-cache.
48252 */
48253 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
48254   return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
48255 }
48256 
48257 /*
48258 ** Return the VFS structure for the pager.
48259 */
48260 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
48261   return pPager->pVfs;
48262 }
48263 
48264 /*
48265 ** Return the file handle for the database file associated
48266 ** with the pager.  This might return NULL if the file has
48267 ** not yet been opened.
48268 */
48269 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
48270   return pPager->fd;
48271 }
48272 
48273 /*
48274 ** Return the full pathname of the journal file.
48275 */
48276 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
48277   return pPager->zJournal;
48278 }
48279 
48280 /*
48281 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
48282 ** if fsync()s are executed normally.
48283 */
48284 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
48285   return pPager->noSync;
48286 }
48287 
48288 #ifdef SQLITE_HAS_CODEC
48289 /*
48290 ** Set or retrieve the codec for this pager
48291 */
48292 SQLITE_PRIVATE void sqlite3PagerSetCodec(
48293   Pager *pPager,
48294   void *(*xCodec)(void*,void*,Pgno,int),
48295   void (*xCodecSizeChng)(void*,int,int),
48296   void (*xCodecFree)(void*),
48297   void *pCodec
48298 ){
48299   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
48300   pPager->xCodec = pPager->memDb ? 0 : xCodec;
48301   pPager->xCodecSizeChng = xCodecSizeChng;
48302   pPager->xCodecFree = xCodecFree;
48303   pPager->pCodec = pCodec;
48304   pagerReportSize(pPager);
48305 }
48306 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
48307   return pPager->pCodec;
48308 }
48309 
48310 /*
48311 ** This function is called by the wal module when writing page content
48312 ** into the log file.
48313 **
48314 ** This function returns a pointer to a buffer containing the encrypted
48315 ** page content. If a malloc fails, this function may return NULL.
48316 */
48317 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
48318   void *aData = 0;
48319   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
48320   return aData;
48321 }
48322 
48323 /*
48324 ** Return the current pager state
48325 */
48326 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
48327   return pPager->eState;
48328 }
48329 #endif /* SQLITE_HAS_CODEC */
48330 
48331 #ifndef SQLITE_OMIT_AUTOVACUUM
48332 /*
48333 ** Move the page pPg to location pgno in the file.
48334 **
48335 ** There must be no references to the page previously located at
48336 ** pgno (which we call pPgOld) though that page is allowed to be
48337 ** in cache.  If the page previously located at pgno is not already
48338 ** in the rollback journal, it is not put there by by this routine.
48339 **
48340 ** References to the page pPg remain valid. Updating any
48341 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
48342 ** allocated along with the page) is the responsibility of the caller.
48343 **
48344 ** A transaction must be active when this routine is called. It used to be
48345 ** required that a statement transaction was not active, but this restriction
48346 ** has been removed (CREATE INDEX needs to move a page when a statement
48347 ** transaction is active).
48348 **
48349 ** If the fourth argument, isCommit, is non-zero, then this page is being
48350 ** moved as part of a database reorganization just before the transaction
48351 ** is being committed. In this case, it is guaranteed that the database page
48352 ** pPg refers to will not be written to again within this transaction.
48353 **
48354 ** This function may return SQLITE_NOMEM or an IO error code if an error
48355 ** occurs. Otherwise, it returns SQLITE_OK.
48356 */
48357 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
48358   PgHdr *pPgOld;               /* The page being overwritten. */
48359   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
48360   int rc;                      /* Return code */
48361   Pgno origPgno;               /* The original page number */
48362 
48363   assert( pPg->nRef>0 );
48364   assert( pPager->eState==PAGER_WRITER_CACHEMOD
48365        || pPager->eState==PAGER_WRITER_DBMOD
48366   );
48367   assert( assert_pager_state(pPager) );
48368 
48369   /* In order to be able to rollback, an in-memory database must journal
48370   ** the page we are moving from.
48371   */
48372   if( MEMDB ){
48373     rc = sqlite3PagerWrite(pPg);
48374     if( rc ) return rc;
48375   }
48376 
48377   /* If the page being moved is dirty and has not been saved by the latest
48378   ** savepoint, then save the current contents of the page into the
48379   ** sub-journal now. This is required to handle the following scenario:
48380   **
48381   **   BEGIN;
48382   **     <journal page X, then modify it in memory>
48383   **     SAVEPOINT one;
48384   **       <Move page X to location Y>
48385   **     ROLLBACK TO one;
48386   **
48387   ** If page X were not written to the sub-journal here, it would not
48388   ** be possible to restore its contents when the "ROLLBACK TO one"
48389   ** statement were is processed.
48390   **
48391   ** subjournalPage() may need to allocate space to store pPg->pgno into
48392   ** one or more savepoint bitvecs. This is the reason this function
48393   ** may return SQLITE_NOMEM.
48394   */
48395   if( pPg->flags&PGHDR_DIRTY
48396    && subjRequiresPage(pPg)
48397    && SQLITE_OK!=(rc = subjournalPage(pPg))
48398   ){
48399     return rc;
48400   }
48401 
48402   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
48403       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
48404   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
48405 
48406   /* If the journal needs to be sync()ed before page pPg->pgno can
48407   ** be written to, store pPg->pgno in local variable needSyncPgno.
48408   **
48409   ** If the isCommit flag is set, there is no need to remember that
48410   ** the journal needs to be sync()ed before database page pPg->pgno
48411   ** can be written to. The caller has already promised not to write to it.
48412   */
48413   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
48414     needSyncPgno = pPg->pgno;
48415     assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
48416             pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
48417     assert( pPg->flags&PGHDR_DIRTY );
48418   }
48419 
48420   /* If the cache contains a page with page-number pgno, remove it
48421   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
48422   ** page pgno before the 'move' operation, it needs to be retained
48423   ** for the page moved there.
48424   */
48425   pPg->flags &= ~PGHDR_NEED_SYNC;
48426   pPgOld = sqlite3PagerLookup(pPager, pgno);
48427   assert( !pPgOld || pPgOld->nRef==1 );
48428   if( pPgOld ){
48429     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
48430     if( MEMDB ){
48431       /* Do not discard pages from an in-memory database since we might
48432       ** need to rollback later.  Just move the page out of the way. */
48433       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
48434     }else{
48435       sqlite3PcacheDrop(pPgOld);
48436     }
48437   }
48438 
48439   origPgno = pPg->pgno;
48440   sqlite3PcacheMove(pPg, pgno);
48441   sqlite3PcacheMakeDirty(pPg);
48442 
48443   /* For an in-memory database, make sure the original page continues
48444   ** to exist, in case the transaction needs to roll back.  Use pPgOld
48445   ** as the original page since it has already been allocated.
48446   */
48447   if( MEMDB ){
48448     assert( pPgOld );
48449     sqlite3PcacheMove(pPgOld, origPgno);
48450     sqlite3PagerUnrefNotNull(pPgOld);
48451   }
48452 
48453   if( needSyncPgno ){
48454     /* If needSyncPgno is non-zero, then the journal file needs to be
48455     ** sync()ed before any data is written to database file page needSyncPgno.
48456     ** Currently, no such page exists in the page-cache and the
48457     ** "is journaled" bitvec flag has been set. This needs to be remedied by
48458     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
48459     ** flag.
48460     **
48461     ** If the attempt to load the page into the page-cache fails, (due
48462     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
48463     ** array. Otherwise, if the page is loaded and written again in
48464     ** this transaction, it may be written to the database file before
48465     ** it is synced into the journal file. This way, it may end up in
48466     ** the journal file twice, but that is not a problem.
48467     */
48468     PgHdr *pPgHdr;
48469     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
48470     if( rc!=SQLITE_OK ){
48471       if( needSyncPgno<=pPager->dbOrigSize ){
48472         assert( pPager->pTmpSpace!=0 );
48473         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
48474       }
48475       return rc;
48476     }
48477     pPgHdr->flags |= PGHDR_NEED_SYNC;
48478     sqlite3PcacheMakeDirty(pPgHdr);
48479     sqlite3PagerUnrefNotNull(pPgHdr);
48480   }
48481 
48482   return SQLITE_OK;
48483 }
48484 #endif
48485 
48486 /*
48487 ** The page handle passed as the first argument refers to a dirty page
48488 ** with a page number other than iNew. This function changes the page's
48489 ** page number to iNew and sets the value of the PgHdr.flags field to
48490 ** the value passed as the third parameter.
48491 */
48492 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
48493   assert( pPg->pgno!=iNew );
48494   pPg->flags = flags;
48495   sqlite3PcacheMove(pPg, iNew);
48496 }
48497 
48498 /*
48499 ** Return a pointer to the data for the specified page.
48500 */
48501 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
48502   assert( pPg->nRef>0 || pPg->pPager->memDb );
48503   return pPg->pData;
48504 }
48505 
48506 /*
48507 ** Return a pointer to the Pager.nExtra bytes of "extra" space
48508 ** allocated along with the specified page.
48509 */
48510 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
48511   return pPg->pExtra;
48512 }
48513 
48514 /*
48515 ** Get/set the locking-mode for this pager. Parameter eMode must be one
48516 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
48517 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
48518 ** the locking-mode is set to the value specified.
48519 **
48520 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
48521 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
48522 ** locking-mode.
48523 */
48524 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
48525   assert( eMode==PAGER_LOCKINGMODE_QUERY
48526             || eMode==PAGER_LOCKINGMODE_NORMAL
48527             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
48528   assert( PAGER_LOCKINGMODE_QUERY<0 );
48529   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
48530   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
48531   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
48532     pPager->exclusiveMode = (u8)eMode;
48533   }
48534   return (int)pPager->exclusiveMode;
48535 }
48536 
48537 /*
48538 ** Set the journal-mode for this pager. Parameter eMode must be one of:
48539 **
48540 **    PAGER_JOURNALMODE_DELETE
48541 **    PAGER_JOURNALMODE_TRUNCATE
48542 **    PAGER_JOURNALMODE_PERSIST
48543 **    PAGER_JOURNALMODE_OFF
48544 **    PAGER_JOURNALMODE_MEMORY
48545 **    PAGER_JOURNALMODE_WAL
48546 **
48547 ** The journalmode is set to the value specified if the change is allowed.
48548 ** The change may be disallowed for the following reasons:
48549 **
48550 **   *  An in-memory database can only have its journal_mode set to _OFF
48551 **      or _MEMORY.
48552 **
48553 **   *  Temporary databases cannot have _WAL journalmode.
48554 **
48555 ** The returned indicate the current (possibly updated) journal-mode.
48556 */
48557 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
48558   u8 eOld = pPager->journalMode;    /* Prior journalmode */
48559 
48560 #ifdef SQLITE_DEBUG
48561   /* The print_pager_state() routine is intended to be used by the debugger
48562   ** only.  We invoke it once here to suppress a compiler warning. */
48563   print_pager_state(pPager);
48564 #endif
48565 
48566 
48567   /* The eMode parameter is always valid */
48568   assert(      eMode==PAGER_JOURNALMODE_DELETE
48569             || eMode==PAGER_JOURNALMODE_TRUNCATE
48570             || eMode==PAGER_JOURNALMODE_PERSIST
48571             || eMode==PAGER_JOURNALMODE_OFF
48572             || eMode==PAGER_JOURNALMODE_WAL
48573             || eMode==PAGER_JOURNALMODE_MEMORY );
48574 
48575   /* This routine is only called from the OP_JournalMode opcode, and
48576   ** the logic there will never allow a temporary file to be changed
48577   ** to WAL mode.
48578   */
48579   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
48580 
48581   /* Do allow the journalmode of an in-memory database to be set to
48582   ** anything other than MEMORY or OFF
48583   */
48584   if( MEMDB ){
48585     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
48586     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
48587       eMode = eOld;
48588     }
48589   }
48590 
48591   if( eMode!=eOld ){
48592 
48593     /* Change the journal mode. */
48594     assert( pPager->eState!=PAGER_ERROR );
48595     pPager->journalMode = (u8)eMode;
48596 
48597     /* When transistioning from TRUNCATE or PERSIST to any other journal
48598     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
48599     ** delete the journal file.
48600     */
48601     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
48602     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
48603     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
48604     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
48605     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
48606     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
48607 
48608     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
48609     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
48610 
48611       /* In this case we would like to delete the journal file. If it is
48612       ** not possible, then that is not a problem. Deleting the journal file
48613       ** here is an optimization only.
48614       **
48615       ** Before deleting the journal file, obtain a RESERVED lock on the
48616       ** database file. This ensures that the journal file is not deleted
48617       ** while it is in use by some other client.
48618       */
48619       sqlite3OsClose(pPager->jfd);
48620       if( pPager->eLock>=RESERVED_LOCK ){
48621         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
48622       }else{
48623         int rc = SQLITE_OK;
48624         int state = pPager->eState;
48625         assert( state==PAGER_OPEN || state==PAGER_READER );
48626         if( state==PAGER_OPEN ){
48627           rc = sqlite3PagerSharedLock(pPager);
48628         }
48629         if( pPager->eState==PAGER_READER ){
48630           assert( rc==SQLITE_OK );
48631           rc = pagerLockDb(pPager, RESERVED_LOCK);
48632         }
48633         if( rc==SQLITE_OK ){
48634           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
48635         }
48636         if( rc==SQLITE_OK && state==PAGER_READER ){
48637           pagerUnlockDb(pPager, SHARED_LOCK);
48638         }else if( state==PAGER_OPEN ){
48639           pager_unlock(pPager);
48640         }
48641         assert( state==pPager->eState );
48642       }
48643     }else if( eMode==PAGER_JOURNALMODE_OFF ){
48644       sqlite3OsClose(pPager->jfd);
48645     }
48646   }
48647 
48648   /* Return the new journal mode */
48649   return (int)pPager->journalMode;
48650 }
48651 
48652 /*
48653 ** Return the current journal mode.
48654 */
48655 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
48656   return (int)pPager->journalMode;
48657 }
48658 
48659 /*
48660 ** Return TRUE if the pager is in a state where it is OK to change the
48661 ** journalmode.  Journalmode changes can only happen when the database
48662 ** is unmodified.
48663 */
48664 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
48665   assert( assert_pager_state(pPager) );
48666   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
48667   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
48668   return 1;
48669 }
48670 
48671 /*
48672 ** Get/set the size-limit used for persistent journal files.
48673 **
48674 ** Setting the size limit to -1 means no limit is enforced.
48675 ** An attempt to set a limit smaller than -1 is a no-op.
48676 */
48677 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
48678   if( iLimit>=-1 ){
48679     pPager->journalSizeLimit = iLimit;
48680     sqlite3WalLimit(pPager->pWal, iLimit);
48681   }
48682   return pPager->journalSizeLimit;
48683 }
48684 
48685 /*
48686 ** Return a pointer to the pPager->pBackup variable. The backup module
48687 ** in backup.c maintains the content of this variable. This module
48688 ** uses it opaquely as an argument to sqlite3BackupRestart() and
48689 ** sqlite3BackupUpdate() only.
48690 */
48691 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
48692   return &pPager->pBackup;
48693 }
48694 
48695 #ifndef SQLITE_OMIT_VACUUM
48696 /*
48697 ** Unless this is an in-memory or temporary database, clear the pager cache.
48698 */
48699 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
48700   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
48701 }
48702 #endif
48703 
48704 #ifndef SQLITE_OMIT_WAL
48705 /*
48706 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
48707 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
48708 ** or wal_blocking_checkpoint() API functions.
48709 **
48710 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
48711 */
48712 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
48713   int rc = SQLITE_OK;
48714   if( pPager->pWal ){
48715     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
48716         (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
48717         pPager->pBusyHandlerArg,
48718         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
48719         pnLog, pnCkpt
48720     );
48721   }
48722   return rc;
48723 }
48724 
48725 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
48726   return sqlite3WalCallback(pPager->pWal);
48727 }
48728 
48729 /*
48730 ** Return true if the underlying VFS for the given pager supports the
48731 ** primitives necessary for write-ahead logging.
48732 */
48733 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
48734   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
48735   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
48736 }
48737 
48738 /*
48739 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
48740 ** is obtained instead, immediately release it.
48741 */
48742 static int pagerExclusiveLock(Pager *pPager){
48743   int rc;                         /* Return code */
48744 
48745   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
48746   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
48747   if( rc!=SQLITE_OK ){
48748     /* If the attempt to grab the exclusive lock failed, release the
48749     ** pending lock that may have been obtained instead.  */
48750     pagerUnlockDb(pPager, SHARED_LOCK);
48751   }
48752 
48753   return rc;
48754 }
48755 
48756 /*
48757 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
48758 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
48759 ** lock on the database file and use heap-memory to store the wal-index
48760 ** in. Otherwise, use the normal shared-memory.
48761 */
48762 static int pagerOpenWal(Pager *pPager){
48763   int rc = SQLITE_OK;
48764 
48765   assert( pPager->pWal==0 && pPager->tempFile==0 );
48766   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
48767 
48768   /* If the pager is already in exclusive-mode, the WAL module will use
48769   ** heap-memory for the wal-index instead of the VFS shared-memory
48770   ** implementation. Take the exclusive lock now, before opening the WAL
48771   ** file, to make sure this is safe.
48772   */
48773   if( pPager->exclusiveMode ){
48774     rc = pagerExclusiveLock(pPager);
48775   }
48776 
48777   /* Open the connection to the log file. If this operation fails,
48778   ** (e.g. due to malloc() failure), return an error code.
48779   */
48780   if( rc==SQLITE_OK ){
48781     rc = sqlite3WalOpen(pPager->pVfs,
48782         pPager->fd, pPager->zWal, pPager->exclusiveMode,
48783         pPager->journalSizeLimit, &pPager->pWal
48784     );
48785   }
48786   pagerFixMaplimit(pPager);
48787 
48788   return rc;
48789 }
48790 
48791 
48792 /*
48793 ** The caller must be holding a SHARED lock on the database file to call
48794 ** this function.
48795 **
48796 ** If the pager passed as the first argument is open on a real database
48797 ** file (not a temp file or an in-memory database), and the WAL file
48798 ** is not already open, make an attempt to open it now. If successful,
48799 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
48800 ** not support the xShmXXX() methods, return an error code. *pbOpen is
48801 ** not modified in either case.
48802 **
48803 ** If the pager is open on a temp-file (or in-memory database), or if
48804 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
48805 ** without doing anything.
48806 */
48807 SQLITE_PRIVATE int sqlite3PagerOpenWal(
48808   Pager *pPager,                  /* Pager object */
48809   int *pbOpen                     /* OUT: Set to true if call is a no-op */
48810 ){
48811   int rc = SQLITE_OK;             /* Return code */
48812 
48813   assert( assert_pager_state(pPager) );
48814   assert( pPager->eState==PAGER_OPEN   || pbOpen );
48815   assert( pPager->eState==PAGER_READER || !pbOpen );
48816   assert( pbOpen==0 || *pbOpen==0 );
48817   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
48818 
48819   if( !pPager->tempFile && !pPager->pWal ){
48820     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
48821 
48822     /* Close any rollback journal previously open */
48823     sqlite3OsClose(pPager->jfd);
48824 
48825     rc = pagerOpenWal(pPager);
48826     if( rc==SQLITE_OK ){
48827       pPager->journalMode = PAGER_JOURNALMODE_WAL;
48828       pPager->eState = PAGER_OPEN;
48829     }
48830   }else{
48831     *pbOpen = 1;
48832   }
48833 
48834   return rc;
48835 }
48836 
48837 /*
48838 ** This function is called to close the connection to the log file prior
48839 ** to switching from WAL to rollback mode.
48840 **
48841 ** Before closing the log file, this function attempts to take an
48842 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
48843 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
48844 ** If successful, the EXCLUSIVE lock is not released before returning.
48845 */
48846 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
48847   int rc = SQLITE_OK;
48848 
48849   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
48850 
48851   /* If the log file is not already open, but does exist in the file-system,
48852   ** it may need to be checkpointed before the connection can switch to
48853   ** rollback mode. Open it now so this can happen.
48854   */
48855   if( !pPager->pWal ){
48856     int logexists = 0;
48857     rc = pagerLockDb(pPager, SHARED_LOCK);
48858     if( rc==SQLITE_OK ){
48859       rc = sqlite3OsAccess(
48860           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
48861       );
48862     }
48863     if( rc==SQLITE_OK && logexists ){
48864       rc = pagerOpenWal(pPager);
48865     }
48866   }
48867 
48868   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
48869   ** the database file, the log and log-summary files will be deleted.
48870   */
48871   if( rc==SQLITE_OK && pPager->pWal ){
48872     rc = pagerExclusiveLock(pPager);
48873     if( rc==SQLITE_OK ){
48874       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
48875                            pPager->pageSize, (u8*)pPager->pTmpSpace);
48876       pPager->pWal = 0;
48877       pagerFixMaplimit(pPager);
48878     }
48879   }
48880   return rc;
48881 }
48882 
48883 #endif /* !SQLITE_OMIT_WAL */
48884 
48885 #ifdef SQLITE_ENABLE_ZIPVFS
48886 /*
48887 ** A read-lock must be held on the pager when this function is called. If
48888 ** the pager is in WAL mode and the WAL file currently contains one or more
48889 ** frames, return the size in bytes of the page images stored within the
48890 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
48891 ** is empty, return 0.
48892 */
48893 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
48894   assert( pPager->eState>=PAGER_READER );
48895   return sqlite3WalFramesize(pPager->pWal);
48896 }
48897 #endif
48898 
48899 
48900 #endif /* SQLITE_OMIT_DISKIO */
48901 
48902 /************** End of pager.c ***********************************************/
48903 /************** Begin file wal.c *********************************************/
48904 /*
48905 ** 2010 February 1
48906 **
48907 ** The author disclaims copyright to this source code.  In place of
48908 ** a legal notice, here is a blessing:
48909 **
48910 **    May you do good and not evil.
48911 **    May you find forgiveness for yourself and forgive others.
48912 **    May you share freely, never taking more than you give.
48913 **
48914 *************************************************************************
48915 **
48916 ** This file contains the implementation of a write-ahead log (WAL) used in
48917 ** "journal_mode=WAL" mode.
48918 **
48919 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
48920 **
48921 ** A WAL file consists of a header followed by zero or more "frames".
48922 ** Each frame records the revised content of a single page from the
48923 ** database file.  All changes to the database are recorded by writing
48924 ** frames into the WAL.  Transactions commit when a frame is written that
48925 ** contains a commit marker.  A single WAL can and usually does record
48926 ** multiple transactions.  Periodically, the content of the WAL is
48927 ** transferred back into the database file in an operation called a
48928 ** "checkpoint".
48929 **
48930 ** A single WAL file can be used multiple times.  In other words, the
48931 ** WAL can fill up with frames and then be checkpointed and then new
48932 ** frames can overwrite the old ones.  A WAL always grows from beginning
48933 ** toward the end.  Checksums and counters attached to each frame are
48934 ** used to determine which frames within the WAL are valid and which
48935 ** are leftovers from prior checkpoints.
48936 **
48937 ** The WAL header is 32 bytes in size and consists of the following eight
48938 ** big-endian 32-bit unsigned integer values:
48939 **
48940 **     0: Magic number.  0x377f0682 or 0x377f0683
48941 **     4: File format version.  Currently 3007000
48942 **     8: Database page size.  Example: 1024
48943 **    12: Checkpoint sequence number
48944 **    16: Salt-1, random integer incremented with each checkpoint
48945 **    20: Salt-2, a different random integer changing with each ckpt
48946 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
48947 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
48948 **
48949 ** Immediately following the wal-header are zero or more frames. Each
48950 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
48951 ** of page data. The frame-header is six big-endian 32-bit unsigned
48952 ** integer values, as follows:
48953 **
48954 **     0: Page number.
48955 **     4: For commit records, the size of the database image in pages
48956 **        after the commit. For all other records, zero.
48957 **     8: Salt-1 (copied from the header)
48958 **    12: Salt-2 (copied from the header)
48959 **    16: Checksum-1.
48960 **    20: Checksum-2.
48961 **
48962 ** A frame is considered valid if and only if the following conditions are
48963 ** true:
48964 **
48965 **    (1) The salt-1 and salt-2 values in the frame-header match
48966 **        salt values in the wal-header
48967 **
48968 **    (2) The checksum values in the final 8 bytes of the frame-header
48969 **        exactly match the checksum computed consecutively on the
48970 **        WAL header and the first 8 bytes and the content of all frames
48971 **        up to and including the current frame.
48972 **
48973 ** The checksum is computed using 32-bit big-endian integers if the
48974 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
48975 ** is computed using little-endian if the magic number is 0x377f0682.
48976 ** The checksum values are always stored in the frame header in a
48977 ** big-endian format regardless of which byte order is used to compute
48978 ** the checksum.  The checksum is computed by interpreting the input as
48979 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
48980 ** algorithm used for the checksum is as follows:
48981 **
48982 **   for i from 0 to n-1 step 2:
48983 **     s0 += x[i] + s1;
48984 **     s1 += x[i+1] + s0;
48985 **   endfor
48986 **
48987 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
48988 ** in reverse order (the largest fibonacci weight occurs on the first element
48989 ** of the sequence being summed.)  The s1 value spans all 32-bit
48990 ** terms of the sequence whereas s0 omits the final term.
48991 **
48992 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
48993 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
48994 ** The VFS.xSync operations serve as write barriers - all writes launched
48995 ** before the xSync must complete before any write that launches after the
48996 ** xSync begins.
48997 **
48998 ** After each checkpoint, the salt-1 value is incremented and the salt-2
48999 ** value is randomized.  This prevents old and new frames in the WAL from
49000 ** being considered valid at the same time and being checkpointing together
49001 ** following a crash.
49002 **
49003 ** READER ALGORITHM
49004 **
49005 ** To read a page from the database (call it page number P), a reader
49006 ** first checks the WAL to see if it contains page P.  If so, then the
49007 ** last valid instance of page P that is a followed by a commit frame
49008 ** or is a commit frame itself becomes the value read.  If the WAL
49009 ** contains no copies of page P that are valid and which are a commit
49010 ** frame or are followed by a commit frame, then page P is read from
49011 ** the database file.
49012 **
49013 ** To start a read transaction, the reader records the index of the last
49014 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
49015 ** for all subsequent read operations.  New transactions can be appended
49016 ** to the WAL, but as long as the reader uses its original mxFrame value
49017 ** and ignores the newly appended content, it will see a consistent snapshot
49018 ** of the database from a single point in time.  This technique allows
49019 ** multiple concurrent readers to view different versions of the database
49020 ** content simultaneously.
49021 **
49022 ** The reader algorithm in the previous paragraphs works correctly, but
49023 ** because frames for page P can appear anywhere within the WAL, the
49024 ** reader has to scan the entire WAL looking for page P frames.  If the
49025 ** WAL is large (multiple megabytes is typical) that scan can be slow,
49026 ** and read performance suffers.  To overcome this problem, a separate
49027 ** data structure called the wal-index is maintained to expedite the
49028 ** search for frames of a particular page.
49029 **
49030 ** WAL-INDEX FORMAT
49031 **
49032 ** Conceptually, the wal-index is shared memory, though VFS implementations
49033 ** might choose to implement the wal-index using a mmapped file.  Because
49034 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
49035 ** on a network filesystem.  All users of the database must be able to
49036 ** share memory.
49037 **
49038 ** The wal-index is transient.  After a crash, the wal-index can (and should
49039 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
49040 ** to either truncate or zero the header of the wal-index when the last
49041 ** connection to it closes.  Because the wal-index is transient, it can
49042 ** use an architecture-specific format; it does not have to be cross-platform.
49043 ** Hence, unlike the database and WAL file formats which store all values
49044 ** as big endian, the wal-index can store multi-byte values in the native
49045 ** byte order of the host computer.
49046 **
49047 ** The purpose of the wal-index is to answer this question quickly:  Given
49048 ** a page number P and a maximum frame index M, return the index of the
49049 ** last frame in the wal before frame M for page P in the WAL, or return
49050 ** NULL if there are no frames for page P in the WAL prior to M.
49051 **
49052 ** The wal-index consists of a header region, followed by an one or
49053 ** more index blocks.
49054 **
49055 ** The wal-index header contains the total number of frames within the WAL
49056 ** in the mxFrame field.
49057 **
49058 ** Each index block except for the first contains information on
49059 ** HASHTABLE_NPAGE frames. The first index block contains information on
49060 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
49061 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
49062 ** first index block are the same size as all other index blocks in the
49063 ** wal-index.
49064 **
49065 ** Each index block contains two sections, a page-mapping that contains the
49066 ** database page number associated with each wal frame, and a hash-table
49067 ** that allows readers to query an index block for a specific page number.
49068 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
49069 ** for the first index block) 32-bit page numbers. The first entry in the
49070 ** first index-block contains the database page number corresponding to the
49071 ** first frame in the WAL file. The first entry in the second index block
49072 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
49073 ** the log, and so on.
49074 **
49075 ** The last index block in a wal-index usually contains less than the full
49076 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
49077 ** depending on the contents of the WAL file. This does not change the
49078 ** allocated size of the page-mapping array - the page-mapping array merely
49079 ** contains unused entries.
49080 **
49081 ** Even without using the hash table, the last frame for page P
49082 ** can be found by scanning the page-mapping sections of each index block
49083 ** starting with the last index block and moving toward the first, and
49084 ** within each index block, starting at the end and moving toward the
49085 ** beginning.  The first entry that equals P corresponds to the frame
49086 ** holding the content for that page.
49087 **
49088 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
49089 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
49090 ** hash table for each page number in the mapping section, so the hash
49091 ** table is never more than half full.  The expected number of collisions
49092 ** prior to finding a match is 1.  Each entry of the hash table is an
49093 ** 1-based index of an entry in the mapping section of the same
49094 ** index block.   Let K be the 1-based index of the largest entry in
49095 ** the mapping section.  (For index blocks other than the last, K will
49096 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
49097 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
49098 ** contain a value of 0.
49099 **
49100 ** To look for page P in the hash table, first compute a hash iKey on
49101 ** P as follows:
49102 **
49103 **      iKey = (P * 383) % HASHTABLE_NSLOT
49104 **
49105 ** Then start scanning entries of the hash table, starting with iKey
49106 ** (wrapping around to the beginning when the end of the hash table is
49107 ** reached) until an unused hash slot is found. Let the first unused slot
49108 ** be at index iUnused.  (iUnused might be less than iKey if there was
49109 ** wrap-around.) Because the hash table is never more than half full,
49110 ** the search is guaranteed to eventually hit an unused entry.  Let
49111 ** iMax be the value between iKey and iUnused, closest to iUnused,
49112 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
49113 ** no hash slot such that aHash[i]==p) then page P is not in the
49114 ** current index block.  Otherwise the iMax-th mapping entry of the
49115 ** current index block corresponds to the last entry that references
49116 ** page P.
49117 **
49118 ** A hash search begins with the last index block and moves toward the
49119 ** first index block, looking for entries corresponding to page P.  On
49120 ** average, only two or three slots in each index block need to be
49121 ** examined in order to either find the last entry for page P, or to
49122 ** establish that no such entry exists in the block.  Each index block
49123 ** holds over 4000 entries.  So two or three index blocks are sufficient
49124 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
49125 ** comparisons (on average) suffice to either locate a frame in the
49126 ** WAL or to establish that the frame does not exist in the WAL.  This
49127 ** is much faster than scanning the entire 10MB WAL.
49128 **
49129 ** Note that entries are added in order of increasing K.  Hence, one
49130 ** reader might be using some value K0 and a second reader that started
49131 ** at a later time (after additional transactions were added to the WAL
49132 ** and to the wal-index) might be using a different value K1, where K1>K0.
49133 ** Both readers can use the same hash table and mapping section to get
49134 ** the correct result.  There may be entries in the hash table with
49135 ** K>K0 but to the first reader, those entries will appear to be unused
49136 ** slots in the hash table and so the first reader will get an answer as
49137 ** if no values greater than K0 had ever been inserted into the hash table
49138 ** in the first place - which is what reader one wants.  Meanwhile, the
49139 ** second reader using K1 will see additional values that were inserted
49140 ** later, which is exactly what reader two wants.
49141 **
49142 ** When a rollback occurs, the value of K is decreased. Hash table entries
49143 ** that correspond to frames greater than the new K value are removed
49144 ** from the hash table at this point.
49145 */
49146 #ifndef SQLITE_OMIT_WAL
49147 
49148 
49149 /*
49150 ** Trace output macros
49151 */
49152 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
49153 SQLITE_PRIVATE int sqlite3WalTrace = 0;
49154 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
49155 #else
49156 # define WALTRACE(X)
49157 #endif
49158 
49159 /*
49160 ** The maximum (and only) versions of the wal and wal-index formats
49161 ** that may be interpreted by this version of SQLite.
49162 **
49163 ** If a client begins recovering a WAL file and finds that (a) the checksum
49164 ** values in the wal-header are correct and (b) the version field is not
49165 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
49166 **
49167 ** Similarly, if a client successfully reads a wal-index header (i.e. the
49168 ** checksum test is successful) and finds that the version field is not
49169 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
49170 ** returns SQLITE_CANTOPEN.
49171 */
49172 #define WAL_MAX_VERSION      3007000
49173 #define WALINDEX_MAX_VERSION 3007000
49174 
49175 /*
49176 ** Indices of various locking bytes.   WAL_NREADER is the number
49177 ** of available reader locks and should be at least 3.
49178 */
49179 #define WAL_WRITE_LOCK         0
49180 #define WAL_ALL_BUT_WRITE      1
49181 #define WAL_CKPT_LOCK          1
49182 #define WAL_RECOVER_LOCK       2
49183 #define WAL_READ_LOCK(I)       (3+(I))
49184 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
49185 
49186 
49187 /* Object declarations */
49188 typedef struct WalIndexHdr WalIndexHdr;
49189 typedef struct WalIterator WalIterator;
49190 typedef struct WalCkptInfo WalCkptInfo;
49191 
49192 
49193 /*
49194 ** The following object holds a copy of the wal-index header content.
49195 **
49196 ** The actual header in the wal-index consists of two copies of this
49197 ** object.
49198 **
49199 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
49200 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
49201 ** added in 3.7.1 when support for 64K pages was added.
49202 */
49203 struct WalIndexHdr {
49204   u32 iVersion;                   /* Wal-index version */
49205   u32 unused;                     /* Unused (padding) field */
49206   u32 iChange;                    /* Counter incremented each transaction */
49207   u8 isInit;                      /* 1 when initialized */
49208   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
49209   u16 szPage;                     /* Database page size in bytes. 1==64K */
49210   u32 mxFrame;                    /* Index of last valid frame in the WAL */
49211   u32 nPage;                      /* Size of database in pages */
49212   u32 aFrameCksum[2];             /* Checksum of last frame in log */
49213   u32 aSalt[2];                   /* Two salt values copied from WAL header */
49214   u32 aCksum[2];                  /* Checksum over all prior fields */
49215 };
49216 
49217 /*
49218 ** A copy of the following object occurs in the wal-index immediately
49219 ** following the second copy of the WalIndexHdr.  This object stores
49220 ** information used by checkpoint.
49221 **
49222 ** nBackfill is the number of frames in the WAL that have been written
49223 ** back into the database. (We call the act of moving content from WAL to
49224 ** database "backfilling".)  The nBackfill number is never greater than
49225 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
49226 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
49227 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
49228 ** mxFrame back to zero when the WAL is reset.
49229 **
49230 ** There is one entry in aReadMark[] for each reader lock.  If a reader
49231 ** holds read-lock K, then the value in aReadMark[K] is no greater than
49232 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
49233 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is
49234 ** a special case; its value is never used and it exists as a place-holder
49235 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
49236 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
49237 ** directly from the database.
49238 **
49239 ** The value of aReadMark[K] may only be changed by a thread that
49240 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
49241 ** aReadMark[K] cannot changed while there is a reader is using that mark
49242 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
49243 **
49244 ** The checkpointer may only transfer frames from WAL to database where
49245 ** the frame numbers are less than or equal to every aReadMark[] that is
49246 ** in use (that is, every aReadMark[j] for which there is a corresponding
49247 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
49248 ** largest value and will increase an unused aReadMark[] to mxFrame if there
49249 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
49250 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
49251 ** in the WAL has been backfilled into the database) then new readers
49252 ** will choose aReadMark[0] which has value 0 and hence such reader will
49253 ** get all their all content directly from the database file and ignore
49254 ** the WAL.
49255 **
49256 ** Writers normally append new frames to the end of the WAL.  However,
49257 ** if nBackfill equals mxFrame (meaning that all WAL content has been
49258 ** written back into the database) and if no readers are using the WAL
49259 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
49260 ** the writer will first "reset" the WAL back to the beginning and start
49261 ** writing new content beginning at frame 1.
49262 **
49263 ** We assume that 32-bit loads are atomic and so no locks are needed in
49264 ** order to read from any aReadMark[] entries.
49265 */
49266 struct WalCkptInfo {
49267   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
49268   u32 aReadMark[WAL_NREADER];     /* Reader marks */
49269 };
49270 #define READMARK_NOT_USED  0xffffffff
49271 
49272 
49273 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
49274 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
49275 ** only support mandatory file-locks, we do not read or write data
49276 ** from the region of the file on which locks are applied.
49277 */
49278 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
49279 #define WALINDEX_LOCK_RESERVED 16
49280 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
49281 
49282 /* Size of header before each frame in wal */
49283 #define WAL_FRAME_HDRSIZE 24
49284 
49285 /* Size of write ahead log header, including checksum. */
49286 /* #define WAL_HDRSIZE 24 */
49287 #define WAL_HDRSIZE 32
49288 
49289 /* WAL magic value. Either this value, or the same value with the least
49290 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
49291 ** big-endian format in the first 4 bytes of a WAL file.
49292 **
49293 ** If the LSB is set, then the checksums for each frame within the WAL
49294 ** file are calculated by treating all data as an array of 32-bit
49295 ** big-endian words. Otherwise, they are calculated by interpreting
49296 ** all data as 32-bit little-endian words.
49297 */
49298 #define WAL_MAGIC 0x377f0682
49299 
49300 /*
49301 ** Return the offset of frame iFrame in the write-ahead log file,
49302 ** assuming a database page size of szPage bytes. The offset returned
49303 ** is to the start of the write-ahead log frame-header.
49304 */
49305 #define walFrameOffset(iFrame, szPage) (                               \
49306   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
49307 )
49308 
49309 /*
49310 ** An open write-ahead log file is represented by an instance of the
49311 ** following object.
49312 */
49313 struct Wal {
49314   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
49315   sqlite3_file *pDbFd;       /* File handle for the database file */
49316   sqlite3_file *pWalFd;      /* File handle for WAL file */
49317   u32 iCallback;             /* Value to pass to log callback (or 0) */
49318   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
49319   int nWiData;               /* Size of array apWiData */
49320   int szFirstBlock;          /* Size of first block written to WAL file */
49321   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
49322   u32 szPage;                /* Database page size */
49323   i16 readLock;              /* Which read lock is being held.  -1 for none */
49324   u8 syncFlags;              /* Flags to use to sync header writes */
49325   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
49326   u8 writeLock;              /* True if in a write transaction */
49327   u8 ckptLock;               /* True if holding a checkpoint lock */
49328   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
49329   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
49330   u8 syncHeader;             /* Fsync the WAL header if true */
49331   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
49332   WalIndexHdr hdr;           /* Wal-index header for current transaction */
49333   const char *zWalName;      /* Name of WAL file */
49334   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
49335 #ifdef SQLITE_DEBUG
49336   u8 lockError;              /* True if a locking error has occurred */
49337 #endif
49338 };
49339 
49340 /*
49341 ** Candidate values for Wal.exclusiveMode.
49342 */
49343 #define WAL_NORMAL_MODE     0
49344 #define WAL_EXCLUSIVE_MODE  1
49345 #define WAL_HEAPMEMORY_MODE 2
49346 
49347 /*
49348 ** Possible values for WAL.readOnly
49349 */
49350 #define WAL_RDWR        0    /* Normal read/write connection */
49351 #define WAL_RDONLY      1    /* The WAL file is readonly */
49352 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
49353 
49354 /*
49355 ** Each page of the wal-index mapping contains a hash-table made up of
49356 ** an array of HASHTABLE_NSLOT elements of the following type.
49357 */
49358 typedef u16 ht_slot;
49359 
49360 /*
49361 ** This structure is used to implement an iterator that loops through
49362 ** all frames in the WAL in database page order. Where two or more frames
49363 ** correspond to the same database page, the iterator visits only the
49364 ** frame most recently written to the WAL (in other words, the frame with
49365 ** the largest index).
49366 **
49367 ** The internals of this structure are only accessed by:
49368 **
49369 **   walIteratorInit() - Create a new iterator,
49370 **   walIteratorNext() - Step an iterator,
49371 **   walIteratorFree() - Free an iterator.
49372 **
49373 ** This functionality is used by the checkpoint code (see walCheckpoint()).
49374 */
49375 struct WalIterator {
49376   int iPrior;                     /* Last result returned from the iterator */
49377   int nSegment;                   /* Number of entries in aSegment[] */
49378   struct WalSegment {
49379     int iNext;                    /* Next slot in aIndex[] not yet returned */
49380     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
49381     u32 *aPgno;                   /* Array of page numbers. */
49382     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
49383     int iZero;                    /* Frame number associated with aPgno[0] */
49384   } aSegment[1];                  /* One for every 32KB page in the wal-index */
49385 };
49386 
49387 /*
49388 ** Define the parameters of the hash tables in the wal-index file. There
49389 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
49390 ** wal-index.
49391 **
49392 ** Changing any of these constants will alter the wal-index format and
49393 ** create incompatibilities.
49394 */
49395 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
49396 #define HASHTABLE_HASH_1     383                  /* Should be prime */
49397 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
49398 
49399 /*
49400 ** The block of page numbers associated with the first hash-table in a
49401 ** wal-index is smaller than usual. This is so that there is a complete
49402 ** hash-table on each aligned 32KB page of the wal-index.
49403 */
49404 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
49405 
49406 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
49407 #define WALINDEX_PGSZ   (                                         \
49408     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
49409 )
49410 
49411 /*
49412 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
49413 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
49414 ** numbered from zero.
49415 **
49416 ** If this call is successful, *ppPage is set to point to the wal-index
49417 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
49418 ** then an SQLite error code is returned and *ppPage is set to 0.
49419 */
49420 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
49421   int rc = SQLITE_OK;
49422 
49423   /* Enlarge the pWal->apWiData[] array if required */
49424   if( pWal->nWiData<=iPage ){
49425     int nByte = sizeof(u32*)*(iPage+1);
49426     volatile u32 **apNew;
49427     apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
49428     if( !apNew ){
49429       *ppPage = 0;
49430       return SQLITE_NOMEM;
49431     }
49432     memset((void*)&apNew[pWal->nWiData], 0,
49433            sizeof(u32*)*(iPage+1-pWal->nWiData));
49434     pWal->apWiData = apNew;
49435     pWal->nWiData = iPage+1;
49436   }
49437 
49438   /* Request a pointer to the required page from the VFS */
49439   if( pWal->apWiData[iPage]==0 ){
49440     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
49441       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
49442       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
49443     }else{
49444       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
49445           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
49446       );
49447       if( rc==SQLITE_READONLY ){
49448         pWal->readOnly |= WAL_SHM_RDONLY;
49449         rc = SQLITE_OK;
49450       }
49451     }
49452   }
49453 
49454   *ppPage = pWal->apWiData[iPage];
49455   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
49456   return rc;
49457 }
49458 
49459 /*
49460 ** Return a pointer to the WalCkptInfo structure in the wal-index.
49461 */
49462 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
49463   assert( pWal->nWiData>0 && pWal->apWiData[0] );
49464   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
49465 }
49466 
49467 /*
49468 ** Return a pointer to the WalIndexHdr structure in the wal-index.
49469 */
49470 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
49471   assert( pWal->nWiData>0 && pWal->apWiData[0] );
49472   return (volatile WalIndexHdr*)pWal->apWiData[0];
49473 }
49474 
49475 /*
49476 ** The argument to this macro must be of type u32. On a little-endian
49477 ** architecture, it returns the u32 value that results from interpreting
49478 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
49479 ** returns the value that would be produced by interpreting the 4 bytes
49480 ** of the input value as a little-endian integer.
49481 */
49482 #define BYTESWAP32(x) ( \
49483     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
49484   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
49485 )
49486 
49487 /*
49488 ** Generate or extend an 8 byte checksum based on the data in
49489 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
49490 ** initial values of 0 and 0 if aIn==NULL).
49491 **
49492 ** The checksum is written back into aOut[] before returning.
49493 **
49494 ** nByte must be a positive multiple of 8.
49495 */
49496 static void walChecksumBytes(
49497   int nativeCksum, /* True for native byte-order, false for non-native */
49498   u8 *a,           /* Content to be checksummed */
49499   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
49500   const u32 *aIn,  /* Initial checksum value input */
49501   u32 *aOut        /* OUT: Final checksum value output */
49502 ){
49503   u32 s1, s2;
49504   u32 *aData = (u32 *)a;
49505   u32 *aEnd = (u32 *)&a[nByte];
49506 
49507   if( aIn ){
49508     s1 = aIn[0];
49509     s2 = aIn[1];
49510   }else{
49511     s1 = s2 = 0;
49512   }
49513 
49514   assert( nByte>=8 );
49515   assert( (nByte&0x00000007)==0 );
49516 
49517   if( nativeCksum ){
49518     do {
49519       s1 += *aData++ + s2;
49520       s2 += *aData++ + s1;
49521     }while( aData<aEnd );
49522   }else{
49523     do {
49524       s1 += BYTESWAP32(aData[0]) + s2;
49525       s2 += BYTESWAP32(aData[1]) + s1;
49526       aData += 2;
49527     }while( aData<aEnd );
49528   }
49529 
49530   aOut[0] = s1;
49531   aOut[1] = s2;
49532 }
49533 
49534 static void walShmBarrier(Wal *pWal){
49535   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
49536     sqlite3OsShmBarrier(pWal->pDbFd);
49537   }
49538 }
49539 
49540 /*
49541 ** Write the header information in pWal->hdr into the wal-index.
49542 **
49543 ** The checksum on pWal->hdr is updated before it is written.
49544 */
49545 static void walIndexWriteHdr(Wal *pWal){
49546   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
49547   const int nCksum = offsetof(WalIndexHdr, aCksum);
49548 
49549   assert( pWal->writeLock );
49550   pWal->hdr.isInit = 1;
49551   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
49552   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
49553   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
49554   walShmBarrier(pWal);
49555   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
49556 }
49557 
49558 /*
49559 ** This function encodes a single frame header and writes it to a buffer
49560 ** supplied by the caller. A frame-header is made up of a series of
49561 ** 4-byte big-endian integers, as follows:
49562 **
49563 **     0: Page number.
49564 **     4: For commit records, the size of the database image in pages
49565 **        after the commit. For all other records, zero.
49566 **     8: Salt-1 (copied from the wal-header)
49567 **    12: Salt-2 (copied from the wal-header)
49568 **    16: Checksum-1.
49569 **    20: Checksum-2.
49570 */
49571 static void walEncodeFrame(
49572   Wal *pWal,                      /* The write-ahead log */
49573   u32 iPage,                      /* Database page number for frame */
49574   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
49575   u8 *aData,                      /* Pointer to page data */
49576   u8 *aFrame                      /* OUT: Write encoded frame here */
49577 ){
49578   int nativeCksum;                /* True for native byte-order checksums */
49579   u32 *aCksum = pWal->hdr.aFrameCksum;
49580   assert( WAL_FRAME_HDRSIZE==24 );
49581   sqlite3Put4byte(&aFrame[0], iPage);
49582   sqlite3Put4byte(&aFrame[4], nTruncate);
49583   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
49584 
49585   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
49586   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
49587   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
49588 
49589   sqlite3Put4byte(&aFrame[16], aCksum[0]);
49590   sqlite3Put4byte(&aFrame[20], aCksum[1]);
49591 }
49592 
49593 /*
49594 ** Check to see if the frame with header in aFrame[] and content
49595 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
49596 ** *pnTruncate and return true.  Return if the frame is not valid.
49597 */
49598 static int walDecodeFrame(
49599   Wal *pWal,                      /* The write-ahead log */
49600   u32 *piPage,                    /* OUT: Database page number for frame */
49601   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
49602   u8 *aData,                      /* Pointer to page data (for checksum) */
49603   u8 *aFrame                      /* Frame data */
49604 ){
49605   int nativeCksum;                /* True for native byte-order checksums */
49606   u32 *aCksum = pWal->hdr.aFrameCksum;
49607   u32 pgno;                       /* Page number of the frame */
49608   assert( WAL_FRAME_HDRSIZE==24 );
49609 
49610   /* A frame is only valid if the salt values in the frame-header
49611   ** match the salt values in the wal-header.
49612   */
49613   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
49614     return 0;
49615   }
49616 
49617   /* A frame is only valid if the page number is creater than zero.
49618   */
49619   pgno = sqlite3Get4byte(&aFrame[0]);
49620   if( pgno==0 ){
49621     return 0;
49622   }
49623 
49624   /* A frame is only valid if a checksum of the WAL header,
49625   ** all prior frams, the first 16 bytes of this frame-header,
49626   ** and the frame-data matches the checksum in the last 8
49627   ** bytes of this frame-header.
49628   */
49629   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
49630   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
49631   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
49632   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
49633    || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
49634   ){
49635     /* Checksum failed. */
49636     return 0;
49637   }
49638 
49639   /* If we reach this point, the frame is valid.  Return the page number
49640   ** and the new database size.
49641   */
49642   *piPage = pgno;
49643   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
49644   return 1;
49645 }
49646 
49647 
49648 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
49649 /*
49650 ** Names of locks.  This routine is used to provide debugging output and is not
49651 ** a part of an ordinary build.
49652 */
49653 static const char *walLockName(int lockIdx){
49654   if( lockIdx==WAL_WRITE_LOCK ){
49655     return "WRITE-LOCK";
49656   }else if( lockIdx==WAL_CKPT_LOCK ){
49657     return "CKPT-LOCK";
49658   }else if( lockIdx==WAL_RECOVER_LOCK ){
49659     return "RECOVER-LOCK";
49660   }else{
49661     static char zName[15];
49662     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
49663                      lockIdx-WAL_READ_LOCK(0));
49664     return zName;
49665   }
49666 }
49667 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
49668 
49669 
49670 /*
49671 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
49672 ** A lock cannot be moved directly between shared and exclusive - it must go
49673 ** through the unlocked state first.
49674 **
49675 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
49676 */
49677 static int walLockShared(Wal *pWal, int lockIdx){
49678   int rc;
49679   if( pWal->exclusiveMode ) return SQLITE_OK;
49680   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
49681                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
49682   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
49683             walLockName(lockIdx), rc ? "failed" : "ok"));
49684   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
49685   return rc;
49686 }
49687 static void walUnlockShared(Wal *pWal, int lockIdx){
49688   if( pWal->exclusiveMode ) return;
49689   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
49690                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
49691   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
49692 }
49693 static int walLockExclusive(Wal *pWal, int lockIdx, int n, int fBlock){
49694   int rc;
49695   if( pWal->exclusiveMode ) return SQLITE_OK;
49696   if( fBlock ) sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_WAL_BLOCK, 0);
49697   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
49698                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
49699   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
49700             walLockName(lockIdx), n, rc ? "failed" : "ok"));
49701   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
49702   return rc;
49703 }
49704 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
49705   if( pWal->exclusiveMode ) return;
49706   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
49707                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
49708   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
49709              walLockName(lockIdx), n));
49710 }
49711 
49712 /*
49713 ** Compute a hash on a page number.  The resulting hash value must land
49714 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
49715 ** the hash to the next value in the event of a collision.
49716 */
49717 static int walHash(u32 iPage){
49718   assert( iPage>0 );
49719   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
49720   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
49721 }
49722 static int walNextHash(int iPriorHash){
49723   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
49724 }
49725 
49726 /*
49727 ** Return pointers to the hash table and page number array stored on
49728 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
49729 ** numbered starting from 0.
49730 **
49731 ** Set output variable *paHash to point to the start of the hash table
49732 ** in the wal-index file. Set *piZero to one less than the frame
49733 ** number of the first frame indexed by this hash table. If a
49734 ** slot in the hash table is set to N, it refers to frame number
49735 ** (*piZero+N) in the log.
49736 **
49737 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
49738 ** first frame indexed by the hash table, frame (*piZero+1).
49739 */
49740 static int walHashGet(
49741   Wal *pWal,                      /* WAL handle */
49742   int iHash,                      /* Find the iHash'th table */
49743   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
49744   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
49745   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
49746 ){
49747   int rc;                         /* Return code */
49748   volatile u32 *aPgno;
49749 
49750   rc = walIndexPage(pWal, iHash, &aPgno);
49751   assert( rc==SQLITE_OK || iHash>0 );
49752 
49753   if( rc==SQLITE_OK ){
49754     u32 iZero;
49755     volatile ht_slot *aHash;
49756 
49757     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
49758     if( iHash==0 ){
49759       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
49760       iZero = 0;
49761     }else{
49762       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
49763     }
49764 
49765     *paPgno = &aPgno[-1];
49766     *paHash = aHash;
49767     *piZero = iZero;
49768   }
49769   return rc;
49770 }
49771 
49772 /*
49773 ** Return the number of the wal-index page that contains the hash-table
49774 ** and page-number array that contain entries corresponding to WAL frame
49775 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
49776 ** are numbered starting from 0.
49777 */
49778 static int walFramePage(u32 iFrame){
49779   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
49780   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
49781        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
49782        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
49783        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
49784        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
49785   );
49786   return iHash;
49787 }
49788 
49789 /*
49790 ** Return the page number associated with frame iFrame in this WAL.
49791 */
49792 static u32 walFramePgno(Wal *pWal, u32 iFrame){
49793   int iHash = walFramePage(iFrame);
49794   if( iHash==0 ){
49795     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
49796   }
49797   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
49798 }
49799 
49800 /*
49801 ** Remove entries from the hash table that point to WAL slots greater
49802 ** than pWal->hdr.mxFrame.
49803 **
49804 ** This function is called whenever pWal->hdr.mxFrame is decreased due
49805 ** to a rollback or savepoint.
49806 **
49807 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
49808 ** updated.  Any later hash tables will be automatically cleared when
49809 ** pWal->hdr.mxFrame advances to the point where those hash tables are
49810 ** actually needed.
49811 */
49812 static void walCleanupHash(Wal *pWal){
49813   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
49814   volatile u32 *aPgno = 0;        /* Page number array for hash table */
49815   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
49816   int iLimit = 0;                 /* Zero values greater than this */
49817   int nByte;                      /* Number of bytes to zero in aPgno[] */
49818   int i;                          /* Used to iterate through aHash[] */
49819 
49820   assert( pWal->writeLock );
49821   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
49822   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
49823   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
49824 
49825   if( pWal->hdr.mxFrame==0 ) return;
49826 
49827   /* Obtain pointers to the hash-table and page-number array containing
49828   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
49829   ** that the page said hash-table and array reside on is already mapped.
49830   */
49831   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
49832   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
49833   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
49834 
49835   /* Zero all hash-table entries that correspond to frame numbers greater
49836   ** than pWal->hdr.mxFrame.
49837   */
49838   iLimit = pWal->hdr.mxFrame - iZero;
49839   assert( iLimit>0 );
49840   for(i=0; i<HASHTABLE_NSLOT; i++){
49841     if( aHash[i]>iLimit ){
49842       aHash[i] = 0;
49843     }
49844   }
49845 
49846   /* Zero the entries in the aPgno array that correspond to frames with
49847   ** frame numbers greater than pWal->hdr.mxFrame.
49848   */
49849   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
49850   memset((void *)&aPgno[iLimit+1], 0, nByte);
49851 
49852 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
49853   /* Verify that the every entry in the mapping region is still reachable
49854   ** via the hash table even after the cleanup.
49855   */
49856   if( iLimit ){
49857     int i;           /* Loop counter */
49858     int iKey;        /* Hash key */
49859     for(i=1; i<=iLimit; i++){
49860       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
49861         if( aHash[iKey]==i ) break;
49862       }
49863       assert( aHash[iKey]==i );
49864     }
49865   }
49866 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
49867 }
49868 
49869 
49870 /*
49871 ** Set an entry in the wal-index that will map database page number
49872 ** pPage into WAL frame iFrame.
49873 */
49874 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
49875   int rc;                         /* Return code */
49876   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
49877   volatile u32 *aPgno = 0;        /* Page number array */
49878   volatile ht_slot *aHash = 0;    /* Hash table */
49879 
49880   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
49881 
49882   /* Assuming the wal-index file was successfully mapped, populate the
49883   ** page number array and hash table entry.
49884   */
49885   if( rc==SQLITE_OK ){
49886     int iKey;                     /* Hash table key */
49887     int idx;                      /* Value to write to hash-table slot */
49888     int nCollide;                 /* Number of hash collisions */
49889 
49890     idx = iFrame - iZero;
49891     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
49892 
49893     /* If this is the first entry to be added to this hash-table, zero the
49894     ** entire hash table and aPgno[] array before proceeding.
49895     */
49896     if( idx==1 ){
49897       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
49898       memset((void*)&aPgno[1], 0, nByte);
49899     }
49900 
49901     /* If the entry in aPgno[] is already set, then the previous writer
49902     ** must have exited unexpectedly in the middle of a transaction (after
49903     ** writing one or more dirty pages to the WAL to free up memory).
49904     ** Remove the remnants of that writers uncommitted transaction from
49905     ** the hash-table before writing any new entries.
49906     */
49907     if( aPgno[idx] ){
49908       walCleanupHash(pWal);
49909       assert( !aPgno[idx] );
49910     }
49911 
49912     /* Write the aPgno[] array entry and the hash-table slot. */
49913     nCollide = idx;
49914     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
49915       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
49916     }
49917     aPgno[idx] = iPage;
49918     aHash[iKey] = (ht_slot)idx;
49919 
49920 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
49921     /* Verify that the number of entries in the hash table exactly equals
49922     ** the number of entries in the mapping region.
49923     */
49924     {
49925       int i;           /* Loop counter */
49926       int nEntry = 0;  /* Number of entries in the hash table */
49927       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
49928       assert( nEntry==idx );
49929     }
49930 
49931     /* Verify that the every entry in the mapping region is reachable
49932     ** via the hash table.  This turns out to be a really, really expensive
49933     ** thing to check, so only do this occasionally - not on every
49934     ** iteration.
49935     */
49936     if( (idx&0x3ff)==0 ){
49937       int i;           /* Loop counter */
49938       for(i=1; i<=idx; i++){
49939         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
49940           if( aHash[iKey]==i ) break;
49941         }
49942         assert( aHash[iKey]==i );
49943       }
49944     }
49945 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
49946   }
49947 
49948 
49949   return rc;
49950 }
49951 
49952 
49953 /*
49954 ** Recover the wal-index by reading the write-ahead log file.
49955 **
49956 ** This routine first tries to establish an exclusive lock on the
49957 ** wal-index to prevent other threads/processes from doing anything
49958 ** with the WAL or wal-index while recovery is running.  The
49959 ** WAL_RECOVER_LOCK is also held so that other threads will know
49960 ** that this thread is running recovery.  If unable to establish
49961 ** the necessary locks, this routine returns SQLITE_BUSY.
49962 */
49963 static int walIndexRecover(Wal *pWal){
49964   int rc;                         /* Return Code */
49965   i64 nSize;                      /* Size of log file */
49966   u32 aFrameCksum[2] = {0, 0};
49967   int iLock;                      /* Lock offset to lock for checkpoint */
49968   int nLock;                      /* Number of locks to hold */
49969 
49970   /* Obtain an exclusive lock on all byte in the locking range not already
49971   ** locked by the caller. The caller is guaranteed to have locked the
49972   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
49973   ** If successful, the same bytes that are locked here are unlocked before
49974   ** this function returns.
49975   */
49976   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
49977   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
49978   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
49979   assert( pWal->writeLock );
49980   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
49981   nLock = SQLITE_SHM_NLOCK - iLock;
49982   rc = walLockExclusive(pWal, iLock, nLock, 0);
49983   if( rc ){
49984     return rc;
49985   }
49986   WALTRACE(("WAL%p: recovery begin...\n", pWal));
49987 
49988   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
49989 
49990   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
49991   if( rc!=SQLITE_OK ){
49992     goto recovery_error;
49993   }
49994 
49995   if( nSize>WAL_HDRSIZE ){
49996     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
49997     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
49998     int szFrame;                  /* Number of bytes in buffer aFrame[] */
49999     u8 *aData;                    /* Pointer to data part of aFrame buffer */
50000     int iFrame;                   /* Index of last frame read */
50001     i64 iOffset;                  /* Next offset to read from log file */
50002     int szPage;                   /* Page size according to the log */
50003     u32 magic;                    /* Magic value read from WAL header */
50004     u32 version;                  /* Magic value read from WAL header */
50005     int isValid;                  /* True if this frame is valid */
50006 
50007     /* Read in the WAL header. */
50008     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
50009     if( rc!=SQLITE_OK ){
50010       goto recovery_error;
50011     }
50012 
50013     /* If the database page size is not a power of two, or is greater than
50014     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
50015     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
50016     ** WAL file.
50017     */
50018     magic = sqlite3Get4byte(&aBuf[0]);
50019     szPage = sqlite3Get4byte(&aBuf[8]);
50020     if( (magic&0xFFFFFFFE)!=WAL_MAGIC
50021      || szPage&(szPage-1)
50022      || szPage>SQLITE_MAX_PAGE_SIZE
50023      || szPage<512
50024     ){
50025       goto finished;
50026     }
50027     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
50028     pWal->szPage = szPage;
50029     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
50030     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
50031 
50032     /* Verify that the WAL header checksum is correct */
50033     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
50034         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
50035     );
50036     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
50037      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
50038     ){
50039       goto finished;
50040     }
50041 
50042     /* Verify that the version number on the WAL format is one that
50043     ** are able to understand */
50044     version = sqlite3Get4byte(&aBuf[4]);
50045     if( version!=WAL_MAX_VERSION ){
50046       rc = SQLITE_CANTOPEN_BKPT;
50047       goto finished;
50048     }
50049 
50050     /* Malloc a buffer to read frames into. */
50051     szFrame = szPage + WAL_FRAME_HDRSIZE;
50052     aFrame = (u8 *)sqlite3_malloc64(szFrame);
50053     if( !aFrame ){
50054       rc = SQLITE_NOMEM;
50055       goto recovery_error;
50056     }
50057     aData = &aFrame[WAL_FRAME_HDRSIZE];
50058 
50059     /* Read all frames from the log file. */
50060     iFrame = 0;
50061     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
50062       u32 pgno;                   /* Database page number for frame */
50063       u32 nTruncate;              /* dbsize field from frame header */
50064 
50065       /* Read and decode the next log frame. */
50066       iFrame++;
50067       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
50068       if( rc!=SQLITE_OK ) break;
50069       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
50070       if( !isValid ) break;
50071       rc = walIndexAppend(pWal, iFrame, pgno);
50072       if( rc!=SQLITE_OK ) break;
50073 
50074       /* If nTruncate is non-zero, this is a commit record. */
50075       if( nTruncate ){
50076         pWal->hdr.mxFrame = iFrame;
50077         pWal->hdr.nPage = nTruncate;
50078         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
50079         testcase( szPage<=32768 );
50080         testcase( szPage>=65536 );
50081         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
50082         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
50083       }
50084     }
50085 
50086     sqlite3_free(aFrame);
50087   }
50088 
50089 finished:
50090   if( rc==SQLITE_OK ){
50091     volatile WalCkptInfo *pInfo;
50092     int i;
50093     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
50094     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
50095     walIndexWriteHdr(pWal);
50096 
50097     /* Reset the checkpoint-header. This is safe because this thread is
50098     ** currently holding locks that exclude all other readers, writers and
50099     ** checkpointers.
50100     */
50101     pInfo = walCkptInfo(pWal);
50102     pInfo->nBackfill = 0;
50103     pInfo->aReadMark[0] = 0;
50104     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
50105     if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
50106 
50107     /* If more than one frame was recovered from the log file, report an
50108     ** event via sqlite3_log(). This is to help with identifying performance
50109     ** problems caused by applications routinely shutting down without
50110     ** checkpointing the log file.
50111     */
50112     if( pWal->hdr.nPage ){
50113       sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
50114           "recovered %d frames from WAL file %s",
50115           pWal->hdr.mxFrame, pWal->zWalName
50116       );
50117     }
50118   }
50119 
50120 recovery_error:
50121   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
50122   walUnlockExclusive(pWal, iLock, nLock);
50123   return rc;
50124 }
50125 
50126 /*
50127 ** Close an open wal-index.
50128 */
50129 static void walIndexClose(Wal *pWal, int isDelete){
50130   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
50131     int i;
50132     for(i=0; i<pWal->nWiData; i++){
50133       sqlite3_free((void *)pWal->apWiData[i]);
50134       pWal->apWiData[i] = 0;
50135     }
50136   }else{
50137     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
50138   }
50139 }
50140 
50141 /*
50142 ** Open a connection to the WAL file zWalName. The database file must
50143 ** already be opened on connection pDbFd. The buffer that zWalName points
50144 ** to must remain valid for the lifetime of the returned Wal* handle.
50145 **
50146 ** A SHARED lock should be held on the database file when this function
50147 ** is called. The purpose of this SHARED lock is to prevent any other
50148 ** client from unlinking the WAL or wal-index file. If another process
50149 ** were to do this just after this client opened one of these files, the
50150 ** system would be badly broken.
50151 **
50152 ** If the log file is successfully opened, SQLITE_OK is returned and
50153 ** *ppWal is set to point to a new WAL handle. If an error occurs,
50154 ** an SQLite error code is returned and *ppWal is left unmodified.
50155 */
50156 SQLITE_PRIVATE int sqlite3WalOpen(
50157   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
50158   sqlite3_file *pDbFd,            /* The open database file */
50159   const char *zWalName,           /* Name of the WAL file */
50160   int bNoShm,                     /* True to run in heap-memory mode */
50161   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
50162   Wal **ppWal                     /* OUT: Allocated Wal handle */
50163 ){
50164   int rc;                         /* Return Code */
50165   Wal *pRet;                      /* Object to allocate and return */
50166   int flags;                      /* Flags passed to OsOpen() */
50167 
50168   assert( zWalName && zWalName[0] );
50169   assert( pDbFd );
50170 
50171   /* In the amalgamation, the os_unix.c and os_win.c source files come before
50172   ** this source file.  Verify that the #defines of the locking byte offsets
50173   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
50174   */
50175 #ifdef WIN_SHM_BASE
50176   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
50177 #endif
50178 #ifdef UNIX_SHM_BASE
50179   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
50180 #endif
50181 
50182 
50183   /* Allocate an instance of struct Wal to return. */
50184   *ppWal = 0;
50185   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
50186   if( !pRet ){
50187     return SQLITE_NOMEM;
50188   }
50189 
50190   pRet->pVfs = pVfs;
50191   pRet->pWalFd = (sqlite3_file *)&pRet[1];
50192   pRet->pDbFd = pDbFd;
50193   pRet->readLock = -1;
50194   pRet->mxWalSize = mxWalSize;
50195   pRet->zWalName = zWalName;
50196   pRet->syncHeader = 1;
50197   pRet->padToSectorBoundary = 1;
50198   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
50199 
50200   /* Open file handle on the write-ahead log file. */
50201   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
50202   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
50203   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
50204     pRet->readOnly = WAL_RDONLY;
50205   }
50206 
50207   if( rc!=SQLITE_OK ){
50208     walIndexClose(pRet, 0);
50209     sqlite3OsClose(pRet->pWalFd);
50210     sqlite3_free(pRet);
50211   }else{
50212     int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
50213     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
50214     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
50215       pRet->padToSectorBoundary = 0;
50216     }
50217     *ppWal = pRet;
50218     WALTRACE(("WAL%d: opened\n", pRet));
50219   }
50220   return rc;
50221 }
50222 
50223 /*
50224 ** Change the size to which the WAL file is trucated on each reset.
50225 */
50226 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
50227   if( pWal ) pWal->mxWalSize = iLimit;
50228 }
50229 
50230 /*
50231 ** Find the smallest page number out of all pages held in the WAL that
50232 ** has not been returned by any prior invocation of this method on the
50233 ** same WalIterator object.   Write into *piFrame the frame index where
50234 ** that page was last written into the WAL.  Write into *piPage the page
50235 ** number.
50236 **
50237 ** Return 0 on success.  If there are no pages in the WAL with a page
50238 ** number larger than *piPage, then return 1.
50239 */
50240 static int walIteratorNext(
50241   WalIterator *p,               /* Iterator */
50242   u32 *piPage,                  /* OUT: The page number of the next page */
50243   u32 *piFrame                  /* OUT: Wal frame index of next page */
50244 ){
50245   u32 iMin;                     /* Result pgno must be greater than iMin */
50246   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
50247   int i;                        /* For looping through segments */
50248 
50249   iMin = p->iPrior;
50250   assert( iMin<0xffffffff );
50251   for(i=p->nSegment-1; i>=0; i--){
50252     struct WalSegment *pSegment = &p->aSegment[i];
50253     while( pSegment->iNext<pSegment->nEntry ){
50254       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
50255       if( iPg>iMin ){
50256         if( iPg<iRet ){
50257           iRet = iPg;
50258           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
50259         }
50260         break;
50261       }
50262       pSegment->iNext++;
50263     }
50264   }
50265 
50266   *piPage = p->iPrior = iRet;
50267   return (iRet==0xFFFFFFFF);
50268 }
50269 
50270 /*
50271 ** This function merges two sorted lists into a single sorted list.
50272 **
50273 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
50274 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
50275 ** is guaranteed for all J<K:
50276 **
50277 **        aContent[aLeft[J]] < aContent[aLeft[K]]
50278 **        aContent[aRight[J]] < aContent[aRight[K]]
50279 **
50280 ** This routine overwrites aRight[] with a new (probably longer) sequence
50281 ** of indices such that the aRight[] contains every index that appears in
50282 ** either aLeft[] or the old aRight[] and such that the second condition
50283 ** above is still met.
50284 **
50285 ** The aContent[aLeft[X]] values will be unique for all X.  And the
50286 ** aContent[aRight[X]] values will be unique too.  But there might be
50287 ** one or more combinations of X and Y such that
50288 **
50289 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
50290 **
50291 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
50292 */
50293 static void walMerge(
50294   const u32 *aContent,            /* Pages in wal - keys for the sort */
50295   ht_slot *aLeft,                 /* IN: Left hand input list */
50296   int nLeft,                      /* IN: Elements in array *paLeft */
50297   ht_slot **paRight,              /* IN/OUT: Right hand input list */
50298   int *pnRight,                   /* IN/OUT: Elements in *paRight */
50299   ht_slot *aTmp                   /* Temporary buffer */
50300 ){
50301   int iLeft = 0;                  /* Current index in aLeft */
50302   int iRight = 0;                 /* Current index in aRight */
50303   int iOut = 0;                   /* Current index in output buffer */
50304   int nRight = *pnRight;
50305   ht_slot *aRight = *paRight;
50306 
50307   assert( nLeft>0 && nRight>0 );
50308   while( iRight<nRight || iLeft<nLeft ){
50309     ht_slot logpage;
50310     Pgno dbpage;
50311 
50312     if( (iLeft<nLeft)
50313      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
50314     ){
50315       logpage = aLeft[iLeft++];
50316     }else{
50317       logpage = aRight[iRight++];
50318     }
50319     dbpage = aContent[logpage];
50320 
50321     aTmp[iOut++] = logpage;
50322     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
50323 
50324     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
50325     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
50326   }
50327 
50328   *paRight = aLeft;
50329   *pnRight = iOut;
50330   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
50331 }
50332 
50333 /*
50334 ** Sort the elements in list aList using aContent[] as the sort key.
50335 ** Remove elements with duplicate keys, preferring to keep the
50336 ** larger aList[] values.
50337 **
50338 ** The aList[] entries are indices into aContent[].  The values in
50339 ** aList[] are to be sorted so that for all J<K:
50340 **
50341 **      aContent[aList[J]] < aContent[aList[K]]
50342 **
50343 ** For any X and Y such that
50344 **
50345 **      aContent[aList[X]] == aContent[aList[Y]]
50346 **
50347 ** Keep the larger of the two values aList[X] and aList[Y] and discard
50348 ** the smaller.
50349 */
50350 static void walMergesort(
50351   const u32 *aContent,            /* Pages in wal */
50352   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
50353   ht_slot *aList,                 /* IN/OUT: List to sort */
50354   int *pnList                     /* IN/OUT: Number of elements in aList[] */
50355 ){
50356   struct Sublist {
50357     int nList;                    /* Number of elements in aList */
50358     ht_slot *aList;               /* Pointer to sub-list content */
50359   };
50360 
50361   const int nList = *pnList;      /* Size of input list */
50362   int nMerge = 0;                 /* Number of elements in list aMerge */
50363   ht_slot *aMerge = 0;            /* List to be merged */
50364   int iList;                      /* Index into input list */
50365   int iSub = 0;                   /* Index into aSub array */
50366   struct Sublist aSub[13];        /* Array of sub-lists */
50367 
50368   memset(aSub, 0, sizeof(aSub));
50369   assert( nList<=HASHTABLE_NPAGE && nList>0 );
50370   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
50371 
50372   for(iList=0; iList<nList; iList++){
50373     nMerge = 1;
50374     aMerge = &aList[iList];
50375     for(iSub=0; iList & (1<<iSub); iSub++){
50376       struct Sublist *p = &aSub[iSub];
50377       assert( p->aList && p->nList<=(1<<iSub) );
50378       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
50379       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
50380     }
50381     aSub[iSub].aList = aMerge;
50382     aSub[iSub].nList = nMerge;
50383   }
50384 
50385   for(iSub++; iSub<ArraySize(aSub); iSub++){
50386     if( nList & (1<<iSub) ){
50387       struct Sublist *p = &aSub[iSub];
50388       assert( p->nList<=(1<<iSub) );
50389       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
50390       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
50391     }
50392   }
50393   assert( aMerge==aList );
50394   *pnList = nMerge;
50395 
50396 #ifdef SQLITE_DEBUG
50397   {
50398     int i;
50399     for(i=1; i<*pnList; i++){
50400       assert( aContent[aList[i]] > aContent[aList[i-1]] );
50401     }
50402   }
50403 #endif
50404 }
50405 
50406 /*
50407 ** Free an iterator allocated by walIteratorInit().
50408 */
50409 static void walIteratorFree(WalIterator *p){
50410   sqlite3_free(p);
50411 }
50412 
50413 /*
50414 ** Construct a WalInterator object that can be used to loop over all
50415 ** pages in the WAL in ascending order. The caller must hold the checkpoint
50416 ** lock.
50417 **
50418 ** On success, make *pp point to the newly allocated WalInterator object
50419 ** return SQLITE_OK. Otherwise, return an error code. If this routine
50420 ** returns an error, the value of *pp is undefined.
50421 **
50422 ** The calling routine should invoke walIteratorFree() to destroy the
50423 ** WalIterator object when it has finished with it.
50424 */
50425 static int walIteratorInit(Wal *pWal, WalIterator **pp){
50426   WalIterator *p;                 /* Return value */
50427   int nSegment;                   /* Number of segments to merge */
50428   u32 iLast;                      /* Last frame in log */
50429   int nByte;                      /* Number of bytes to allocate */
50430   int i;                          /* Iterator variable */
50431   ht_slot *aTmp;                  /* Temp space used by merge-sort */
50432   int rc = SQLITE_OK;             /* Return Code */
50433 
50434   /* This routine only runs while holding the checkpoint lock. And
50435   ** it only runs if there is actually content in the log (mxFrame>0).
50436   */
50437   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
50438   iLast = pWal->hdr.mxFrame;
50439 
50440   /* Allocate space for the WalIterator object. */
50441   nSegment = walFramePage(iLast) + 1;
50442   nByte = sizeof(WalIterator)
50443         + (nSegment-1)*sizeof(struct WalSegment)
50444         + iLast*sizeof(ht_slot);
50445   p = (WalIterator *)sqlite3_malloc64(nByte);
50446   if( !p ){
50447     return SQLITE_NOMEM;
50448   }
50449   memset(p, 0, nByte);
50450   p->nSegment = nSegment;
50451 
50452   /* Allocate temporary space used by the merge-sort routine. This block
50453   ** of memory will be freed before this function returns.
50454   */
50455   aTmp = (ht_slot *)sqlite3_malloc64(
50456       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
50457   );
50458   if( !aTmp ){
50459     rc = SQLITE_NOMEM;
50460   }
50461 
50462   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
50463     volatile ht_slot *aHash;
50464     u32 iZero;
50465     volatile u32 *aPgno;
50466 
50467     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
50468     if( rc==SQLITE_OK ){
50469       int j;                      /* Counter variable */
50470       int nEntry;                 /* Number of entries in this segment */
50471       ht_slot *aIndex;            /* Sorted index for this segment */
50472 
50473       aPgno++;
50474       if( (i+1)==nSegment ){
50475         nEntry = (int)(iLast - iZero);
50476       }else{
50477         nEntry = (int)((u32*)aHash - (u32*)aPgno);
50478       }
50479       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
50480       iZero++;
50481 
50482       for(j=0; j<nEntry; j++){
50483         aIndex[j] = (ht_slot)j;
50484       }
50485       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
50486       p->aSegment[i].iZero = iZero;
50487       p->aSegment[i].nEntry = nEntry;
50488       p->aSegment[i].aIndex = aIndex;
50489       p->aSegment[i].aPgno = (u32 *)aPgno;
50490     }
50491   }
50492   sqlite3_free(aTmp);
50493 
50494   if( rc!=SQLITE_OK ){
50495     walIteratorFree(p);
50496   }
50497   *pp = p;
50498   return rc;
50499 }
50500 
50501 /*
50502 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
50503 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
50504 ** busy-handler function. Invoke it and retry the lock until either the
50505 ** lock is successfully obtained or the busy-handler returns 0.
50506 */
50507 static int walBusyLock(
50508   Wal *pWal,                      /* WAL connection */
50509   int (*xBusy)(void*),            /* Function to call when busy */
50510   void *pBusyArg,                 /* Context argument for xBusyHandler */
50511   int lockIdx,                    /* Offset of first byte to lock */
50512   int n                           /* Number of bytes to lock */
50513 ){
50514   int rc;
50515   do {
50516     rc = walLockExclusive(pWal, lockIdx, n, 0);
50517   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
50518   return rc;
50519 }
50520 
50521 /*
50522 ** The cache of the wal-index header must be valid to call this function.
50523 ** Return the page-size in bytes used by the database.
50524 */
50525 static int walPagesize(Wal *pWal){
50526   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
50527 }
50528 
50529 /*
50530 ** The following is guaranteed when this function is called:
50531 **
50532 **   a) the WRITER lock is held,
50533 **   b) the entire log file has been checkpointed, and
50534 **   c) any existing readers are reading exclusively from the database
50535 **      file - there are no readers that may attempt to read a frame from
50536 **      the log file.
50537 **
50538 ** This function updates the shared-memory structures so that the next
50539 ** client to write to the database (which may be this one) does so by
50540 ** writing frames into the start of the log file.
50541 **
50542 ** The value of parameter salt1 is used as the aSalt[1] value in the
50543 ** new wal-index header. It should be passed a pseudo-random value (i.e.
50544 ** one obtained from sqlite3_randomness()).
50545 */
50546 static void walRestartHdr(Wal *pWal, u32 salt1){
50547   volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
50548   int i;                          /* Loop counter */
50549   u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */
50550   pWal->nCkpt++;
50551   pWal->hdr.mxFrame = 0;
50552   sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
50553   memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
50554   walIndexWriteHdr(pWal);
50555   pInfo->nBackfill = 0;
50556   pInfo->aReadMark[1] = 0;
50557   for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
50558   assert( pInfo->aReadMark[0]==0 );
50559 }
50560 
50561 /*
50562 ** Copy as much content as we can from the WAL back into the database file
50563 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
50564 **
50565 ** The amount of information copies from WAL to database might be limited
50566 ** by active readers.  This routine will never overwrite a database page
50567 ** that a concurrent reader might be using.
50568 **
50569 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
50570 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
50571 ** checkpoints are always run by a background thread or background
50572 ** process, foreground threads will never block on a lengthy fsync call.
50573 **
50574 ** Fsync is called on the WAL before writing content out of the WAL and
50575 ** into the database.  This ensures that if the new content is persistent
50576 ** in the WAL and can be recovered following a power-loss or hard reset.
50577 **
50578 ** Fsync is also called on the database file if (and only if) the entire
50579 ** WAL content is copied into the database file.  This second fsync makes
50580 ** it safe to delete the WAL since the new content will persist in the
50581 ** database file.
50582 **
50583 ** This routine uses and updates the nBackfill field of the wal-index header.
50584 ** This is the only routine that will increase the value of nBackfill.
50585 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
50586 ** its value.)
50587 **
50588 ** The caller must be holding sufficient locks to ensure that no other
50589 ** checkpoint is running (in any other thread or process) at the same
50590 ** time.
50591 */
50592 static int walCheckpoint(
50593   Wal *pWal,                      /* Wal connection */
50594   int eMode,                      /* One of PASSIVE, FULL or RESTART */
50595   int (*xBusy)(void*),            /* Function to call when busy */
50596   void *pBusyArg,                 /* Context argument for xBusyHandler */
50597   int sync_flags,                 /* Flags for OsSync() (or 0) */
50598   u8 *zBuf                        /* Temporary buffer to use */
50599 ){
50600   int rc = SQLITE_OK;             /* Return code */
50601   int szPage;                     /* Database page-size */
50602   WalIterator *pIter = 0;         /* Wal iterator context */
50603   u32 iDbpage = 0;                /* Next database page to write */
50604   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
50605   u32 mxSafeFrame;                /* Max frame that can be backfilled */
50606   u32 mxPage;                     /* Max database page to write */
50607   int i;                          /* Loop counter */
50608   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
50609 
50610   szPage = walPagesize(pWal);
50611   testcase( szPage<=32768 );
50612   testcase( szPage>=65536 );
50613   pInfo = walCkptInfo(pWal);
50614   if( pInfo->nBackfill<pWal->hdr.mxFrame ){
50615 
50616     /* Allocate the iterator */
50617     rc = walIteratorInit(pWal, &pIter);
50618     if( rc!=SQLITE_OK ){
50619       return rc;
50620     }
50621     assert( pIter );
50622 
50623     /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
50624     ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
50625     assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
50626 
50627     /* Compute in mxSafeFrame the index of the last frame of the WAL that is
50628     ** safe to write into the database.  Frames beyond mxSafeFrame might
50629     ** overwrite database pages that are in use by active readers and thus
50630     ** cannot be backfilled from the WAL.
50631     */
50632     mxSafeFrame = pWal->hdr.mxFrame;
50633     mxPage = pWal->hdr.nPage;
50634     for(i=1; i<WAL_NREADER; i++){
50635       /* Thread-sanitizer reports that the following is an unsafe read,
50636       ** as some other thread may be in the process of updating the value
50637       ** of the aReadMark[] slot. The assumption here is that if that is
50638       ** happening, the other client may only be increasing the value,
50639       ** not decreasing it. So assuming either that either the "old" or
50640       ** "new" version of the value is read, and not some arbitrary value
50641       ** that would never be written by a real client, things are still
50642       ** safe.  */
50643       u32 y = pInfo->aReadMark[i];
50644       if( mxSafeFrame>y ){
50645         assert( y<=pWal->hdr.mxFrame );
50646         rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
50647         if( rc==SQLITE_OK ){
50648           pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
50649           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
50650         }else if( rc==SQLITE_BUSY ){
50651           mxSafeFrame = y;
50652           xBusy = 0;
50653         }else{
50654           goto walcheckpoint_out;
50655         }
50656       }
50657     }
50658 
50659     if( pInfo->nBackfill<mxSafeFrame
50660      && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
50661     ){
50662       i64 nSize;                    /* Current size of database file */
50663       u32 nBackfill = pInfo->nBackfill;
50664 
50665       /* Sync the WAL to disk */
50666       if( sync_flags ){
50667         rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
50668       }
50669 
50670       /* If the database may grow as a result of this checkpoint, hint
50671       ** about the eventual size of the db file to the VFS layer.
50672       */
50673       if( rc==SQLITE_OK ){
50674         i64 nReq = ((i64)mxPage * szPage);
50675         rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
50676         if( rc==SQLITE_OK && nSize<nReq ){
50677           sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
50678         }
50679       }
50680 
50681 
50682       /* Iterate through the contents of the WAL, copying data to the db file */
50683       while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
50684         i64 iOffset;
50685         assert( walFramePgno(pWal, iFrame)==iDbpage );
50686         if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
50687           continue;
50688         }
50689         iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
50690         /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
50691         rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
50692         if( rc!=SQLITE_OK ) break;
50693         iOffset = (iDbpage-1)*(i64)szPage;
50694         testcase( IS_BIG_INT(iOffset) );
50695         rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
50696         if( rc!=SQLITE_OK ) break;
50697       }
50698 
50699       /* If work was actually accomplished... */
50700       if( rc==SQLITE_OK ){
50701         if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
50702           i64 szDb = pWal->hdr.nPage*(i64)szPage;
50703           testcase( IS_BIG_INT(szDb) );
50704           rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
50705           if( rc==SQLITE_OK && sync_flags ){
50706             rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
50707           }
50708         }
50709         if( rc==SQLITE_OK ){
50710           pInfo->nBackfill = mxSafeFrame;
50711         }
50712       }
50713 
50714       /* Release the reader lock held while backfilling */
50715       walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
50716     }
50717 
50718     if( rc==SQLITE_BUSY ){
50719       /* Reset the return code so as not to report a checkpoint failure
50720       ** just because there are active readers.  */
50721       rc = SQLITE_OK;
50722     }
50723   }
50724 
50725   /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
50726   ** entire wal file has been copied into the database file, then block
50727   ** until all readers have finished using the wal file. This ensures that
50728   ** the next process to write to the database restarts the wal file.
50729   */
50730   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
50731     assert( pWal->writeLock );
50732     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
50733       rc = SQLITE_BUSY;
50734     }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
50735       u32 salt1;
50736       sqlite3_randomness(4, &salt1);
50737       assert( pInfo->nBackfill==pWal->hdr.mxFrame );
50738       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
50739       if( rc==SQLITE_OK ){
50740         if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
50741           /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
50742           ** SQLITE_CHECKPOINT_RESTART with the addition that it also
50743           ** truncates the log file to zero bytes just prior to a
50744           ** successful return.
50745           **
50746           ** In theory, it might be safe to do this without updating the
50747           ** wal-index header in shared memory, as all subsequent reader or
50748           ** writer clients should see that the entire log file has been
50749           ** checkpointed and behave accordingly. This seems unsafe though,
50750           ** as it would leave the system in a state where the contents of
50751           ** the wal-index header do not match the contents of the
50752           ** file-system. To avoid this, update the wal-index header to
50753           ** indicate that the log file contains zero valid frames.  */
50754           walRestartHdr(pWal, salt1);
50755           rc = sqlite3OsTruncate(pWal->pWalFd, 0);
50756         }
50757         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
50758       }
50759     }
50760   }
50761 
50762  walcheckpoint_out:
50763   walIteratorFree(pIter);
50764   return rc;
50765 }
50766 
50767 /*
50768 ** If the WAL file is currently larger than nMax bytes in size, truncate
50769 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
50770 */
50771 static void walLimitSize(Wal *pWal, i64 nMax){
50772   i64 sz;
50773   int rx;
50774   sqlite3BeginBenignMalloc();
50775   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
50776   if( rx==SQLITE_OK && (sz > nMax ) ){
50777     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
50778   }
50779   sqlite3EndBenignMalloc();
50780   if( rx ){
50781     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
50782   }
50783 }
50784 
50785 /*
50786 ** Close a connection to a log file.
50787 */
50788 SQLITE_PRIVATE int sqlite3WalClose(
50789   Wal *pWal,                      /* Wal to close */
50790   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
50791   int nBuf,
50792   u8 *zBuf                        /* Buffer of at least nBuf bytes */
50793 ){
50794   int rc = SQLITE_OK;
50795   if( pWal ){
50796     int isDelete = 0;             /* True to unlink wal and wal-index files */
50797 
50798     /* If an EXCLUSIVE lock can be obtained on the database file (using the
50799     ** ordinary, rollback-mode locking methods, this guarantees that the
50800     ** connection associated with this log file is the only connection to
50801     ** the database. In this case checkpoint the database and unlink both
50802     ** the wal and wal-index files.
50803     **
50804     ** The EXCLUSIVE lock is not released before returning.
50805     */
50806     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
50807     if( rc==SQLITE_OK ){
50808       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
50809         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
50810       }
50811       rc = sqlite3WalCheckpoint(
50812           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
50813       );
50814       if( rc==SQLITE_OK ){
50815         int bPersist = -1;
50816         sqlite3OsFileControlHint(
50817             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
50818         );
50819         if( bPersist!=1 ){
50820           /* Try to delete the WAL file if the checkpoint completed and
50821           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
50822           ** mode (!bPersist) */
50823           isDelete = 1;
50824         }else if( pWal->mxWalSize>=0 ){
50825           /* Try to truncate the WAL file to zero bytes if the checkpoint
50826           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
50827           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
50828           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
50829           ** to zero bytes as truncating to the journal_size_limit might
50830           ** leave a corrupt WAL file on disk. */
50831           walLimitSize(pWal, 0);
50832         }
50833       }
50834     }
50835 
50836     walIndexClose(pWal, isDelete);
50837     sqlite3OsClose(pWal->pWalFd);
50838     if( isDelete ){
50839       sqlite3BeginBenignMalloc();
50840       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
50841       sqlite3EndBenignMalloc();
50842     }
50843     WALTRACE(("WAL%p: closed\n", pWal));
50844     sqlite3_free((void *)pWal->apWiData);
50845     sqlite3_free(pWal);
50846   }
50847   return rc;
50848 }
50849 
50850 /*
50851 ** Try to read the wal-index header.  Return 0 on success and 1 if
50852 ** there is a problem.
50853 **
50854 ** The wal-index is in shared memory.  Another thread or process might
50855 ** be writing the header at the same time this procedure is trying to
50856 ** read it, which might result in inconsistency.  A dirty read is detected
50857 ** by verifying that both copies of the header are the same and also by
50858 ** a checksum on the header.
50859 **
50860 ** If and only if the read is consistent and the header is different from
50861 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
50862 ** and *pChanged is set to 1.
50863 **
50864 ** If the checksum cannot be verified return non-zero. If the header
50865 ** is read successfully and the checksum verified, return zero.
50866 */
50867 static int walIndexTryHdr(Wal *pWal, int *pChanged){
50868   u32 aCksum[2];                  /* Checksum on the header content */
50869   WalIndexHdr h1, h2;             /* Two copies of the header content */
50870   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
50871 
50872   /* The first page of the wal-index must be mapped at this point. */
50873   assert( pWal->nWiData>0 && pWal->apWiData[0] );
50874 
50875   /* Read the header. This might happen concurrently with a write to the
50876   ** same area of shared memory on a different CPU in a SMP,
50877   ** meaning it is possible that an inconsistent snapshot is read
50878   ** from the file. If this happens, return non-zero.
50879   **
50880   ** There are two copies of the header at the beginning of the wal-index.
50881   ** When reading, read [0] first then [1].  Writes are in the reverse order.
50882   ** Memory barriers are used to prevent the compiler or the hardware from
50883   ** reordering the reads and writes.
50884   */
50885   aHdr = walIndexHdr(pWal);
50886   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
50887   walShmBarrier(pWal);
50888   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
50889 
50890   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
50891     return 1;   /* Dirty read */
50892   }
50893   if( h1.isInit==0 ){
50894     return 1;   /* Malformed header - probably all zeros */
50895   }
50896   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
50897   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
50898     return 1;   /* Checksum does not match */
50899   }
50900 
50901   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
50902     *pChanged = 1;
50903     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
50904     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
50905     testcase( pWal->szPage<=32768 );
50906     testcase( pWal->szPage>=65536 );
50907   }
50908 
50909   /* The header was successfully read. Return zero. */
50910   return 0;
50911 }
50912 
50913 /*
50914 ** Read the wal-index header from the wal-index and into pWal->hdr.
50915 ** If the wal-header appears to be corrupt, try to reconstruct the
50916 ** wal-index from the WAL before returning.
50917 **
50918 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
50919 ** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
50920 ** to 0.
50921 **
50922 ** If the wal-index header is successfully read, return SQLITE_OK.
50923 ** Otherwise an SQLite error code.
50924 */
50925 static int walIndexReadHdr(Wal *pWal, int *pChanged){
50926   int rc;                         /* Return code */
50927   int badHdr;                     /* True if a header read failed */
50928   volatile u32 *page0;            /* Chunk of wal-index containing header */
50929 
50930   /* Ensure that page 0 of the wal-index (the page that contains the
50931   ** wal-index header) is mapped. Return early if an error occurs here.
50932   */
50933   assert( pChanged );
50934   rc = walIndexPage(pWal, 0, &page0);
50935   if( rc!=SQLITE_OK ){
50936     return rc;
50937   };
50938   assert( page0 || pWal->writeLock==0 );
50939 
50940   /* If the first page of the wal-index has been mapped, try to read the
50941   ** wal-index header immediately, without holding any lock. This usually
50942   ** works, but may fail if the wal-index header is corrupt or currently
50943   ** being modified by another thread or process.
50944   */
50945   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
50946 
50947   /* If the first attempt failed, it might have been due to a race
50948   ** with a writer.  So get a WRITE lock and try again.
50949   */
50950   assert( badHdr==0 || pWal->writeLock==0 );
50951   if( badHdr ){
50952     if( pWal->readOnly & WAL_SHM_RDONLY ){
50953       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
50954         walUnlockShared(pWal, WAL_WRITE_LOCK);
50955         rc = SQLITE_READONLY_RECOVERY;
50956       }
50957     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1, 1)) ){
50958       pWal->writeLock = 1;
50959       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
50960         badHdr = walIndexTryHdr(pWal, pChanged);
50961         if( badHdr ){
50962           /* If the wal-index header is still malformed even while holding
50963           ** a WRITE lock, it can only mean that the header is corrupted and
50964           ** needs to be reconstructed.  So run recovery to do exactly that.
50965           */
50966           rc = walIndexRecover(pWal);
50967           *pChanged = 1;
50968         }
50969       }
50970       pWal->writeLock = 0;
50971       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
50972     }
50973   }
50974 
50975   /* If the header is read successfully, check the version number to make
50976   ** sure the wal-index was not constructed with some future format that
50977   ** this version of SQLite cannot understand.
50978   */
50979   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
50980     rc = SQLITE_CANTOPEN_BKPT;
50981   }
50982 
50983   return rc;
50984 }
50985 
50986 /*
50987 ** This is the value that walTryBeginRead returns when it needs to
50988 ** be retried.
50989 */
50990 #define WAL_RETRY  (-1)
50991 
50992 /*
50993 ** Attempt to start a read transaction.  This might fail due to a race or
50994 ** other transient condition.  When that happens, it returns WAL_RETRY to
50995 ** indicate to the caller that it is safe to retry immediately.
50996 **
50997 ** On success return SQLITE_OK.  On a permanent failure (such an
50998 ** I/O error or an SQLITE_BUSY because another process is running
50999 ** recovery) return a positive error code.
51000 **
51001 ** The useWal parameter is true to force the use of the WAL and disable
51002 ** the case where the WAL is bypassed because it has been completely
51003 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
51004 ** to make a copy of the wal-index header into pWal->hdr.  If the
51005 ** wal-index header has changed, *pChanged is set to 1 (as an indication
51006 ** to the caller that the local paget cache is obsolete and needs to be
51007 ** flushed.)  When useWal==1, the wal-index header is assumed to already
51008 ** be loaded and the pChanged parameter is unused.
51009 **
51010 ** The caller must set the cnt parameter to the number of prior calls to
51011 ** this routine during the current read attempt that returned WAL_RETRY.
51012 ** This routine will start taking more aggressive measures to clear the
51013 ** race conditions after multiple WAL_RETRY returns, and after an excessive
51014 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
51015 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
51016 ** and is not honoring the locking protocol.  There is a vanishingly small
51017 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
51018 ** bad luck when there is lots of contention for the wal-index, but that
51019 ** possibility is so small that it can be safely neglected, we believe.
51020 **
51021 ** On success, this routine obtains a read lock on
51022 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
51023 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
51024 ** that means the Wal does not hold any read lock.  The reader must not
51025 ** access any database page that is modified by a WAL frame up to and
51026 ** including frame number aReadMark[pWal->readLock].  The reader will
51027 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
51028 ** Or if pWal->readLock==0, then the reader will ignore the WAL
51029 ** completely and get all content directly from the database file.
51030 ** If the useWal parameter is 1 then the WAL will never be ignored and
51031 ** this routine will always set pWal->readLock>0 on success.
51032 ** When the read transaction is completed, the caller must release the
51033 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
51034 **
51035 ** This routine uses the nBackfill and aReadMark[] fields of the header
51036 ** to select a particular WAL_READ_LOCK() that strives to let the
51037 ** checkpoint process do as much work as possible.  This routine might
51038 ** update values of the aReadMark[] array in the header, but if it does
51039 ** so it takes care to hold an exclusive lock on the corresponding
51040 ** WAL_READ_LOCK() while changing values.
51041 */
51042 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
51043   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
51044   u32 mxReadMark;                 /* Largest aReadMark[] value */
51045   int mxI;                        /* Index of largest aReadMark[] value */
51046   int i;                          /* Loop counter */
51047   int rc = SQLITE_OK;             /* Return code  */
51048 
51049   assert( pWal->readLock<0 );     /* Not currently locked */
51050 
51051   /* Take steps to avoid spinning forever if there is a protocol error.
51052   **
51053   ** Circumstances that cause a RETRY should only last for the briefest
51054   ** instances of time.  No I/O or other system calls are done while the
51055   ** locks are held, so the locks should not be held for very long. But
51056   ** if we are unlucky, another process that is holding a lock might get
51057   ** paged out or take a page-fault that is time-consuming to resolve,
51058   ** during the few nanoseconds that it is holding the lock.  In that case,
51059   ** it might take longer than normal for the lock to free.
51060   **
51061   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
51062   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
51063   ** is more of a scheduler yield than an actual delay.  But on the 10th
51064   ** an subsequent retries, the delays start becoming longer and longer,
51065   ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
51066   ** The total delay time before giving up is less than 10 seconds.
51067   */
51068   if( cnt>5 ){
51069     int nDelay = 1;                      /* Pause time in microseconds */
51070     if( cnt>100 ){
51071       VVA_ONLY( pWal->lockError = 1; )
51072       return SQLITE_PROTOCOL;
51073     }
51074     if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
51075     sqlite3OsSleep(pWal->pVfs, nDelay);
51076   }
51077 
51078   if( !useWal ){
51079     rc = walIndexReadHdr(pWal, pChanged);
51080     if( rc==SQLITE_BUSY ){
51081       /* If there is not a recovery running in another thread or process
51082       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
51083       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
51084       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
51085       ** would be technically correct.  But the race is benign since with
51086       ** WAL_RETRY this routine will be called again and will probably be
51087       ** right on the second iteration.
51088       */
51089       if( pWal->apWiData[0]==0 ){
51090         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
51091         ** We assume this is a transient condition, so return WAL_RETRY. The
51092         ** xShmMap() implementation used by the default unix and win32 VFS
51093         ** modules may return SQLITE_BUSY due to a race condition in the
51094         ** code that determines whether or not the shared-memory region
51095         ** must be zeroed before the requested page is returned.
51096         */
51097         rc = WAL_RETRY;
51098       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
51099         walUnlockShared(pWal, WAL_RECOVER_LOCK);
51100         rc = WAL_RETRY;
51101       }else if( rc==SQLITE_BUSY ){
51102         rc = SQLITE_BUSY_RECOVERY;
51103       }
51104     }
51105     if( rc!=SQLITE_OK ){
51106       return rc;
51107     }
51108   }
51109 
51110   pInfo = walCkptInfo(pWal);
51111   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
51112     /* The WAL has been completely backfilled (or it is empty).
51113     ** and can be safely ignored.
51114     */
51115     rc = walLockShared(pWal, WAL_READ_LOCK(0));
51116     walShmBarrier(pWal);
51117     if( rc==SQLITE_OK ){
51118       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
51119         /* It is not safe to allow the reader to continue here if frames
51120         ** may have been appended to the log before READ_LOCK(0) was obtained.
51121         ** When holding READ_LOCK(0), the reader ignores the entire log file,
51122         ** which implies that the database file contains a trustworthy
51123         ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
51124         ** happening, this is usually correct.
51125         **
51126         ** However, if frames have been appended to the log (or if the log
51127         ** is wrapped and written for that matter) before the READ_LOCK(0)
51128         ** is obtained, that is not necessarily true. A checkpointer may
51129         ** have started to backfill the appended frames but crashed before
51130         ** it finished. Leaving a corrupt image in the database file.
51131         */
51132         walUnlockShared(pWal, WAL_READ_LOCK(0));
51133         return WAL_RETRY;
51134       }
51135       pWal->readLock = 0;
51136       return SQLITE_OK;
51137     }else if( rc!=SQLITE_BUSY ){
51138       return rc;
51139     }
51140   }
51141 
51142   /* If we get this far, it means that the reader will want to use
51143   ** the WAL to get at content from recent commits.  The job now is
51144   ** to select one of the aReadMark[] entries that is closest to
51145   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
51146   */
51147   mxReadMark = 0;
51148   mxI = 0;
51149   for(i=1; i<WAL_NREADER; i++){
51150     u32 thisMark = pInfo->aReadMark[i];
51151     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
51152       assert( thisMark!=READMARK_NOT_USED );
51153       mxReadMark = thisMark;
51154       mxI = i;
51155     }
51156   }
51157   /* There was once an "if" here. The extra "{" is to preserve indentation. */
51158   {
51159     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
51160      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
51161     ){
51162       for(i=1; i<WAL_NREADER; i++){
51163         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1, 0);
51164         if( rc==SQLITE_OK ){
51165           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
51166           mxI = i;
51167           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
51168           break;
51169         }else if( rc!=SQLITE_BUSY ){
51170           return rc;
51171         }
51172       }
51173     }
51174     if( mxI==0 ){
51175       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
51176       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
51177     }
51178 
51179     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
51180     if( rc ){
51181       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
51182     }
51183     /* Now that the read-lock has been obtained, check that neither the
51184     ** value in the aReadMark[] array or the contents of the wal-index
51185     ** header have changed.
51186     **
51187     ** It is necessary to check that the wal-index header did not change
51188     ** between the time it was read and when the shared-lock was obtained
51189     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
51190     ** that the log file may have been wrapped by a writer, or that frames
51191     ** that occur later in the log than pWal->hdr.mxFrame may have been
51192     ** copied into the database by a checkpointer. If either of these things
51193     ** happened, then reading the database with the current value of
51194     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
51195     ** instead.
51196     **
51197     ** This does not guarantee that the copy of the wal-index header is up to
51198     ** date before proceeding. That would not be possible without somehow
51199     ** blocking writers. It only guarantees that a dangerous checkpoint or
51200     ** log-wrap (either of which would require an exclusive lock on
51201     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
51202     */
51203     walShmBarrier(pWal);
51204     if( pInfo->aReadMark[mxI]!=mxReadMark
51205      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
51206     ){
51207       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
51208       return WAL_RETRY;
51209     }else{
51210       assert( mxReadMark<=pWal->hdr.mxFrame );
51211       pWal->readLock = (i16)mxI;
51212     }
51213   }
51214   return rc;
51215 }
51216 
51217 /*
51218 ** Begin a read transaction on the database.
51219 **
51220 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
51221 ** it takes a snapshot of the state of the WAL and wal-index for the current
51222 ** instant in time.  The current thread will continue to use this snapshot.
51223 ** Other threads might append new content to the WAL and wal-index but
51224 ** that extra content is ignored by the current thread.
51225 **
51226 ** If the database contents have changes since the previous read
51227 ** transaction, then *pChanged is set to 1 before returning.  The
51228 ** Pager layer will use this to know that is cache is stale and
51229 ** needs to be flushed.
51230 */
51231 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
51232   int rc;                         /* Return code */
51233   int cnt = 0;                    /* Number of TryBeginRead attempts */
51234 
51235   do{
51236     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
51237   }while( rc==WAL_RETRY );
51238   testcase( (rc&0xff)==SQLITE_BUSY );
51239   testcase( (rc&0xff)==SQLITE_IOERR );
51240   testcase( rc==SQLITE_PROTOCOL );
51241   testcase( rc==SQLITE_OK );
51242   return rc;
51243 }
51244 
51245 /*
51246 ** Finish with a read transaction.  All this does is release the
51247 ** read-lock.
51248 */
51249 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
51250   sqlite3WalEndWriteTransaction(pWal);
51251   if( pWal->readLock>=0 ){
51252     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
51253     pWal->readLock = -1;
51254   }
51255 }
51256 
51257 /*
51258 ** Search the wal file for page pgno. If found, set *piRead to the frame that
51259 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
51260 ** to zero.
51261 **
51262 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
51263 ** error does occur, the final value of *piRead is undefined.
51264 */
51265 SQLITE_PRIVATE int sqlite3WalFindFrame(
51266   Wal *pWal,                      /* WAL handle */
51267   Pgno pgno,                      /* Database page number to read data for */
51268   u32 *piRead                     /* OUT: Frame number (or zero) */
51269 ){
51270   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
51271   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
51272   int iHash;                      /* Used to loop through N hash tables */
51273 
51274   /* This routine is only be called from within a read transaction. */
51275   assert( pWal->readLock>=0 || pWal->lockError );
51276 
51277   /* If the "last page" field of the wal-index header snapshot is 0, then
51278   ** no data will be read from the wal under any circumstances. Return early
51279   ** in this case as an optimization.  Likewise, if pWal->readLock==0,
51280   ** then the WAL is ignored by the reader so return early, as if the
51281   ** WAL were empty.
51282   */
51283   if( iLast==0 || pWal->readLock==0 ){
51284     *piRead = 0;
51285     return SQLITE_OK;
51286   }
51287 
51288   /* Search the hash table or tables for an entry matching page number
51289   ** pgno. Each iteration of the following for() loop searches one
51290   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
51291   **
51292   ** This code might run concurrently to the code in walIndexAppend()
51293   ** that adds entries to the wal-index (and possibly to this hash
51294   ** table). This means the value just read from the hash
51295   ** slot (aHash[iKey]) may have been added before or after the
51296   ** current read transaction was opened. Values added after the
51297   ** read transaction was opened may have been written incorrectly -
51298   ** i.e. these slots may contain garbage data. However, we assume
51299   ** that any slots written before the current read transaction was
51300   ** opened remain unmodified.
51301   **
51302   ** For the reasons above, the if(...) condition featured in the inner
51303   ** loop of the following block is more stringent that would be required
51304   ** if we had exclusive access to the hash-table:
51305   **
51306   **   (aPgno[iFrame]==pgno):
51307   **     This condition filters out normal hash-table collisions.
51308   **
51309   **   (iFrame<=iLast):
51310   **     This condition filters out entries that were added to the hash
51311   **     table after the current read-transaction had started.
51312   */
51313   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
51314     volatile ht_slot *aHash;      /* Pointer to hash table */
51315     volatile u32 *aPgno;          /* Pointer to array of page numbers */
51316     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
51317     int iKey;                     /* Hash slot index */
51318     int nCollide;                 /* Number of hash collisions remaining */
51319     int rc;                       /* Error code */
51320 
51321     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
51322     if( rc!=SQLITE_OK ){
51323       return rc;
51324     }
51325     nCollide = HASHTABLE_NSLOT;
51326     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
51327       u32 iFrame = aHash[iKey] + iZero;
51328       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
51329         assert( iFrame>iRead || CORRUPT_DB );
51330         iRead = iFrame;
51331       }
51332       if( (nCollide--)==0 ){
51333         return SQLITE_CORRUPT_BKPT;
51334       }
51335     }
51336   }
51337 
51338 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
51339   /* If expensive assert() statements are available, do a linear search
51340   ** of the wal-index file content. Make sure the results agree with the
51341   ** result obtained using the hash indexes above.  */
51342   {
51343     u32 iRead2 = 0;
51344     u32 iTest;
51345     for(iTest=iLast; iTest>0; iTest--){
51346       if( walFramePgno(pWal, iTest)==pgno ){
51347         iRead2 = iTest;
51348         break;
51349       }
51350     }
51351     assert( iRead==iRead2 );
51352   }
51353 #endif
51354 
51355   *piRead = iRead;
51356   return SQLITE_OK;
51357 }
51358 
51359 /*
51360 ** Read the contents of frame iRead from the wal file into buffer pOut
51361 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
51362 ** error code otherwise.
51363 */
51364 SQLITE_PRIVATE int sqlite3WalReadFrame(
51365   Wal *pWal,                      /* WAL handle */
51366   u32 iRead,                      /* Frame to read */
51367   int nOut,                       /* Size of buffer pOut in bytes */
51368   u8 *pOut                        /* Buffer to write page data to */
51369 ){
51370   int sz;
51371   i64 iOffset;
51372   sz = pWal->hdr.szPage;
51373   sz = (sz&0xfe00) + ((sz&0x0001)<<16);
51374   testcase( sz<=32768 );
51375   testcase( sz>=65536 );
51376   iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
51377   /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
51378   return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
51379 }
51380 
51381 /*
51382 ** Return the size of the database in pages (or zero, if unknown).
51383 */
51384 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
51385   if( pWal && ALWAYS(pWal->readLock>=0) ){
51386     return pWal->hdr.nPage;
51387   }
51388   return 0;
51389 }
51390 
51391 
51392 /*
51393 ** This function starts a write transaction on the WAL.
51394 **
51395 ** A read transaction must have already been started by a prior call
51396 ** to sqlite3WalBeginReadTransaction().
51397 **
51398 ** If another thread or process has written into the database since
51399 ** the read transaction was started, then it is not possible for this
51400 ** thread to write as doing so would cause a fork.  So this routine
51401 ** returns SQLITE_BUSY in that case and no write transaction is started.
51402 **
51403 ** There can only be a single writer active at a time.
51404 */
51405 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
51406   int rc;
51407 
51408   /* Cannot start a write transaction without first holding a read
51409   ** transaction. */
51410   assert( pWal->readLock>=0 );
51411 
51412   if( pWal->readOnly ){
51413     return SQLITE_READONLY;
51414   }
51415 
51416   /* Only one writer allowed at a time.  Get the write lock.  Return
51417   ** SQLITE_BUSY if unable.
51418   */
51419   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1, 0);
51420   if( rc ){
51421     return rc;
51422   }
51423   pWal->writeLock = 1;
51424 
51425   /* If another connection has written to the database file since the
51426   ** time the read transaction on this connection was started, then
51427   ** the write is disallowed.
51428   */
51429   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
51430     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
51431     pWal->writeLock = 0;
51432     rc = SQLITE_BUSY_SNAPSHOT;
51433   }
51434 
51435   return rc;
51436 }
51437 
51438 /*
51439 ** End a write transaction.  The commit has already been done.  This
51440 ** routine merely releases the lock.
51441 */
51442 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
51443   if( pWal->writeLock ){
51444     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
51445     pWal->writeLock = 0;
51446     pWal->truncateOnCommit = 0;
51447   }
51448   return SQLITE_OK;
51449 }
51450 
51451 /*
51452 ** If any data has been written (but not committed) to the log file, this
51453 ** function moves the write-pointer back to the start of the transaction.
51454 **
51455 ** Additionally, the callback function is invoked for each frame written
51456 ** to the WAL since the start of the transaction. If the callback returns
51457 ** other than SQLITE_OK, it is not invoked again and the error code is
51458 ** returned to the caller.
51459 **
51460 ** Otherwise, if the callback function does not return an error, this
51461 ** function returns SQLITE_OK.
51462 */
51463 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
51464   int rc = SQLITE_OK;
51465   if( ALWAYS(pWal->writeLock) ){
51466     Pgno iMax = pWal->hdr.mxFrame;
51467     Pgno iFrame;
51468 
51469     /* Restore the clients cache of the wal-index header to the state it
51470     ** was in before the client began writing to the database.
51471     */
51472     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
51473 
51474     for(iFrame=pWal->hdr.mxFrame+1;
51475         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
51476         iFrame++
51477     ){
51478       /* This call cannot fail. Unless the page for which the page number
51479       ** is passed as the second argument is (a) in the cache and
51480       ** (b) has an outstanding reference, then xUndo is either a no-op
51481       ** (if (a) is false) or simply expels the page from the cache (if (b)
51482       ** is false).
51483       **
51484       ** If the upper layer is doing a rollback, it is guaranteed that there
51485       ** are no outstanding references to any page other than page 1. And
51486       ** page 1 is never written to the log until the transaction is
51487       ** committed. As a result, the call to xUndo may not fail.
51488       */
51489       assert( walFramePgno(pWal, iFrame)!=1 );
51490       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
51491     }
51492     if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
51493   }
51494   return rc;
51495 }
51496 
51497 /*
51498 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
51499 ** values. This function populates the array with values required to
51500 ** "rollback" the write position of the WAL handle back to the current
51501 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
51502 */
51503 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
51504   assert( pWal->writeLock );
51505   aWalData[0] = pWal->hdr.mxFrame;
51506   aWalData[1] = pWal->hdr.aFrameCksum[0];
51507   aWalData[2] = pWal->hdr.aFrameCksum[1];
51508   aWalData[3] = pWal->nCkpt;
51509 }
51510 
51511 /*
51512 ** Move the write position of the WAL back to the point identified by
51513 ** the values in the aWalData[] array. aWalData must point to an array
51514 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
51515 ** by a call to WalSavepoint().
51516 */
51517 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
51518   int rc = SQLITE_OK;
51519 
51520   assert( pWal->writeLock );
51521   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
51522 
51523   if( aWalData[3]!=pWal->nCkpt ){
51524     /* This savepoint was opened immediately after the write-transaction
51525     ** was started. Right after that, the writer decided to wrap around
51526     ** to the start of the log. Update the savepoint values to match.
51527     */
51528     aWalData[0] = 0;
51529     aWalData[3] = pWal->nCkpt;
51530   }
51531 
51532   if( aWalData[0]<pWal->hdr.mxFrame ){
51533     pWal->hdr.mxFrame = aWalData[0];
51534     pWal->hdr.aFrameCksum[0] = aWalData[1];
51535     pWal->hdr.aFrameCksum[1] = aWalData[2];
51536     walCleanupHash(pWal);
51537   }
51538 
51539   return rc;
51540 }
51541 
51542 /*
51543 ** This function is called just before writing a set of frames to the log
51544 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
51545 ** to the current log file, it is possible to overwrite the start of the
51546 ** existing log file with the new frames (i.e. "reset" the log). If so,
51547 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
51548 ** unchanged.
51549 **
51550 ** SQLITE_OK is returned if no error is encountered (regardless of whether
51551 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
51552 ** if an error occurs.
51553 */
51554 static int walRestartLog(Wal *pWal){
51555   int rc = SQLITE_OK;
51556   int cnt;
51557 
51558   if( pWal->readLock==0 ){
51559     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
51560     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
51561     if( pInfo->nBackfill>0 ){
51562       u32 salt1;
51563       sqlite3_randomness(4, &salt1);
51564       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1, 0);
51565       if( rc==SQLITE_OK ){
51566         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
51567         ** readers are currently using the WAL), then the transactions
51568         ** frames will overwrite the start of the existing log. Update the
51569         ** wal-index header to reflect this.
51570         **
51571         ** In theory it would be Ok to update the cache of the header only
51572         ** at this point. But updating the actual wal-index header is also
51573         ** safe and means there is no special case for sqlite3WalUndo()
51574         ** to handle if this transaction is rolled back.  */
51575         walRestartHdr(pWal, salt1);
51576         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
51577       }else if( rc!=SQLITE_BUSY ){
51578         return rc;
51579       }
51580     }
51581     walUnlockShared(pWal, WAL_READ_LOCK(0));
51582     pWal->readLock = -1;
51583     cnt = 0;
51584     do{
51585       int notUsed;
51586       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
51587     }while( rc==WAL_RETRY );
51588     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
51589     testcase( (rc&0xff)==SQLITE_IOERR );
51590     testcase( rc==SQLITE_PROTOCOL );
51591     testcase( rc==SQLITE_OK );
51592   }
51593   return rc;
51594 }
51595 
51596 /*
51597 ** Information about the current state of the WAL file and where
51598 ** the next fsync should occur - passed from sqlite3WalFrames() into
51599 ** walWriteToLog().
51600 */
51601 typedef struct WalWriter {
51602   Wal *pWal;                   /* The complete WAL information */
51603   sqlite3_file *pFd;           /* The WAL file to which we write */
51604   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
51605   int syncFlags;               /* Flags for the fsync */
51606   int szPage;                  /* Size of one page */
51607 } WalWriter;
51608 
51609 /*
51610 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
51611 ** Do a sync when crossing the p->iSyncPoint boundary.
51612 **
51613 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
51614 ** first write the part before iSyncPoint, then sync, then write the
51615 ** rest.
51616 */
51617 static int walWriteToLog(
51618   WalWriter *p,              /* WAL to write to */
51619   void *pContent,            /* Content to be written */
51620   int iAmt,                  /* Number of bytes to write */
51621   sqlite3_int64 iOffset      /* Start writing at this offset */
51622 ){
51623   int rc;
51624   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
51625     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
51626     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
51627     if( rc ) return rc;
51628     iOffset += iFirstAmt;
51629     iAmt -= iFirstAmt;
51630     pContent = (void*)(iFirstAmt + (char*)pContent);
51631     assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
51632     rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
51633     if( iAmt==0 || rc ) return rc;
51634   }
51635   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
51636   return rc;
51637 }
51638 
51639 /*
51640 ** Write out a single frame of the WAL
51641 */
51642 static int walWriteOneFrame(
51643   WalWriter *p,               /* Where to write the frame */
51644   PgHdr *pPage,               /* The page of the frame to be written */
51645   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
51646   sqlite3_int64 iOffset       /* Byte offset at which to write */
51647 ){
51648   int rc;                         /* Result code from subfunctions */
51649   void *pData;                    /* Data actually written */
51650   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
51651 #if defined(SQLITE_HAS_CODEC)
51652   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
51653 #else
51654   pData = pPage->pData;
51655 #endif
51656   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
51657   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
51658   if( rc ) return rc;
51659   /* Write the page data */
51660   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
51661   return rc;
51662 }
51663 
51664 /*
51665 ** Write a set of frames to the log. The caller must hold the write-lock
51666 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
51667 */
51668 SQLITE_PRIVATE int sqlite3WalFrames(
51669   Wal *pWal,                      /* Wal handle to write to */
51670   int szPage,                     /* Database page-size in bytes */
51671   PgHdr *pList,                   /* List of dirty pages to write */
51672   Pgno nTruncate,                 /* Database size after this commit */
51673   int isCommit,                   /* True if this is a commit */
51674   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
51675 ){
51676   int rc;                         /* Used to catch return codes */
51677   u32 iFrame;                     /* Next frame address */
51678   PgHdr *p;                       /* Iterator to run through pList with. */
51679   PgHdr *pLast = 0;               /* Last frame in list */
51680   int nExtra = 0;                 /* Number of extra copies of last page */
51681   int szFrame;                    /* The size of a single frame */
51682   i64 iOffset;                    /* Next byte to write in WAL file */
51683   WalWriter w;                    /* The writer */
51684 
51685   assert( pList );
51686   assert( pWal->writeLock );
51687 
51688   /* If this frame set completes a transaction, then nTruncate>0.  If
51689   ** nTruncate==0 then this frame set does not complete the transaction. */
51690   assert( (isCommit!=0)==(nTruncate!=0) );
51691 
51692 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
51693   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
51694     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
51695               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
51696   }
51697 #endif
51698 
51699   /* See if it is possible to write these frames into the start of the
51700   ** log file, instead of appending to it at pWal->hdr.mxFrame.
51701   */
51702   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
51703     return rc;
51704   }
51705 
51706   /* If this is the first frame written into the log, write the WAL
51707   ** header to the start of the WAL file. See comments at the top of
51708   ** this source file for a description of the WAL header format.
51709   */
51710   iFrame = pWal->hdr.mxFrame;
51711   if( iFrame==0 ){
51712     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
51713     u32 aCksum[2];                /* Checksum for wal-header */
51714 
51715     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
51716     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
51717     sqlite3Put4byte(&aWalHdr[8], szPage);
51718     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
51719     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
51720     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
51721     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
51722     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
51723     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
51724 
51725     pWal->szPage = szPage;
51726     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
51727     pWal->hdr.aFrameCksum[0] = aCksum[0];
51728     pWal->hdr.aFrameCksum[1] = aCksum[1];
51729     pWal->truncateOnCommit = 1;
51730 
51731     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
51732     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
51733     if( rc!=SQLITE_OK ){
51734       return rc;
51735     }
51736 
51737     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
51738     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
51739     ** an out-of-order write following a WAL restart could result in
51740     ** database corruption.  See the ticket:
51741     **
51742     **     http://localhost:591/sqlite/info/ff5be73dee
51743     */
51744     if( pWal->syncHeader && sync_flags ){
51745       rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
51746       if( rc ) return rc;
51747     }
51748   }
51749   assert( (int)pWal->szPage==szPage );
51750 
51751   /* Setup information needed to write frames into the WAL */
51752   w.pWal = pWal;
51753   w.pFd = pWal->pWalFd;
51754   w.iSyncPoint = 0;
51755   w.syncFlags = sync_flags;
51756   w.szPage = szPage;
51757   iOffset = walFrameOffset(iFrame+1, szPage);
51758   szFrame = szPage + WAL_FRAME_HDRSIZE;
51759 
51760   /* Write all frames into the log file exactly once */
51761   for(p=pList; p; p=p->pDirty){
51762     int nDbSize;   /* 0 normally.  Positive == commit flag */
51763     iFrame++;
51764     assert( iOffset==walFrameOffset(iFrame, szPage) );
51765     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
51766     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
51767     if( rc ) return rc;
51768     pLast = p;
51769     iOffset += szFrame;
51770   }
51771 
51772   /* If this is the end of a transaction, then we might need to pad
51773   ** the transaction and/or sync the WAL file.
51774   **
51775   ** Padding and syncing only occur if this set of frames complete a
51776   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
51777   ** or synchronous==OFF, then no padding or syncing are needed.
51778   **
51779   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
51780   ** needed and only the sync is done.  If padding is needed, then the
51781   ** final frame is repeated (with its commit mark) until the next sector
51782   ** boundary is crossed.  Only the part of the WAL prior to the last
51783   ** sector boundary is synced; the part of the last frame that extends
51784   ** past the sector boundary is written after the sync.
51785   */
51786   if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
51787     if( pWal->padToSectorBoundary ){
51788       int sectorSize = sqlite3SectorSize(pWal->pWalFd);
51789       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
51790       while( iOffset<w.iSyncPoint ){
51791         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
51792         if( rc ) return rc;
51793         iOffset += szFrame;
51794         nExtra++;
51795       }
51796     }else{
51797       rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
51798     }
51799   }
51800 
51801   /* If this frame set completes the first transaction in the WAL and
51802   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
51803   ** journal size limit, if possible.
51804   */
51805   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
51806     i64 sz = pWal->mxWalSize;
51807     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
51808       sz = walFrameOffset(iFrame+nExtra+1, szPage);
51809     }
51810     walLimitSize(pWal, sz);
51811     pWal->truncateOnCommit = 0;
51812   }
51813 
51814   /* Append data to the wal-index. It is not necessary to lock the
51815   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
51816   ** guarantees that there are no other writers, and no data that may
51817   ** be in use by existing readers is being overwritten.
51818   */
51819   iFrame = pWal->hdr.mxFrame;
51820   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
51821     iFrame++;
51822     rc = walIndexAppend(pWal, iFrame, p->pgno);
51823   }
51824   while( rc==SQLITE_OK && nExtra>0 ){
51825     iFrame++;
51826     nExtra--;
51827     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
51828   }
51829 
51830   if( rc==SQLITE_OK ){
51831     /* Update the private copy of the header. */
51832     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
51833     testcase( szPage<=32768 );
51834     testcase( szPage>=65536 );
51835     pWal->hdr.mxFrame = iFrame;
51836     if( isCommit ){
51837       pWal->hdr.iChange++;
51838       pWal->hdr.nPage = nTruncate;
51839     }
51840     /* If this is a commit, update the wal-index header too. */
51841     if( isCommit ){
51842       walIndexWriteHdr(pWal);
51843       pWal->iCallback = iFrame;
51844     }
51845   }
51846 
51847   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
51848   return rc;
51849 }
51850 
51851 /*
51852 ** This routine is called to implement sqlite3_wal_checkpoint() and
51853 ** related interfaces.
51854 **
51855 ** Obtain a CHECKPOINT lock and then backfill as much information as
51856 ** we can from WAL into the database.
51857 **
51858 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
51859 ** callback. In this case this function runs a blocking checkpoint.
51860 */
51861 SQLITE_PRIVATE int sqlite3WalCheckpoint(
51862   Wal *pWal,                      /* Wal connection */
51863   int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */
51864   int (*xBusy)(void*),            /* Function to call when busy */
51865   void *pBusyArg,                 /* Context argument for xBusyHandler */
51866   int sync_flags,                 /* Flags to sync db file with (or 0) */
51867   int nBuf,                       /* Size of temporary buffer */
51868   u8 *zBuf,                       /* Temporary buffer to use */
51869   int *pnLog,                     /* OUT: Number of frames in WAL */
51870   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
51871 ){
51872   int rc;                         /* Return code */
51873   int isChanged = 0;              /* True if a new wal-index header is loaded */
51874   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
51875   int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */
51876 
51877   assert( pWal->ckptLock==0 );
51878   assert( pWal->writeLock==0 );
51879 
51880   /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
51881   ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
51882   assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
51883 
51884   if( pWal->readOnly ) return SQLITE_READONLY;
51885   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
51886 
51887   /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
51888   ** "checkpoint" lock on the database file. */
51889   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1, 0);
51890   if( rc ){
51891     /* EVIDENCE-OF: R-10421-19736 If any other process is running a
51892     ** checkpoint operation at the same time, the lock cannot be obtained and
51893     ** SQLITE_BUSY is returned.
51894     ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
51895     ** it will not be invoked in this case.
51896     */
51897     testcase( rc==SQLITE_BUSY );
51898     testcase( xBusy!=0 );
51899     return rc;
51900   }
51901   pWal->ckptLock = 1;
51902 
51903   /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
51904   ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
51905   ** file.
51906   **
51907   ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
51908   ** immediately, and a busy-handler is configured, it is invoked and the
51909   ** writer lock retried until either the busy-handler returns 0 or the
51910   ** lock is successfully obtained.
51911   */
51912   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
51913     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
51914     if( rc==SQLITE_OK ){
51915       pWal->writeLock = 1;
51916     }else if( rc==SQLITE_BUSY ){
51917       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
51918       xBusy2 = 0;
51919       rc = SQLITE_OK;
51920     }
51921   }
51922 
51923   /* Read the wal-index header. */
51924   if( rc==SQLITE_OK ){
51925     rc = walIndexReadHdr(pWal, &isChanged);
51926     if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
51927       sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
51928     }
51929   }
51930 
51931   /* Copy data from the log to the database file. */
51932   if( rc==SQLITE_OK ){
51933     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
51934       rc = SQLITE_CORRUPT_BKPT;
51935     }else{
51936       rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
51937     }
51938 
51939     /* If no error occurred, set the output variables. */
51940     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
51941       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
51942       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
51943     }
51944   }
51945 
51946   if( isChanged ){
51947     /* If a new wal-index header was loaded before the checkpoint was
51948     ** performed, then the pager-cache associated with pWal is now
51949     ** out of date. So zero the cached wal-index header to ensure that
51950     ** next time the pager opens a snapshot on this database it knows that
51951     ** the cache needs to be reset.
51952     */
51953     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
51954   }
51955 
51956   /* Release the locks. */
51957   sqlite3WalEndWriteTransaction(pWal);
51958   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
51959   pWal->ckptLock = 0;
51960   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
51961   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
51962 }
51963 
51964 /* Return the value to pass to a sqlite3_wal_hook callback, the
51965 ** number of frames in the WAL at the point of the last commit since
51966 ** sqlite3WalCallback() was called.  If no commits have occurred since
51967 ** the last call, then return 0.
51968 */
51969 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
51970   u32 ret = 0;
51971   if( pWal ){
51972     ret = pWal->iCallback;
51973     pWal->iCallback = 0;
51974   }
51975   return (int)ret;
51976 }
51977 
51978 /*
51979 ** This function is called to change the WAL subsystem into or out
51980 ** of locking_mode=EXCLUSIVE.
51981 **
51982 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
51983 ** into locking_mode=NORMAL.  This means that we must acquire a lock
51984 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
51985 ** or if the acquisition of the lock fails, then return 0.  If the
51986 ** transition out of exclusive-mode is successful, return 1.  This
51987 ** operation must occur while the pager is still holding the exclusive
51988 ** lock on the main database file.
51989 **
51990 ** If op is one, then change from locking_mode=NORMAL into
51991 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
51992 ** be released.  Return 1 if the transition is made and 0 if the
51993 ** WAL is already in exclusive-locking mode - meaning that this
51994 ** routine is a no-op.  The pager must already hold the exclusive lock
51995 ** on the main database file before invoking this operation.
51996 **
51997 ** If op is negative, then do a dry-run of the op==1 case but do
51998 ** not actually change anything. The pager uses this to see if it
51999 ** should acquire the database exclusive lock prior to invoking
52000 ** the op==1 case.
52001 */
52002 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
52003   int rc;
52004   assert( pWal->writeLock==0 );
52005   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
52006 
52007   /* pWal->readLock is usually set, but might be -1 if there was a
52008   ** prior error while attempting to acquire are read-lock. This cannot
52009   ** happen if the connection is actually in exclusive mode (as no xShmLock
52010   ** locks are taken in this case). Nor should the pager attempt to
52011   ** upgrade to exclusive-mode following such an error.
52012   */
52013   assert( pWal->readLock>=0 || pWal->lockError );
52014   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
52015 
52016   if( op==0 ){
52017     if( pWal->exclusiveMode ){
52018       pWal->exclusiveMode = 0;
52019       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
52020         pWal->exclusiveMode = 1;
52021       }
52022       rc = pWal->exclusiveMode==0;
52023     }else{
52024       /* Already in locking_mode=NORMAL */
52025       rc = 0;
52026     }
52027   }else if( op>0 ){
52028     assert( pWal->exclusiveMode==0 );
52029     assert( pWal->readLock>=0 );
52030     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
52031     pWal->exclusiveMode = 1;
52032     rc = 1;
52033   }else{
52034     rc = pWal->exclusiveMode==0;
52035   }
52036   return rc;
52037 }
52038 
52039 /*
52040 ** Return true if the argument is non-NULL and the WAL module is using
52041 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
52042 ** WAL module is using shared-memory, return false.
52043 */
52044 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
52045   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
52046 }
52047 
52048 #ifdef SQLITE_ENABLE_ZIPVFS
52049 /*
52050 ** If the argument is not NULL, it points to a Wal object that holds a
52051 ** read-lock. This function returns the database page-size if it is known,
52052 ** or zero if it is not (or if pWal is NULL).
52053 */
52054 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
52055   assert( pWal==0 || pWal->readLock>=0 );
52056   return (pWal ? pWal->szPage : 0);
52057 }
52058 #endif
52059 
52060 #endif /* #ifndef SQLITE_OMIT_WAL */
52061 
52062 /************** End of wal.c *************************************************/
52063 /************** Begin file btmutex.c *****************************************/
52064 /*
52065 ** 2007 August 27
52066 **
52067 ** The author disclaims copyright to this source code.  In place of
52068 ** a legal notice, here is a blessing:
52069 **
52070 **    May you do good and not evil.
52071 **    May you find forgiveness for yourself and forgive others.
52072 **    May you share freely, never taking more than you give.
52073 **
52074 *************************************************************************
52075 **
52076 ** This file contains code used to implement mutexes on Btree objects.
52077 ** This code really belongs in btree.c.  But btree.c is getting too
52078 ** big and we want to break it down some.  This packaged seemed like
52079 ** a good breakout.
52080 */
52081 /************** Include btreeInt.h in the middle of btmutex.c ****************/
52082 /************** Begin file btreeInt.h ****************************************/
52083 /*
52084 ** 2004 April 6
52085 **
52086 ** The author disclaims copyright to this source code.  In place of
52087 ** a legal notice, here is a blessing:
52088 **
52089 **    May you do good and not evil.
52090 **    May you find forgiveness for yourself and forgive others.
52091 **    May you share freely, never taking more than you give.
52092 **
52093 *************************************************************************
52094 ** This file implements an external (disk-based) database using BTrees.
52095 ** For a detailed discussion of BTrees, refer to
52096 **
52097 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
52098 **     "Sorting And Searching", pages 473-480. Addison-Wesley
52099 **     Publishing Company, Reading, Massachusetts.
52100 **
52101 ** The basic idea is that each page of the file contains N database
52102 ** entries and N+1 pointers to subpages.
52103 **
52104 **   ----------------------------------------------------------------
52105 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
52106 **   ----------------------------------------------------------------
52107 **
52108 ** All of the keys on the page that Ptr(0) points to have values less
52109 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
52110 ** values greater than Key(0) and less than Key(1).  All of the keys
52111 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
52112 ** so forth.
52113 **
52114 ** Finding a particular key requires reading O(log(M)) pages from the
52115 ** disk where M is the number of entries in the tree.
52116 **
52117 ** In this implementation, a single file can hold one or more separate
52118 ** BTrees.  Each BTree is identified by the index of its root page.  The
52119 ** key and data for any entry are combined to form the "payload".  A
52120 ** fixed amount of payload can be carried directly on the database
52121 ** page.  If the payload is larger than the preset amount then surplus
52122 ** bytes are stored on overflow pages.  The payload for an entry
52123 ** and the preceding pointer are combined to form a "Cell".  Each
52124 ** page has a small header which contains the Ptr(N) pointer and other
52125 ** information such as the size of key and data.
52126 **
52127 ** FORMAT DETAILS
52128 **
52129 ** The file is divided into pages.  The first page is called page 1,
52130 ** the second is page 2, and so forth.  A page number of zero indicates
52131 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
52132 ** Each page can be either a btree page, a freelist page, an overflow
52133 ** page, or a pointer-map page.
52134 **
52135 ** The first page is always a btree page.  The first 100 bytes of the first
52136 ** page contain a special header (the "file header") that describes the file.
52137 ** The format of the file header is as follows:
52138 **
52139 **   OFFSET   SIZE    DESCRIPTION
52140 **      0      16     Header string: "SQLite format 3\000"
52141 **     16       2     Page size in bytes.  (1 means 65536)
52142 **     18       1     File format write version
52143 **     19       1     File format read version
52144 **     20       1     Bytes of unused space at the end of each page
52145 **     21       1     Max embedded payload fraction (must be 64)
52146 **     22       1     Min embedded payload fraction (must be 32)
52147 **     23       1     Min leaf payload fraction (must be 32)
52148 **     24       4     File change counter
52149 **     28       4     Reserved for future use
52150 **     32       4     First freelist page
52151 **     36       4     Number of freelist pages in the file
52152 **     40      60     15 4-byte meta values passed to higher layers
52153 **
52154 **     40       4     Schema cookie
52155 **     44       4     File format of schema layer
52156 **     48       4     Size of page cache
52157 **     52       4     Largest root-page (auto/incr_vacuum)
52158 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
52159 **     60       4     User version
52160 **     64       4     Incremental vacuum mode
52161 **     68       4     Application-ID
52162 **     72      20     unused
52163 **     92       4     The version-valid-for number
52164 **     96       4     SQLITE_VERSION_NUMBER
52165 **
52166 ** All of the integer values are big-endian (most significant byte first).
52167 **
52168 ** The file change counter is incremented when the database is changed
52169 ** This counter allows other processes to know when the file has changed
52170 ** and thus when they need to flush their cache.
52171 **
52172 ** The max embedded payload fraction is the amount of the total usable
52173 ** space in a page that can be consumed by a single cell for standard
52174 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
52175 ** is to limit the maximum cell size so that at least 4 cells will fit
52176 ** on one page.  Thus the default max embedded payload fraction is 64.
52177 **
52178 ** If the payload for a cell is larger than the max payload, then extra
52179 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
52180 ** as many bytes as possible are moved into the overflow pages without letting
52181 ** the cell size drop below the min embedded payload fraction.
52182 **
52183 ** The min leaf payload fraction is like the min embedded payload fraction
52184 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
52185 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
52186 ** not specified in the header.
52187 **
52188 ** Each btree pages is divided into three sections:  The header, the
52189 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
52190 ** file header that occurs before the page header.
52191 **
52192 **      |----------------|
52193 **      | file header    |   100 bytes.  Page 1 only.
52194 **      |----------------|
52195 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
52196 **      |----------------|
52197 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
52198 **      | array          |   |  Grows downward
52199 **      |                |   v
52200 **      |----------------|
52201 **      | unallocated    |
52202 **      | space          |
52203 **      |----------------|   ^  Grows upwards
52204 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
52205 **      | area           |   |  and free space fragments.
52206 **      |----------------|
52207 **
52208 ** The page headers looks like this:
52209 **
52210 **   OFFSET   SIZE     DESCRIPTION
52211 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
52212 **      1       2      byte offset to the first freeblock
52213 **      3       2      number of cells on this page
52214 **      5       2      first byte of the cell content area
52215 **      7       1      number of fragmented free bytes
52216 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
52217 **
52218 ** The flags define the format of this btree page.  The leaf flag means that
52219 ** this page has no children.  The zerodata flag means that this page carries
52220 ** only keys and no data.  The intkey flag means that the key is an integer
52221 ** which is stored in the key size entry of the cell header rather than in
52222 ** the payload area.
52223 **
52224 ** The cell pointer array begins on the first byte after the page header.
52225 ** The cell pointer array contains zero or more 2-byte numbers which are
52226 ** offsets from the beginning of the page to the cell content in the cell
52227 ** content area.  The cell pointers occur in sorted order.  The system strives
52228 ** to keep free space after the last cell pointer so that new cells can
52229 ** be easily added without having to defragment the page.
52230 **
52231 ** Cell content is stored at the very end of the page and grows toward the
52232 ** beginning of the page.
52233 **
52234 ** Unused space within the cell content area is collected into a linked list of
52235 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
52236 ** to the first freeblock is given in the header.  Freeblocks occur in
52237 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
52238 ** any group of 3 or fewer unused bytes in the cell content area cannot
52239 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
52240 ** a fragment.  The total number of bytes in all fragments is recorded.
52241 ** in the page header at offset 7.
52242 **
52243 **    SIZE    DESCRIPTION
52244 **      2     Byte offset of the next freeblock
52245 **      2     Bytes in this freeblock
52246 **
52247 ** Cells are of variable length.  Cells are stored in the cell content area at
52248 ** the end of the page.  Pointers to the cells are in the cell pointer array
52249 ** that immediately follows the page header.  Cells is not necessarily
52250 ** contiguous or in order, but cell pointers are contiguous and in order.
52251 **
52252 ** Cell content makes use of variable length integers.  A variable
52253 ** length integer is 1 to 9 bytes where the lower 7 bits of each
52254 ** byte are used.  The integer consists of all bytes that have bit 8 set and
52255 ** the first byte with bit 8 clear.  The most significant byte of the integer
52256 ** appears first.  A variable-length integer may not be more than 9 bytes long.
52257 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
52258 ** allows a 64-bit integer to be encoded in 9 bytes.
52259 **
52260 **    0x00                      becomes  0x00000000
52261 **    0x7f                      becomes  0x0000007f
52262 **    0x81 0x00                 becomes  0x00000080
52263 **    0x82 0x00                 becomes  0x00000100
52264 **    0x80 0x7f                 becomes  0x0000007f
52265 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
52266 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
52267 **
52268 ** Variable length integers are used for rowids and to hold the number of
52269 ** bytes of key and data in a btree cell.
52270 **
52271 ** The content of a cell looks like this:
52272 **
52273 **    SIZE    DESCRIPTION
52274 **      4     Page number of the left child. Omitted if leaf flag is set.
52275 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
52276 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
52277 **      *     Payload
52278 **      4     First page of the overflow chain.  Omitted if no overflow
52279 **
52280 ** Overflow pages form a linked list.  Each page except the last is completely
52281 ** filled with data (pagesize - 4 bytes).  The last page can have as little
52282 ** as 1 byte of data.
52283 **
52284 **    SIZE    DESCRIPTION
52285 **      4     Page number of next overflow page
52286 **      *     Data
52287 **
52288 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
52289 ** file header points to the first in a linked list of trunk page.  Each trunk
52290 ** page points to multiple leaf pages.  The content of a leaf page is
52291 ** unspecified.  A trunk page looks like this:
52292 **
52293 **    SIZE    DESCRIPTION
52294 **      4     Page number of next trunk page
52295 **      4     Number of leaf pointers on this page
52296 **      *     zero or more pages numbers of leaves
52297 */
52298 
52299 
52300 /* The following value is the maximum cell size assuming a maximum page
52301 ** size give above.
52302 */
52303 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
52304 
52305 /* The maximum number of cells on a single page of the database.  This
52306 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
52307 ** plus 2 bytes for the index to the cell in the page header).  Such
52308 ** small cells will be rare, but they are possible.
52309 */
52310 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
52311 
52312 /* Forward declarations */
52313 typedef struct MemPage MemPage;
52314 typedef struct BtLock BtLock;
52315 
52316 /*
52317 ** This is a magic string that appears at the beginning of every
52318 ** SQLite database in order to identify the file as a real database.
52319 **
52320 ** You can change this value at compile-time by specifying a
52321 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
52322 ** header must be exactly 16 bytes including the zero-terminator so
52323 ** the string itself should be 15 characters long.  If you change
52324 ** the header, then your custom library will not be able to read
52325 ** databases generated by the standard tools and the standard tools
52326 ** will not be able to read databases created by your custom library.
52327 */
52328 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
52329 #  define SQLITE_FILE_HEADER "SQLite format 3"
52330 #endif
52331 
52332 /*
52333 ** Page type flags.  An ORed combination of these flags appear as the
52334 ** first byte of on-disk image of every BTree page.
52335 */
52336 #define PTF_INTKEY    0x01
52337 #define PTF_ZERODATA  0x02
52338 #define PTF_LEAFDATA  0x04
52339 #define PTF_LEAF      0x08
52340 
52341 /*
52342 ** As each page of the file is loaded into memory, an instance of the following
52343 ** structure is appended and initialized to zero.  This structure stores
52344 ** information about the page that is decoded from the raw file page.
52345 **
52346 ** The pParent field points back to the parent page.  This allows us to
52347 ** walk up the BTree from any leaf to the root.  Care must be taken to
52348 ** unref() the parent page pointer when this page is no longer referenced.
52349 ** The pageDestructor() routine handles that chore.
52350 **
52351 ** Access to all fields of this structure is controlled by the mutex
52352 ** stored in MemPage.pBt->mutex.
52353 */
52354 struct MemPage {
52355   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
52356   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
52357   u8 intKey;           /* True if table b-trees.  False for index b-trees */
52358   u8 intKeyLeaf;       /* True if the leaf of an intKey table */
52359   u8 noPayload;        /* True if internal intKey page (thus w/o data) */
52360   u8 leaf;             /* True if a leaf page */
52361   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
52362   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
52363   u8 max1bytePayload;  /* min(maxLocal,127) */
52364   u8 bBusy;            /* Prevent endless loops on corrupt database files */
52365   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
52366   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
52367   u16 cellOffset;      /* Index in aData of first cell pointer */
52368   u16 nFree;           /* Number of free bytes on the page */
52369   u16 nCell;           /* Number of cells on this page, local and ovfl */
52370   u16 maskPage;        /* Mask for page offset */
52371   u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
52372                        ** non-overflow cell */
52373   u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
52374   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
52375   u8 *aData;           /* Pointer to disk image of the page data */
52376   u8 *aDataEnd;        /* One byte past the end of usable data */
52377   u8 *aCellIdx;        /* The cell index area */
52378   DbPage *pDbPage;     /* Pager page handle */
52379   Pgno pgno;           /* Page number for this page */
52380 };
52381 
52382 /*
52383 ** The in-memory image of a disk page has the auxiliary information appended
52384 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
52385 ** that extra information.
52386 */
52387 #define EXTRA_SIZE sizeof(MemPage)
52388 
52389 /*
52390 ** A linked list of the following structures is stored at BtShared.pLock.
52391 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
52392 ** is opened on the table with root page BtShared.iTable. Locks are removed
52393 ** from this list when a transaction is committed or rolled back, or when
52394 ** a btree handle is closed.
52395 */
52396 struct BtLock {
52397   Btree *pBtree;        /* Btree handle holding this lock */
52398   Pgno iTable;          /* Root page of table */
52399   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
52400   BtLock *pNext;        /* Next in BtShared.pLock list */
52401 };
52402 
52403 /* Candidate values for BtLock.eLock */
52404 #define READ_LOCK     1
52405 #define WRITE_LOCK    2
52406 
52407 /* A Btree handle
52408 **
52409 ** A database connection contains a pointer to an instance of
52410 ** this object for every database file that it has open.  This structure
52411 ** is opaque to the database connection.  The database connection cannot
52412 ** see the internals of this structure and only deals with pointers to
52413 ** this structure.
52414 **
52415 ** For some database files, the same underlying database cache might be
52416 ** shared between multiple connections.  In that case, each connection
52417 ** has it own instance of this object.  But each instance of this object
52418 ** points to the same BtShared object.  The database cache and the
52419 ** schema associated with the database file are all contained within
52420 ** the BtShared object.
52421 **
52422 ** All fields in this structure are accessed under sqlite3.mutex.
52423 ** The pBt pointer itself may not be changed while there exists cursors
52424 ** in the referenced BtShared that point back to this Btree since those
52425 ** cursors have to go through this Btree to find their BtShared and
52426 ** they often do so without holding sqlite3.mutex.
52427 */
52428 struct Btree {
52429   sqlite3 *db;       /* The database connection holding this btree */
52430   BtShared *pBt;     /* Sharable content of this btree */
52431   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
52432   u8 sharable;       /* True if we can share pBt with another db */
52433   u8 locked;         /* True if db currently has pBt locked */
52434   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
52435   int nBackup;       /* Number of backup operations reading this btree */
52436   u32 iDataVersion;  /* Combines with pBt->pPager->iDataVersion */
52437   Btree *pNext;      /* List of other sharable Btrees from the same db */
52438   Btree *pPrev;      /* Back pointer of the same list */
52439 #ifndef SQLITE_OMIT_SHARED_CACHE
52440   BtLock lock;       /* Object used to lock page 1 */
52441 #endif
52442 };
52443 
52444 /*
52445 ** Btree.inTrans may take one of the following values.
52446 **
52447 ** If the shared-data extension is enabled, there may be multiple users
52448 ** of the Btree structure. At most one of these may open a write transaction,
52449 ** but any number may have active read transactions.
52450 */
52451 #define TRANS_NONE  0
52452 #define TRANS_READ  1
52453 #define TRANS_WRITE 2
52454 
52455 /*
52456 ** An instance of this object represents a single database file.
52457 **
52458 ** A single database file can be in use at the same time by two
52459 ** or more database connections.  When two or more connections are
52460 ** sharing the same database file, each connection has it own
52461 ** private Btree object for the file and each of those Btrees points
52462 ** to this one BtShared object.  BtShared.nRef is the number of
52463 ** connections currently sharing this database file.
52464 **
52465 ** Fields in this structure are accessed under the BtShared.mutex
52466 ** mutex, except for nRef and pNext which are accessed under the
52467 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
52468 ** may not be modified once it is initially set as long as nRef>0.
52469 ** The pSchema field may be set once under BtShared.mutex and
52470 ** thereafter is unchanged as long as nRef>0.
52471 **
52472 ** isPending:
52473 **
52474 **   If a BtShared client fails to obtain a write-lock on a database
52475 **   table (because there exists one or more read-locks on the table),
52476 **   the shared-cache enters 'pending-lock' state and isPending is
52477 **   set to true.
52478 **
52479 **   The shared-cache leaves the 'pending lock' state when either of
52480 **   the following occur:
52481 **
52482 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
52483 **     2) The number of locks held by other connections drops to zero.
52484 **
52485 **   while in the 'pending-lock' state, no connection may start a new
52486 **   transaction.
52487 **
52488 **   This feature is included to help prevent writer-starvation.
52489 */
52490 struct BtShared {
52491   Pager *pPager;        /* The page cache */
52492   sqlite3 *db;          /* Database connection currently using this Btree */
52493   BtCursor *pCursor;    /* A list of all open cursors */
52494   MemPage *pPage1;      /* First page of the database */
52495   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
52496 #ifndef SQLITE_OMIT_AUTOVACUUM
52497   u8 autoVacuum;        /* True if auto-vacuum is enabled */
52498   u8 incrVacuum;        /* True if incr-vacuum is enabled */
52499   u8 bDoTruncate;       /* True to truncate db on commit */
52500 #endif
52501   u8 inTransaction;     /* Transaction state */
52502   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
52503 #ifdef SQLITE_HAS_CODEC
52504   u8 optimalReserve;    /* Desired amount of reserved space per page */
52505 #endif
52506   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
52507   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
52508   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
52509   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
52510   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
52511   u32 pageSize;         /* Total number of bytes on a page */
52512   u32 usableSize;       /* Number of usable bytes on each page */
52513   int nTransaction;     /* Number of open transactions (read + write) */
52514   u32 nPage;            /* Number of pages in the database */
52515   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
52516   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
52517   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
52518   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
52519 #ifndef SQLITE_OMIT_SHARED_CACHE
52520   int nRef;             /* Number of references to this structure */
52521   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
52522   BtLock *pLock;        /* List of locks held on this shared-btree struct */
52523   Btree *pWriter;       /* Btree with currently open write transaction */
52524 #endif
52525   u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */
52526 };
52527 
52528 /*
52529 ** Allowed values for BtShared.btsFlags
52530 */
52531 #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
52532 #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
52533 #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
52534 #define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
52535 #define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
52536 #define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
52537 #define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
52538 
52539 /*
52540 ** An instance of the following structure is used to hold information
52541 ** about a cell.  The parseCellPtr() function fills in this structure
52542 ** based on information extract from the raw disk page.
52543 */
52544 typedef struct CellInfo CellInfo;
52545 struct CellInfo {
52546   i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */
52547   u8 *pPayload;  /* Pointer to the start of payload */
52548   u32 nPayload;  /* Bytes of payload */
52549   u16 nLocal;    /* Amount of payload held locally, not on overflow */
52550   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
52551   u16 nSize;     /* Size of the cell content on the main b-tree page */
52552 };
52553 
52554 /*
52555 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
52556 ** this will be declared corrupt. This value is calculated based on a
52557 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
52558 ** root-node and 3 for all other internal nodes.
52559 **
52560 ** If a tree that appears to be taller than this is encountered, it is
52561 ** assumed that the database is corrupt.
52562 */
52563 #define BTCURSOR_MAX_DEPTH 20
52564 
52565 /*
52566 ** A cursor is a pointer to a particular entry within a particular
52567 ** b-tree within a database file.
52568 **
52569 ** The entry is identified by its MemPage and the index in
52570 ** MemPage.aCell[] of the entry.
52571 **
52572 ** A single database file can be shared by two more database connections,
52573 ** but cursors cannot be shared.  Each cursor is associated with a
52574 ** particular database connection identified BtCursor.pBtree.db.
52575 **
52576 ** Fields in this structure are accessed under the BtShared.mutex
52577 ** found at self->pBt->mutex.
52578 **
52579 ** skipNext meaning:
52580 **    eState==SKIPNEXT && skipNext>0:  Next sqlite3BtreeNext() is no-op.
52581 **    eState==SKIPNEXT && skipNext<0:  Next sqlite3BtreePrevious() is no-op.
52582 **    eState==FAULT:                   Cursor fault with skipNext as error code.
52583 */
52584 struct BtCursor {
52585   Btree *pBtree;            /* The Btree to which this cursor belongs */
52586   BtShared *pBt;            /* The BtShared this cursor points to */
52587   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
52588   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
52589   Pgno *aOverflow;          /* Cache of overflow page locations */
52590   CellInfo info;            /* A parse of the cell we are pointing at */
52591   i64 nKey;                 /* Size of pKey, or last integer key */
52592   void *pKey;               /* Saved key that was cursor last known position */
52593   Pgno pgnoRoot;            /* The root page of this tree */
52594   int nOvflAlloc;           /* Allocated size of aOverflow[] array */
52595   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive.
52596                    ** Error code if eState==CURSOR_FAULT */
52597   u8 curFlags;              /* zero or more BTCF_* flags defined below */
52598   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
52599   u8 hints;                             /* As configured by CursorSetHints() */
52600   i16 iPage;                            /* Index of current page in apPage */
52601   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
52602   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
52603 };
52604 
52605 /*
52606 ** Legal values for BtCursor.curFlags
52607 */
52608 #define BTCF_WriteFlag    0x01   /* True if a write cursor */
52609 #define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
52610 #define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
52611 #define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
52612 #define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
52613 
52614 /*
52615 ** Potential values for BtCursor.eState.
52616 **
52617 ** CURSOR_INVALID:
52618 **   Cursor does not point to a valid entry. This can happen (for example)
52619 **   because the table is empty or because BtreeCursorFirst() has not been
52620 **   called.
52621 **
52622 ** CURSOR_VALID:
52623 **   Cursor points to a valid entry. getPayload() etc. may be called.
52624 **
52625 ** CURSOR_SKIPNEXT:
52626 **   Cursor is valid except that the Cursor.skipNext field is non-zero
52627 **   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
52628 **   operation should be a no-op.
52629 **
52630 ** CURSOR_REQUIRESEEK:
52631 **   The table that this cursor was opened on still exists, but has been
52632 **   modified since the cursor was last used. The cursor position is saved
52633 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
52634 **   this state, restoreCursorPosition() can be called to attempt to
52635 **   seek the cursor to the saved position.
52636 **
52637 ** CURSOR_FAULT:
52638 **   An unrecoverable error (an I/O error or a malloc failure) has occurred
52639 **   on a different connection that shares the BtShared cache with this
52640 **   cursor.  The error has left the cache in an inconsistent state.
52641 **   Do nothing else with this cursor.  Any attempt to use the cursor
52642 **   should return the error code stored in BtCursor.skipNext
52643 */
52644 #define CURSOR_INVALID           0
52645 #define CURSOR_VALID             1
52646 #define CURSOR_SKIPNEXT          2
52647 #define CURSOR_REQUIRESEEK       3
52648 #define CURSOR_FAULT             4
52649 
52650 /*
52651 ** The database page the PENDING_BYTE occupies. This page is never used.
52652 */
52653 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
52654 
52655 /*
52656 ** These macros define the location of the pointer-map entry for a
52657 ** database page. The first argument to each is the number of usable
52658 ** bytes on each page of the database (often 1024). The second is the
52659 ** page number to look up in the pointer map.
52660 **
52661 ** PTRMAP_PAGENO returns the database page number of the pointer-map
52662 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
52663 ** the offset of the requested map entry.
52664 **
52665 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
52666 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
52667 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
52668 ** this test.
52669 */
52670 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
52671 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
52672 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
52673 
52674 /*
52675 ** The pointer map is a lookup table that identifies the parent page for
52676 ** each child page in the database file.  The parent page is the page that
52677 ** contains a pointer to the child.  Every page in the database contains
52678 ** 0 or 1 parent pages.  (In this context 'database page' refers
52679 ** to any page that is not part of the pointer map itself.)  Each pointer map
52680 ** entry consists of a single byte 'type' and a 4 byte parent page number.
52681 ** The PTRMAP_XXX identifiers below are the valid types.
52682 **
52683 ** The purpose of the pointer map is to facility moving pages from one
52684 ** position in the file to another as part of autovacuum.  When a page
52685 ** is moved, the pointer in its parent must be updated to point to the
52686 ** new location.  The pointer map is used to locate the parent page quickly.
52687 **
52688 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
52689 **                  used in this case.
52690 **
52691 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
52692 **                  is not used in this case.
52693 **
52694 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
52695 **                   overflow pages. The page number identifies the page that
52696 **                   contains the cell with a pointer to this overflow page.
52697 **
52698 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
52699 **                   overflow pages. The page-number identifies the previous
52700 **                   page in the overflow page list.
52701 **
52702 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
52703 **               identifies the parent page in the btree.
52704 */
52705 #define PTRMAP_ROOTPAGE 1
52706 #define PTRMAP_FREEPAGE 2
52707 #define PTRMAP_OVERFLOW1 3
52708 #define PTRMAP_OVERFLOW2 4
52709 #define PTRMAP_BTREE 5
52710 
52711 /* A bunch of assert() statements to check the transaction state variables
52712 ** of handle p (type Btree*) are internally consistent.
52713 */
52714 #define btreeIntegrity(p) \
52715   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
52716   assert( p->pBt->inTransaction>=p->inTrans );
52717 
52718 
52719 /*
52720 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
52721 ** if the database supports auto-vacuum or not. Because it is used
52722 ** within an expression that is an argument to another macro
52723 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
52724 ** So, this macro is defined instead.
52725 */
52726 #ifndef SQLITE_OMIT_AUTOVACUUM
52727 #define ISAUTOVACUUM (pBt->autoVacuum)
52728 #else
52729 #define ISAUTOVACUUM 0
52730 #endif
52731 
52732 
52733 /*
52734 ** This structure is passed around through all the sanity checking routines
52735 ** in order to keep track of some global state information.
52736 **
52737 ** The aRef[] array is allocated so that there is 1 bit for each page in
52738 ** the database. As the integrity-check proceeds, for each page used in
52739 ** the database the corresponding bit is set. This allows integrity-check to
52740 ** detect pages that are used twice and orphaned pages (both of which
52741 ** indicate corruption).
52742 */
52743 typedef struct IntegrityCk IntegrityCk;
52744 struct IntegrityCk {
52745   BtShared *pBt;    /* The tree being checked out */
52746   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
52747   u8 *aPgRef;       /* 1 bit per page in the db (see above) */
52748   Pgno nPage;       /* Number of pages in the database */
52749   int mxErr;        /* Stop accumulating errors when this reaches zero */
52750   int nErr;         /* Number of messages written to zErrMsg so far */
52751   int mallocFailed; /* A memory allocation error has occurred */
52752   const char *zPfx; /* Error message prefix */
52753   int v1, v2;       /* Values for up to two %d fields in zPfx */
52754   StrAccum errMsg;  /* Accumulate the error message text here */
52755 };
52756 
52757 /*
52758 ** Routines to read or write a two- and four-byte big-endian integer values.
52759 */
52760 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
52761 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
52762 #define get4byte sqlite3Get4byte
52763 #define put4byte sqlite3Put4byte
52764 
52765 /************** End of btreeInt.h ********************************************/
52766 /************** Continuing where we left off in btmutex.c ********************/
52767 #ifndef SQLITE_OMIT_SHARED_CACHE
52768 #if SQLITE_THREADSAFE
52769 
52770 /*
52771 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
52772 ** set BtShared.db to the database handle associated with p and the
52773 ** p->locked boolean to true.
52774 */
52775 static void lockBtreeMutex(Btree *p){
52776   assert( p->locked==0 );
52777   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
52778   assert( sqlite3_mutex_held(p->db->mutex) );
52779 
52780   sqlite3_mutex_enter(p->pBt->mutex);
52781   p->pBt->db = p->db;
52782   p->locked = 1;
52783 }
52784 
52785 /*
52786 ** Release the BtShared mutex associated with B-Tree handle p and
52787 ** clear the p->locked boolean.
52788 */
52789 static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
52790   BtShared *pBt = p->pBt;
52791   assert( p->locked==1 );
52792   assert( sqlite3_mutex_held(pBt->mutex) );
52793   assert( sqlite3_mutex_held(p->db->mutex) );
52794   assert( p->db==pBt->db );
52795 
52796   sqlite3_mutex_leave(pBt->mutex);
52797   p->locked = 0;
52798 }
52799 
52800 /* Forward reference */
52801 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
52802 
52803 /*
52804 ** Enter a mutex on the given BTree object.
52805 **
52806 ** If the object is not sharable, then no mutex is ever required
52807 ** and this routine is a no-op.  The underlying mutex is non-recursive.
52808 ** But we keep a reference count in Btree.wantToLock so the behavior
52809 ** of this interface is recursive.
52810 **
52811 ** To avoid deadlocks, multiple Btrees are locked in the same order
52812 ** by all database connections.  The p->pNext is a list of other
52813 ** Btrees belonging to the same database connection as the p Btree
52814 ** which need to be locked after p.  If we cannot get a lock on
52815 ** p, then first unlock all of the others on p->pNext, then wait
52816 ** for the lock to become available on p, then relock all of the
52817 ** subsequent Btrees that desire a lock.
52818 */
52819 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
52820   /* Some basic sanity checking on the Btree.  The list of Btrees
52821   ** connected by pNext and pPrev should be in sorted order by
52822   ** Btree.pBt value. All elements of the list should belong to
52823   ** the same connection. Only shared Btrees are on the list. */
52824   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
52825   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
52826   assert( p->pNext==0 || p->pNext->db==p->db );
52827   assert( p->pPrev==0 || p->pPrev->db==p->db );
52828   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
52829 
52830   /* Check for locking consistency */
52831   assert( !p->locked || p->wantToLock>0 );
52832   assert( p->sharable || p->wantToLock==0 );
52833 
52834   /* We should already hold a lock on the database connection */
52835   assert( sqlite3_mutex_held(p->db->mutex) );
52836 
52837   /* Unless the database is sharable and unlocked, then BtShared.db
52838   ** should already be set correctly. */
52839   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
52840 
52841   if( !p->sharable ) return;
52842   p->wantToLock++;
52843   if( p->locked ) return;
52844   btreeLockCarefully(p);
52845 }
52846 
52847 /* This is a helper function for sqlite3BtreeLock(). By moving
52848 ** complex, but seldom used logic, out of sqlite3BtreeLock() and
52849 ** into this routine, we avoid unnecessary stack pointer changes
52850 ** and thus help the sqlite3BtreeLock() routine to run much faster
52851 ** in the common case.
52852 */
52853 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
52854   Btree *pLater;
52855 
52856   /* In most cases, we should be able to acquire the lock we
52857   ** want without having to go through the ascending lock
52858   ** procedure that follows.  Just be sure not to block.
52859   */
52860   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
52861     p->pBt->db = p->db;
52862     p->locked = 1;
52863     return;
52864   }
52865 
52866   /* To avoid deadlock, first release all locks with a larger
52867   ** BtShared address.  Then acquire our lock.  Then reacquire
52868   ** the other BtShared locks that we used to hold in ascending
52869   ** order.
52870   */
52871   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
52872     assert( pLater->sharable );
52873     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
52874     assert( !pLater->locked || pLater->wantToLock>0 );
52875     if( pLater->locked ){
52876       unlockBtreeMutex(pLater);
52877     }
52878   }
52879   lockBtreeMutex(p);
52880   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
52881     if( pLater->wantToLock ){
52882       lockBtreeMutex(pLater);
52883     }
52884   }
52885 }
52886 
52887 
52888 /*
52889 ** Exit the recursive mutex on a Btree.
52890 */
52891 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
52892   assert( sqlite3_mutex_held(p->db->mutex) );
52893   if( p->sharable ){
52894     assert( p->wantToLock>0 );
52895     p->wantToLock--;
52896     if( p->wantToLock==0 ){
52897       unlockBtreeMutex(p);
52898     }
52899   }
52900 }
52901 
52902 #ifndef NDEBUG
52903 /*
52904 ** Return true if the BtShared mutex is held on the btree, or if the
52905 ** B-Tree is not marked as sharable.
52906 **
52907 ** This routine is used only from within assert() statements.
52908 */
52909 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
52910   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
52911   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
52912   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
52913   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
52914 
52915   return (p->sharable==0 || p->locked);
52916 }
52917 #endif
52918 
52919 
52920 #ifndef SQLITE_OMIT_INCRBLOB
52921 /*
52922 ** Enter and leave a mutex on a Btree given a cursor owned by that
52923 ** Btree.  These entry points are used by incremental I/O and can be
52924 ** omitted if that module is not used.
52925 */
52926 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
52927   sqlite3BtreeEnter(pCur->pBtree);
52928 }
52929 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
52930   sqlite3BtreeLeave(pCur->pBtree);
52931 }
52932 #endif /* SQLITE_OMIT_INCRBLOB */
52933 
52934 
52935 /*
52936 ** Enter the mutex on every Btree associated with a database
52937 ** connection.  This is needed (for example) prior to parsing
52938 ** a statement since we will be comparing table and column names
52939 ** against all schemas and we do not want those schemas being
52940 ** reset out from under us.
52941 **
52942 ** There is a corresponding leave-all procedures.
52943 **
52944 ** Enter the mutexes in accending order by BtShared pointer address
52945 ** to avoid the possibility of deadlock when two threads with
52946 ** two or more btrees in common both try to lock all their btrees
52947 ** at the same instant.
52948 */
52949 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
52950   int i;
52951   Btree *p;
52952   assert( sqlite3_mutex_held(db->mutex) );
52953   for(i=0; i<db->nDb; i++){
52954     p = db->aDb[i].pBt;
52955     if( p ) sqlite3BtreeEnter(p);
52956   }
52957 }
52958 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
52959   int i;
52960   Btree *p;
52961   assert( sqlite3_mutex_held(db->mutex) );
52962   for(i=0; i<db->nDb; i++){
52963     p = db->aDb[i].pBt;
52964     if( p ) sqlite3BtreeLeave(p);
52965   }
52966 }
52967 
52968 /*
52969 ** Return true if a particular Btree requires a lock.  Return FALSE if
52970 ** no lock is ever required since it is not sharable.
52971 */
52972 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
52973   return p->sharable;
52974 }
52975 
52976 #ifndef NDEBUG
52977 /*
52978 ** Return true if the current thread holds the database connection
52979 ** mutex and all required BtShared mutexes.
52980 **
52981 ** This routine is used inside assert() statements only.
52982 */
52983 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
52984   int i;
52985   if( !sqlite3_mutex_held(db->mutex) ){
52986     return 0;
52987   }
52988   for(i=0; i<db->nDb; i++){
52989     Btree *p;
52990     p = db->aDb[i].pBt;
52991     if( p && p->sharable &&
52992          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
52993       return 0;
52994     }
52995   }
52996   return 1;
52997 }
52998 #endif /* NDEBUG */
52999 
53000 #ifndef NDEBUG
53001 /*
53002 ** Return true if the correct mutexes are held for accessing the
53003 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
53004 ** access are:
53005 **
53006 **   (1) The mutex on db
53007 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
53008 **
53009 ** If pSchema is not NULL, then iDb is computed from pSchema and
53010 ** db using sqlite3SchemaToIndex().
53011 */
53012 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
53013   Btree *p;
53014   assert( db!=0 );
53015   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
53016   assert( iDb>=0 && iDb<db->nDb );
53017   if( !sqlite3_mutex_held(db->mutex) ) return 0;
53018   if( iDb==1 ) return 1;
53019   p = db->aDb[iDb].pBt;
53020   assert( p!=0 );
53021   return p->sharable==0 || p->locked==1;
53022 }
53023 #endif /* NDEBUG */
53024 
53025 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
53026 /*
53027 ** The following are special cases for mutex enter routines for use
53028 ** in single threaded applications that use shared cache.  Except for
53029 ** these two routines, all mutex operations are no-ops in that case and
53030 ** are null #defines in btree.h.
53031 **
53032 ** If shared cache is disabled, then all btree mutex routines, including
53033 ** the ones below, are no-ops and are null #defines in btree.h.
53034 */
53035 
53036 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
53037   p->pBt->db = p->db;
53038 }
53039 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
53040   int i;
53041   for(i=0; i<db->nDb; i++){
53042     Btree *p = db->aDb[i].pBt;
53043     if( p ){
53044       p->pBt->db = p->db;
53045     }
53046   }
53047 }
53048 #endif /* if SQLITE_THREADSAFE */
53049 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
53050 
53051 /************** End of btmutex.c *********************************************/
53052 /************** Begin file btree.c *******************************************/
53053 /*
53054 ** 2004 April 6
53055 **
53056 ** The author disclaims copyright to this source code.  In place of
53057 ** a legal notice, here is a blessing:
53058 **
53059 **    May you do good and not evil.
53060 **    May you find forgiveness for yourself and forgive others.
53061 **    May you share freely, never taking more than you give.
53062 **
53063 *************************************************************************
53064 ** This file implements an external (disk-based) database using BTrees.
53065 ** See the header comment on "btreeInt.h" for additional information.
53066 ** Including a description of file format and an overview of operation.
53067 */
53068 
53069 /*
53070 ** The header string that appears at the beginning of every
53071 ** SQLite database.
53072 */
53073 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
53074 
53075 /*
53076 ** Set this global variable to 1 to enable tracing using the TRACE
53077 ** macro.
53078 */
53079 #if 0
53080 int sqlite3BtreeTrace=1;  /* True to enable tracing */
53081 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
53082 #else
53083 # define TRACE(X)
53084 #endif
53085 
53086 /*
53087 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
53088 ** But if the value is zero, make it 65536.
53089 **
53090 ** This routine is used to extract the "offset to cell content area" value
53091 ** from the header of a btree page.  If the page size is 65536 and the page
53092 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
53093 ** This routine makes the necessary adjustment to 65536.
53094 */
53095 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
53096 
53097 /*
53098 ** Values passed as the 5th argument to allocateBtreePage()
53099 */
53100 #define BTALLOC_ANY   0           /* Allocate any page */
53101 #define BTALLOC_EXACT 1           /* Allocate exact page if possible */
53102 #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
53103 
53104 /*
53105 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
53106 ** defined, or 0 if it is. For example:
53107 **
53108 **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
53109 */
53110 #ifndef SQLITE_OMIT_AUTOVACUUM
53111 #define IfNotOmitAV(expr) (expr)
53112 #else
53113 #define IfNotOmitAV(expr) 0
53114 #endif
53115 
53116 #ifndef SQLITE_OMIT_SHARED_CACHE
53117 /*
53118 ** A list of BtShared objects that are eligible for participation
53119 ** in shared cache.  This variable has file scope during normal builds,
53120 ** but the test harness needs to access it so we make it global for
53121 ** test builds.
53122 **
53123 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
53124 */
53125 #ifdef SQLITE_TEST
53126 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
53127 #else
53128 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
53129 #endif
53130 #endif /* SQLITE_OMIT_SHARED_CACHE */
53131 
53132 #ifndef SQLITE_OMIT_SHARED_CACHE
53133 /*
53134 ** Enable or disable the shared pager and schema features.
53135 **
53136 ** This routine has no effect on existing database connections.
53137 ** The shared cache setting effects only future calls to
53138 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
53139 */
53140 SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int enable){
53141   sqlite3GlobalConfig.sharedCacheEnabled = enable;
53142   return SQLITE_OK;
53143 }
53144 #endif
53145 
53146 
53147 
53148 #ifdef SQLITE_OMIT_SHARED_CACHE
53149   /*
53150   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
53151   ** and clearAllSharedCacheTableLocks()
53152   ** manipulate entries in the BtShared.pLock linked list used to store
53153   ** shared-cache table level locks. If the library is compiled with the
53154   ** shared-cache feature disabled, then there is only ever one user
53155   ** of each BtShared structure and so this locking is not necessary.
53156   ** So define the lock related functions as no-ops.
53157   */
53158   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
53159   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
53160   #define clearAllSharedCacheTableLocks(a)
53161   #define downgradeAllSharedCacheTableLocks(a)
53162   #define hasSharedCacheTableLock(a,b,c,d) 1
53163   #define hasReadConflicts(a, b) 0
53164 #endif
53165 
53166 #ifndef SQLITE_OMIT_SHARED_CACHE
53167 
53168 #ifdef SQLITE_DEBUG
53169 /*
53170 **** This function is only used as part of an assert() statement. ***
53171 **
53172 ** Check to see if pBtree holds the required locks to read or write to the
53173 ** table with root page iRoot.   Return 1 if it does and 0 if not.
53174 **
53175 ** For example, when writing to a table with root-page iRoot via
53176 ** Btree connection pBtree:
53177 **
53178 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
53179 **
53180 ** When writing to an index that resides in a sharable database, the
53181 ** caller should have first obtained a lock specifying the root page of
53182 ** the corresponding table. This makes things a bit more complicated,
53183 ** as this module treats each table as a separate structure. To determine
53184 ** the table corresponding to the index being written, this
53185 ** function has to search through the database schema.
53186 **
53187 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
53188 ** hold a write-lock on the schema table (root page 1). This is also
53189 ** acceptable.
53190 */
53191 static int hasSharedCacheTableLock(
53192   Btree *pBtree,         /* Handle that must hold lock */
53193   Pgno iRoot,            /* Root page of b-tree */
53194   int isIndex,           /* True if iRoot is the root of an index b-tree */
53195   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
53196 ){
53197   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
53198   Pgno iTab = 0;
53199   BtLock *pLock;
53200 
53201   /* If this database is not shareable, or if the client is reading
53202   ** and has the read-uncommitted flag set, then no lock is required.
53203   ** Return true immediately.
53204   */
53205   if( (pBtree->sharable==0)
53206    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
53207   ){
53208     return 1;
53209   }
53210 
53211   /* If the client is reading  or writing an index and the schema is
53212   ** not loaded, then it is too difficult to actually check to see if
53213   ** the correct locks are held.  So do not bother - just return true.
53214   ** This case does not come up very often anyhow.
53215   */
53216   if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
53217     return 1;
53218   }
53219 
53220   /* Figure out the root-page that the lock should be held on. For table
53221   ** b-trees, this is just the root page of the b-tree being read or
53222   ** written. For index b-trees, it is the root page of the associated
53223   ** table.  */
53224   if( isIndex ){
53225     HashElem *p;
53226     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
53227       Index *pIdx = (Index *)sqliteHashData(p);
53228       if( pIdx->tnum==(int)iRoot ){
53229         if( iTab ){
53230           /* Two or more indexes share the same root page.  There must
53231           ** be imposter tables.  So just return true.  The assert is not
53232           ** useful in that case. */
53233           return 1;
53234         }
53235         iTab = pIdx->pTable->tnum;
53236       }
53237     }
53238   }else{
53239     iTab = iRoot;
53240   }
53241 
53242   /* Search for the required lock. Either a write-lock on root-page iTab, a
53243   ** write-lock on the schema table, or (if the client is reading) a
53244   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
53245   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
53246     if( pLock->pBtree==pBtree
53247      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
53248      && pLock->eLock>=eLockType
53249     ){
53250       return 1;
53251     }
53252   }
53253 
53254   /* Failed to find the required lock. */
53255   return 0;
53256 }
53257 #endif /* SQLITE_DEBUG */
53258 
53259 #ifdef SQLITE_DEBUG
53260 /*
53261 **** This function may be used as part of assert() statements only. ****
53262 **
53263 ** Return true if it would be illegal for pBtree to write into the
53264 ** table or index rooted at iRoot because other shared connections are
53265 ** simultaneously reading that same table or index.
53266 **
53267 ** It is illegal for pBtree to write if some other Btree object that
53268 ** shares the same BtShared object is currently reading or writing
53269 ** the iRoot table.  Except, if the other Btree object has the
53270 ** read-uncommitted flag set, then it is OK for the other object to
53271 ** have a read cursor.
53272 **
53273 ** For example, before writing to any part of the table or index
53274 ** rooted at page iRoot, one should call:
53275 **
53276 **    assert( !hasReadConflicts(pBtree, iRoot) );
53277 */
53278 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
53279   BtCursor *p;
53280   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
53281     if( p->pgnoRoot==iRoot
53282      && p->pBtree!=pBtree
53283      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
53284     ){
53285       return 1;
53286     }
53287   }
53288   return 0;
53289 }
53290 #endif    /* #ifdef SQLITE_DEBUG */
53291 
53292 /*
53293 ** Query to see if Btree handle p may obtain a lock of type eLock
53294 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
53295 ** SQLITE_OK if the lock may be obtained (by calling
53296 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
53297 */
53298 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
53299   BtShared *pBt = p->pBt;
53300   BtLock *pIter;
53301 
53302   assert( sqlite3BtreeHoldsMutex(p) );
53303   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
53304   assert( p->db!=0 );
53305   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
53306 
53307   /* If requesting a write-lock, then the Btree must have an open write
53308   ** transaction on this file. And, obviously, for this to be so there
53309   ** must be an open write transaction on the file itself.
53310   */
53311   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
53312   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
53313 
53314   /* This routine is a no-op if the shared-cache is not enabled */
53315   if( !p->sharable ){
53316     return SQLITE_OK;
53317   }
53318 
53319   /* If some other connection is holding an exclusive lock, the
53320   ** requested lock may not be obtained.
53321   */
53322   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
53323     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
53324     return SQLITE_LOCKED_SHAREDCACHE;
53325   }
53326 
53327   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
53328     /* The condition (pIter->eLock!=eLock) in the following if(...)
53329     ** statement is a simplification of:
53330     **
53331     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
53332     **
53333     ** since we know that if eLock==WRITE_LOCK, then no other connection
53334     ** may hold a WRITE_LOCK on any table in this file (since there can
53335     ** only be a single writer).
53336     */
53337     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
53338     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
53339     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
53340       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
53341       if( eLock==WRITE_LOCK ){
53342         assert( p==pBt->pWriter );
53343         pBt->btsFlags |= BTS_PENDING;
53344       }
53345       return SQLITE_LOCKED_SHAREDCACHE;
53346     }
53347   }
53348   return SQLITE_OK;
53349 }
53350 #endif /* !SQLITE_OMIT_SHARED_CACHE */
53351 
53352 #ifndef SQLITE_OMIT_SHARED_CACHE
53353 /*
53354 ** Add a lock on the table with root-page iTable to the shared-btree used
53355 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
53356 ** WRITE_LOCK.
53357 **
53358 ** This function assumes the following:
53359 **
53360 **   (a) The specified Btree object p is connected to a sharable
53361 **       database (one with the BtShared.sharable flag set), and
53362 **
53363 **   (b) No other Btree objects hold a lock that conflicts
53364 **       with the requested lock (i.e. querySharedCacheTableLock() has
53365 **       already been called and returned SQLITE_OK).
53366 **
53367 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
53368 ** is returned if a malloc attempt fails.
53369 */
53370 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
53371   BtShared *pBt = p->pBt;
53372   BtLock *pLock = 0;
53373   BtLock *pIter;
53374 
53375   assert( sqlite3BtreeHoldsMutex(p) );
53376   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
53377   assert( p->db!=0 );
53378 
53379   /* A connection with the read-uncommitted flag set will never try to
53380   ** obtain a read-lock using this function. The only read-lock obtained
53381   ** by a connection in read-uncommitted mode is on the sqlite_master
53382   ** table, and that lock is obtained in BtreeBeginTrans().  */
53383   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
53384 
53385   /* This function should only be called on a sharable b-tree after it
53386   ** has been determined that no other b-tree holds a conflicting lock.  */
53387   assert( p->sharable );
53388   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
53389 
53390   /* First search the list for an existing lock on this table. */
53391   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
53392     if( pIter->iTable==iTable && pIter->pBtree==p ){
53393       pLock = pIter;
53394       break;
53395     }
53396   }
53397 
53398   /* If the above search did not find a BtLock struct associating Btree p
53399   ** with table iTable, allocate one and link it into the list.
53400   */
53401   if( !pLock ){
53402     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
53403     if( !pLock ){
53404       return SQLITE_NOMEM;
53405     }
53406     pLock->iTable = iTable;
53407     pLock->pBtree = p;
53408     pLock->pNext = pBt->pLock;
53409     pBt->pLock = pLock;
53410   }
53411 
53412   /* Set the BtLock.eLock variable to the maximum of the current lock
53413   ** and the requested lock. This means if a write-lock was already held
53414   ** and a read-lock requested, we don't incorrectly downgrade the lock.
53415   */
53416   assert( WRITE_LOCK>READ_LOCK );
53417   if( eLock>pLock->eLock ){
53418     pLock->eLock = eLock;
53419   }
53420 
53421   return SQLITE_OK;
53422 }
53423 #endif /* !SQLITE_OMIT_SHARED_CACHE */
53424 
53425 #ifndef SQLITE_OMIT_SHARED_CACHE
53426 /*
53427 ** Release all the table locks (locks obtained via calls to
53428 ** the setSharedCacheTableLock() procedure) held by Btree object p.
53429 **
53430 ** This function assumes that Btree p has an open read or write
53431 ** transaction. If it does not, then the BTS_PENDING flag
53432 ** may be incorrectly cleared.
53433 */
53434 static void clearAllSharedCacheTableLocks(Btree *p){
53435   BtShared *pBt = p->pBt;
53436   BtLock **ppIter = &pBt->pLock;
53437 
53438   assert( sqlite3BtreeHoldsMutex(p) );
53439   assert( p->sharable || 0==*ppIter );
53440   assert( p->inTrans>0 );
53441 
53442   while( *ppIter ){
53443     BtLock *pLock = *ppIter;
53444     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
53445     assert( pLock->pBtree->inTrans>=pLock->eLock );
53446     if( pLock->pBtree==p ){
53447       *ppIter = pLock->pNext;
53448       assert( pLock->iTable!=1 || pLock==&p->lock );
53449       if( pLock->iTable!=1 ){
53450         sqlite3_free(pLock);
53451       }
53452     }else{
53453       ppIter = &pLock->pNext;
53454     }
53455   }
53456 
53457   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
53458   if( pBt->pWriter==p ){
53459     pBt->pWriter = 0;
53460     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
53461   }else if( pBt->nTransaction==2 ){
53462     /* This function is called when Btree p is concluding its
53463     ** transaction. If there currently exists a writer, and p is not
53464     ** that writer, then the number of locks held by connections other
53465     ** than the writer must be about to drop to zero. In this case
53466     ** set the BTS_PENDING flag to 0.
53467     **
53468     ** If there is not currently a writer, then BTS_PENDING must
53469     ** be zero already. So this next line is harmless in that case.
53470     */
53471     pBt->btsFlags &= ~BTS_PENDING;
53472   }
53473 }
53474 
53475 /*
53476 ** This function changes all write-locks held by Btree p into read-locks.
53477 */
53478 static void downgradeAllSharedCacheTableLocks(Btree *p){
53479   BtShared *pBt = p->pBt;
53480   if( pBt->pWriter==p ){
53481     BtLock *pLock;
53482     pBt->pWriter = 0;
53483     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
53484     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
53485       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
53486       pLock->eLock = READ_LOCK;
53487     }
53488   }
53489 }
53490 
53491 #endif /* SQLITE_OMIT_SHARED_CACHE */
53492 
53493 static void releasePage(MemPage *pPage);  /* Forward reference */
53494 
53495 /*
53496 ***** This routine is used inside of assert() only ****
53497 **
53498 ** Verify that the cursor holds the mutex on its BtShared
53499 */
53500 #ifdef SQLITE_DEBUG
53501 static int cursorHoldsMutex(BtCursor *p){
53502   return sqlite3_mutex_held(p->pBt->mutex);
53503 }
53504 #endif
53505 
53506 /*
53507 ** Invalidate the overflow cache of the cursor passed as the first argument.
53508 ** on the shared btree structure pBt.
53509 */
53510 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
53511 
53512 /*
53513 ** Invalidate the overflow page-list cache for all cursors opened
53514 ** on the shared btree structure pBt.
53515 */
53516 static void invalidateAllOverflowCache(BtShared *pBt){
53517   BtCursor *p;
53518   assert( sqlite3_mutex_held(pBt->mutex) );
53519   for(p=pBt->pCursor; p; p=p->pNext){
53520     invalidateOverflowCache(p);
53521   }
53522 }
53523 
53524 #ifndef SQLITE_OMIT_INCRBLOB
53525 /*
53526 ** This function is called before modifying the contents of a table
53527 ** to invalidate any incrblob cursors that are open on the
53528 ** row or one of the rows being modified.
53529 **
53530 ** If argument isClearTable is true, then the entire contents of the
53531 ** table is about to be deleted. In this case invalidate all incrblob
53532 ** cursors open on any row within the table with root-page pgnoRoot.
53533 **
53534 ** Otherwise, if argument isClearTable is false, then the row with
53535 ** rowid iRow is being replaced or deleted. In this case invalidate
53536 ** only those incrblob cursors open on that specific row.
53537 */
53538 static void invalidateIncrblobCursors(
53539   Btree *pBtree,          /* The database file to check */
53540   i64 iRow,               /* The rowid that might be changing */
53541   int isClearTable        /* True if all rows are being deleted */
53542 ){
53543   BtCursor *p;
53544   BtShared *pBt = pBtree->pBt;
53545   assert( sqlite3BtreeHoldsMutex(pBtree) );
53546   for(p=pBt->pCursor; p; p=p->pNext){
53547     if( (p->curFlags & BTCF_Incrblob)!=0
53548      && (isClearTable || p->info.nKey==iRow)
53549     ){
53550       p->eState = CURSOR_INVALID;
53551     }
53552   }
53553 }
53554 
53555 #else
53556   /* Stub function when INCRBLOB is omitted */
53557   #define invalidateIncrblobCursors(x,y,z)
53558 #endif /* SQLITE_OMIT_INCRBLOB */
53559 
53560 /*
53561 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
53562 ** when a page that previously contained data becomes a free-list leaf
53563 ** page.
53564 **
53565 ** The BtShared.pHasContent bitvec exists to work around an obscure
53566 ** bug caused by the interaction of two useful IO optimizations surrounding
53567 ** free-list leaf pages:
53568 **
53569 **   1) When all data is deleted from a page and the page becomes
53570 **      a free-list leaf page, the page is not written to the database
53571 **      (as free-list leaf pages contain no meaningful data). Sometimes
53572 **      such a page is not even journalled (as it will not be modified,
53573 **      why bother journalling it?).
53574 **
53575 **   2) When a free-list leaf page is reused, its content is not read
53576 **      from the database or written to the journal file (why should it
53577 **      be, if it is not at all meaningful?).
53578 **
53579 ** By themselves, these optimizations work fine and provide a handy
53580 ** performance boost to bulk delete or insert operations. However, if
53581 ** a page is moved to the free-list and then reused within the same
53582 ** transaction, a problem comes up. If the page is not journalled when
53583 ** it is moved to the free-list and it is also not journalled when it
53584 ** is extracted from the free-list and reused, then the original data
53585 ** may be lost. In the event of a rollback, it may not be possible
53586 ** to restore the database to its original configuration.
53587 **
53588 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
53589 ** moved to become a free-list leaf page, the corresponding bit is
53590 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
53591 ** optimization 2 above is omitted if the corresponding bit is already
53592 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
53593 ** at the end of every transaction.
53594 */
53595 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
53596   int rc = SQLITE_OK;
53597   if( !pBt->pHasContent ){
53598     assert( pgno<=pBt->nPage );
53599     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
53600     if( !pBt->pHasContent ){
53601       rc = SQLITE_NOMEM;
53602     }
53603   }
53604   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
53605     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
53606   }
53607   return rc;
53608 }
53609 
53610 /*
53611 ** Query the BtShared.pHasContent vector.
53612 **
53613 ** This function is called when a free-list leaf page is removed from the
53614 ** free-list for reuse. It returns false if it is safe to retrieve the
53615 ** page from the pager layer with the 'no-content' flag set. True otherwise.
53616 */
53617 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
53618   Bitvec *p = pBt->pHasContent;
53619   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
53620 }
53621 
53622 /*
53623 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
53624 ** invoked at the conclusion of each write-transaction.
53625 */
53626 static void btreeClearHasContent(BtShared *pBt){
53627   sqlite3BitvecDestroy(pBt->pHasContent);
53628   pBt->pHasContent = 0;
53629 }
53630 
53631 /*
53632 ** Release all of the apPage[] pages for a cursor.
53633 */
53634 static void btreeReleaseAllCursorPages(BtCursor *pCur){
53635   int i;
53636   for(i=0; i<=pCur->iPage; i++){
53637     releasePage(pCur->apPage[i]);
53638     pCur->apPage[i] = 0;
53639   }
53640   pCur->iPage = -1;
53641 }
53642 
53643 
53644 /*
53645 ** Save the current cursor position in the variables BtCursor.nKey
53646 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
53647 **
53648 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
53649 ** prior to calling this routine.
53650 */
53651 static int saveCursorPosition(BtCursor *pCur){
53652   int rc;
53653 
53654   assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
53655   assert( 0==pCur->pKey );
53656   assert( cursorHoldsMutex(pCur) );
53657 
53658   if( pCur->eState==CURSOR_SKIPNEXT ){
53659     pCur->eState = CURSOR_VALID;
53660   }else{
53661     pCur->skipNext = 0;
53662   }
53663   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
53664   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
53665 
53666   /* If this is an intKey table, then the above call to BtreeKeySize()
53667   ** stores the integer key in pCur->nKey. In this case this value is
53668   ** all that is required. Otherwise, if pCur is not open on an intKey
53669   ** table, then malloc space for and store the pCur->nKey bytes of key
53670   ** data.
53671   */
53672   if( 0==pCur->apPage[0]->intKey ){
53673     void *pKey = sqlite3Malloc( pCur->nKey );
53674     if( pKey ){
53675       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
53676       if( rc==SQLITE_OK ){
53677         pCur->pKey = pKey;
53678       }else{
53679         sqlite3_free(pKey);
53680       }
53681     }else{
53682       rc = SQLITE_NOMEM;
53683     }
53684   }
53685   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
53686 
53687   if( rc==SQLITE_OK ){
53688     btreeReleaseAllCursorPages(pCur);
53689     pCur->eState = CURSOR_REQUIRESEEK;
53690   }
53691 
53692   invalidateOverflowCache(pCur);
53693   return rc;
53694 }
53695 
53696 /* Forward reference */
53697 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
53698 
53699 /*
53700 ** Save the positions of all cursors (except pExcept) that are open on
53701 ** the table with root-page iRoot.  "Saving the cursor position" means that
53702 ** the location in the btree is remembered in such a way that it can be
53703 ** moved back to the same spot after the btree has been modified.  This
53704 ** routine is called just before cursor pExcept is used to modify the
53705 ** table, for example in BtreeDelete() or BtreeInsert().
53706 **
53707 ** Implementation note:  This routine merely checks to see if any cursors
53708 ** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
53709 ** event that cursors are in need to being saved.
53710 */
53711 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
53712   BtCursor *p;
53713   assert( sqlite3_mutex_held(pBt->mutex) );
53714   assert( pExcept==0 || pExcept->pBt==pBt );
53715   for(p=pBt->pCursor; p; p=p->pNext){
53716     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
53717   }
53718   return p ? saveCursorsOnList(p, iRoot, pExcept) : SQLITE_OK;
53719 }
53720 
53721 /* This helper routine to saveAllCursors does the actual work of saving
53722 ** the cursors if and when a cursor is found that actually requires saving.
53723 ** The common case is that no cursors need to be saved, so this routine is
53724 ** broken out from its caller to avoid unnecessary stack pointer movement.
53725 */
53726 static int SQLITE_NOINLINE saveCursorsOnList(
53727   BtCursor *p,         /* The first cursor that needs saving */
53728   Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
53729   BtCursor *pExcept    /* Do not save this cursor */
53730 ){
53731   do{
53732     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
53733       if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
53734         int rc = saveCursorPosition(p);
53735         if( SQLITE_OK!=rc ){
53736           return rc;
53737         }
53738       }else{
53739         testcase( p->iPage>0 );
53740         btreeReleaseAllCursorPages(p);
53741       }
53742     }
53743     p = p->pNext;
53744   }while( p );
53745   return SQLITE_OK;
53746 }
53747 
53748 /*
53749 ** Clear the current cursor position.
53750 */
53751 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
53752   assert( cursorHoldsMutex(pCur) );
53753   sqlite3_free(pCur->pKey);
53754   pCur->pKey = 0;
53755   pCur->eState = CURSOR_INVALID;
53756 }
53757 
53758 /*
53759 ** In this version of BtreeMoveto, pKey is a packed index record
53760 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
53761 ** record and then call BtreeMovetoUnpacked() to do the work.
53762 */
53763 static int btreeMoveto(
53764   BtCursor *pCur,     /* Cursor open on the btree to be searched */
53765   const void *pKey,   /* Packed key if the btree is an index */
53766   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
53767   int bias,           /* Bias search to the high end */
53768   int *pRes           /* Write search results here */
53769 ){
53770   int rc;                    /* Status code */
53771   UnpackedRecord *pIdxKey;   /* Unpacked index key */
53772   char aSpace[200];          /* Temp space for pIdxKey - to avoid a malloc */
53773   char *pFree = 0;
53774 
53775   if( pKey ){
53776     assert( nKey==(i64)(int)nKey );
53777     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
53778         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
53779     );
53780     if( pIdxKey==0 ) return SQLITE_NOMEM;
53781     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
53782     if( pIdxKey->nField==0 ){
53783       sqlite3DbFree(pCur->pKeyInfo->db, pFree);
53784       return SQLITE_CORRUPT_BKPT;
53785     }
53786   }else{
53787     pIdxKey = 0;
53788   }
53789   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
53790   if( pFree ){
53791     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
53792   }
53793   return rc;
53794 }
53795 
53796 /*
53797 ** Restore the cursor to the position it was in (or as close to as possible)
53798 ** when saveCursorPosition() was called. Note that this call deletes the
53799 ** saved position info stored by saveCursorPosition(), so there can be
53800 ** at most one effective restoreCursorPosition() call after each
53801 ** saveCursorPosition().
53802 */
53803 static int btreeRestoreCursorPosition(BtCursor *pCur){
53804   int rc;
53805   int skipNext;
53806   assert( cursorHoldsMutex(pCur) );
53807   assert( pCur->eState>=CURSOR_REQUIRESEEK );
53808   if( pCur->eState==CURSOR_FAULT ){
53809     return pCur->skipNext;
53810   }
53811   pCur->eState = CURSOR_INVALID;
53812   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
53813   if( rc==SQLITE_OK ){
53814     sqlite3_free(pCur->pKey);
53815     pCur->pKey = 0;
53816     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
53817     pCur->skipNext |= skipNext;
53818     if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
53819       pCur->eState = CURSOR_SKIPNEXT;
53820     }
53821   }
53822   return rc;
53823 }
53824 
53825 #define restoreCursorPosition(p) \
53826   (p->eState>=CURSOR_REQUIRESEEK ? \
53827          btreeRestoreCursorPosition(p) : \
53828          SQLITE_OK)
53829 
53830 /*
53831 ** Determine whether or not a cursor has moved from the position where
53832 ** it was last placed, or has been invalidated for any other reason.
53833 ** Cursors can move when the row they are pointing at is deleted out
53834 ** from under them, for example.  Cursor might also move if a btree
53835 ** is rebalanced.
53836 **
53837 ** Calling this routine with a NULL cursor pointer returns false.
53838 **
53839 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
53840 ** back to where it ought to be if this routine returns true.
53841 */
53842 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
53843   return pCur->eState!=CURSOR_VALID;
53844 }
53845 
53846 /*
53847 ** This routine restores a cursor back to its original position after it
53848 ** has been moved by some outside activity (such as a btree rebalance or
53849 ** a row having been deleted out from under the cursor).
53850 **
53851 ** On success, the *pDifferentRow parameter is false if the cursor is left
53852 ** pointing at exactly the same row.  *pDifferntRow is the row the cursor
53853 ** was pointing to has been deleted, forcing the cursor to point to some
53854 ** nearby row.
53855 **
53856 ** This routine should only be called for a cursor that just returned
53857 ** TRUE from sqlite3BtreeCursorHasMoved().
53858 */
53859 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
53860   int rc;
53861 
53862   assert( pCur!=0 );
53863   assert( pCur->eState!=CURSOR_VALID );
53864   rc = restoreCursorPosition(pCur);
53865   if( rc ){
53866     *pDifferentRow = 1;
53867     return rc;
53868   }
53869   if( pCur->eState!=CURSOR_VALID ){
53870     *pDifferentRow = 1;
53871   }else{
53872     assert( pCur->skipNext==0 );
53873     *pDifferentRow = 0;
53874   }
53875   return SQLITE_OK;
53876 }
53877 
53878 #ifndef SQLITE_OMIT_AUTOVACUUM
53879 /*
53880 ** Given a page number of a regular database page, return the page
53881 ** number for the pointer-map page that contains the entry for the
53882 ** input page number.
53883 **
53884 ** Return 0 (not a valid page) for pgno==1 since there is
53885 ** no pointer map associated with page 1.  The integrity_check logic
53886 ** requires that ptrmapPageno(*,1)!=1.
53887 */
53888 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
53889   int nPagesPerMapPage;
53890   Pgno iPtrMap, ret;
53891   assert( sqlite3_mutex_held(pBt->mutex) );
53892   if( pgno<2 ) return 0;
53893   nPagesPerMapPage = (pBt->usableSize/5)+1;
53894   iPtrMap = (pgno-2)/nPagesPerMapPage;
53895   ret = (iPtrMap*nPagesPerMapPage) + 2;
53896   if( ret==PENDING_BYTE_PAGE(pBt) ){
53897     ret++;
53898   }
53899   return ret;
53900 }
53901 
53902 /*
53903 ** Write an entry into the pointer map.
53904 **
53905 ** This routine updates the pointer map entry for page number 'key'
53906 ** so that it maps to type 'eType' and parent page number 'pgno'.
53907 **
53908 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
53909 ** a no-op.  If an error occurs, the appropriate error code is written
53910 ** into *pRC.
53911 */
53912 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
53913   DbPage *pDbPage;  /* The pointer map page */
53914   u8 *pPtrmap;      /* The pointer map data */
53915   Pgno iPtrmap;     /* The pointer map page number */
53916   int offset;       /* Offset in pointer map page */
53917   int rc;           /* Return code from subfunctions */
53918 
53919   if( *pRC ) return;
53920 
53921   assert( sqlite3_mutex_held(pBt->mutex) );
53922   /* The master-journal page number must never be used as a pointer map page */
53923   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
53924 
53925   assert( pBt->autoVacuum );
53926   if( key==0 ){
53927     *pRC = SQLITE_CORRUPT_BKPT;
53928     return;
53929   }
53930   iPtrmap = PTRMAP_PAGENO(pBt, key);
53931   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
53932   if( rc!=SQLITE_OK ){
53933     *pRC = rc;
53934     return;
53935   }
53936   offset = PTRMAP_PTROFFSET(iPtrmap, key);
53937   if( offset<0 ){
53938     *pRC = SQLITE_CORRUPT_BKPT;
53939     goto ptrmap_exit;
53940   }
53941   assert( offset <= (int)pBt->usableSize-5 );
53942   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
53943 
53944   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
53945     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
53946     *pRC= rc = sqlite3PagerWrite(pDbPage);
53947     if( rc==SQLITE_OK ){
53948       pPtrmap[offset] = eType;
53949       put4byte(&pPtrmap[offset+1], parent);
53950     }
53951   }
53952 
53953 ptrmap_exit:
53954   sqlite3PagerUnref(pDbPage);
53955 }
53956 
53957 /*
53958 ** Read an entry from the pointer map.
53959 **
53960 ** This routine retrieves the pointer map entry for page 'key', writing
53961 ** the type and parent page number to *pEType and *pPgno respectively.
53962 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
53963 */
53964 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
53965   DbPage *pDbPage;   /* The pointer map page */
53966   int iPtrmap;       /* Pointer map page index */
53967   u8 *pPtrmap;       /* Pointer map page data */
53968   int offset;        /* Offset of entry in pointer map */
53969   int rc;
53970 
53971   assert( sqlite3_mutex_held(pBt->mutex) );
53972 
53973   iPtrmap = PTRMAP_PAGENO(pBt, key);
53974   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
53975   if( rc!=0 ){
53976     return rc;
53977   }
53978   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
53979 
53980   offset = PTRMAP_PTROFFSET(iPtrmap, key);
53981   if( offset<0 ){
53982     sqlite3PagerUnref(pDbPage);
53983     return SQLITE_CORRUPT_BKPT;
53984   }
53985   assert( offset <= (int)pBt->usableSize-5 );
53986   assert( pEType!=0 );
53987   *pEType = pPtrmap[offset];
53988   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
53989 
53990   sqlite3PagerUnref(pDbPage);
53991   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
53992   return SQLITE_OK;
53993 }
53994 
53995 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
53996   #define ptrmapPut(w,x,y,z,rc)
53997   #define ptrmapGet(w,x,y,z) SQLITE_OK
53998   #define ptrmapPutOvflPtr(x, y, rc)
53999 #endif
54000 
54001 /*
54002 ** Given a btree page and a cell index (0 means the first cell on
54003 ** the page, 1 means the second cell, and so forth) return a pointer
54004 ** to the cell content.
54005 **
54006 ** This routine works only for pages that do not contain overflow cells.
54007 */
54008 #define findCell(P,I) \
54009   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
54010 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
54011 
54012 
54013 /*
54014 ** This a more complex version of findCell() that works for
54015 ** pages that do contain overflow cells.
54016 */
54017 static u8 *findOverflowCell(MemPage *pPage, int iCell){
54018   int i;
54019   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54020   for(i=pPage->nOverflow-1; i>=0; i--){
54021     int k;
54022     k = pPage->aiOvfl[i];
54023     if( k<=iCell ){
54024       if( k==iCell ){
54025         return pPage->apOvfl[i];
54026       }
54027       iCell--;
54028     }
54029   }
54030   return findCell(pPage, iCell);
54031 }
54032 
54033 /*
54034 ** Parse a cell content block and fill in the CellInfo structure.  There
54035 ** are two versions of this function.  btreeParseCell() takes a
54036 ** cell index as the second argument and btreeParseCellPtr()
54037 ** takes a pointer to the body of the cell as its second argument.
54038 */
54039 static void btreeParseCellPtr(
54040   MemPage *pPage,         /* Page containing the cell */
54041   u8 *pCell,              /* Pointer to the cell text. */
54042   CellInfo *pInfo         /* Fill in this structure */
54043 ){
54044   u8 *pIter;              /* For scanning through pCell */
54045   u32 nPayload;           /* Number of bytes of cell payload */
54046 
54047   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54048   assert( pPage->leaf==0 || pPage->leaf==1 );
54049   if( pPage->intKeyLeaf ){
54050     assert( pPage->childPtrSize==0 );
54051     pIter = pCell + getVarint32(pCell, nPayload);
54052     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
54053   }else if( pPage->noPayload ){
54054     assert( pPage->childPtrSize==4 );
54055     pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
54056     pInfo->nPayload = 0;
54057     pInfo->nLocal = 0;
54058     pInfo->iOverflow = 0;
54059     pInfo->pPayload = 0;
54060     return;
54061   }else{
54062     pIter = pCell + pPage->childPtrSize;
54063     pIter += getVarint32(pIter, nPayload);
54064     pInfo->nKey = nPayload;
54065   }
54066   pInfo->nPayload = nPayload;
54067   pInfo->pPayload = pIter;
54068   testcase( nPayload==pPage->maxLocal );
54069   testcase( nPayload==pPage->maxLocal+1 );
54070   if( nPayload<=pPage->maxLocal ){
54071     /* This is the (easy) common case where the entire payload fits
54072     ** on the local page.  No overflow is required.
54073     */
54074     pInfo->nSize = nPayload + (u16)(pIter - pCell);
54075     if( pInfo->nSize<4 ) pInfo->nSize = 4;
54076     pInfo->nLocal = (u16)nPayload;
54077     pInfo->iOverflow = 0;
54078   }else{
54079     /* If the payload will not fit completely on the local page, we have
54080     ** to decide how much to store locally and how much to spill onto
54081     ** overflow pages.  The strategy is to minimize the amount of unused
54082     ** space on overflow pages while keeping the amount of local storage
54083     ** in between minLocal and maxLocal.
54084     **
54085     ** Warning:  changing the way overflow payload is distributed in any
54086     ** way will result in an incompatible file format.
54087     */
54088     int minLocal;  /* Minimum amount of payload held locally */
54089     int maxLocal;  /* Maximum amount of payload held locally */
54090     int surplus;   /* Overflow payload available for local storage */
54091 
54092     minLocal = pPage->minLocal;
54093     maxLocal = pPage->maxLocal;
54094     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
54095     testcase( surplus==maxLocal );
54096     testcase( surplus==maxLocal+1 );
54097     if( surplus <= maxLocal ){
54098       pInfo->nLocal = (u16)surplus;
54099     }else{
54100       pInfo->nLocal = (u16)minLocal;
54101     }
54102     pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
54103     pInfo->nSize = pInfo->iOverflow + 4;
54104   }
54105 }
54106 static void btreeParseCell(
54107   MemPage *pPage,         /* Page containing the cell */
54108   int iCell,              /* The cell index.  First cell is 0 */
54109   CellInfo *pInfo         /* Fill in this structure */
54110 ){
54111   btreeParseCellPtr(pPage, findCell(pPage, iCell), pInfo);
54112 }
54113 
54114 /*
54115 ** Compute the total number of bytes that a Cell needs in the cell
54116 ** data area of the btree-page.  The return number includes the cell
54117 ** data header and the local payload, but not any overflow page or
54118 ** the space used by the cell pointer.
54119 */
54120 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
54121   u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
54122   u8 *pEnd;                                /* End mark for a varint */
54123   u32 nSize;                               /* Size value to return */
54124 
54125 #ifdef SQLITE_DEBUG
54126   /* The value returned by this function should always be the same as
54127   ** the (CellInfo.nSize) value found by doing a full parse of the
54128   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
54129   ** this function verifies that this invariant is not violated. */
54130   CellInfo debuginfo;
54131   btreeParseCellPtr(pPage, pCell, &debuginfo);
54132 #endif
54133 
54134   if( pPage->noPayload ){
54135     pEnd = &pIter[9];
54136     while( (*pIter++)&0x80 && pIter<pEnd );
54137     assert( pPage->childPtrSize==4 );
54138     return (u16)(pIter - pCell);
54139   }
54140   nSize = *pIter;
54141   if( nSize>=0x80 ){
54142     pEnd = &pIter[9];
54143     nSize &= 0x7f;
54144     do{
54145       nSize = (nSize<<7) | (*++pIter & 0x7f);
54146     }while( *(pIter)>=0x80 && pIter<pEnd );
54147   }
54148   pIter++;
54149   if( pPage->intKey ){
54150     /* pIter now points at the 64-bit integer key value, a variable length
54151     ** integer. The following block moves pIter to point at the first byte
54152     ** past the end of the key value. */
54153     pEnd = &pIter[9];
54154     while( (*pIter++)&0x80 && pIter<pEnd );
54155   }
54156   testcase( nSize==pPage->maxLocal );
54157   testcase( nSize==pPage->maxLocal+1 );
54158   if( nSize<=pPage->maxLocal ){
54159     nSize += (u32)(pIter - pCell);
54160     if( nSize<4 ) nSize = 4;
54161   }else{
54162     int minLocal = pPage->minLocal;
54163     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
54164     testcase( nSize==pPage->maxLocal );
54165     testcase( nSize==pPage->maxLocal+1 );
54166     if( nSize>pPage->maxLocal ){
54167       nSize = minLocal;
54168     }
54169     nSize += 4 + (u16)(pIter - pCell);
54170   }
54171   assert( nSize==debuginfo.nSize || CORRUPT_DB );
54172   return (u16)nSize;
54173 }
54174 
54175 #ifdef SQLITE_DEBUG
54176 /* This variation on cellSizePtr() is used inside of assert() statements
54177 ** only. */
54178 static u16 cellSize(MemPage *pPage, int iCell){
54179   return cellSizePtr(pPage, findCell(pPage, iCell));
54180 }
54181 #endif
54182 
54183 #ifndef SQLITE_OMIT_AUTOVACUUM
54184 /*
54185 ** If the cell pCell, part of page pPage contains a pointer
54186 ** to an overflow page, insert an entry into the pointer-map
54187 ** for the overflow page.
54188 */
54189 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
54190   CellInfo info;
54191   if( *pRC ) return;
54192   assert( pCell!=0 );
54193   btreeParseCellPtr(pPage, pCell, &info);
54194   if( info.iOverflow ){
54195     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
54196     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
54197   }
54198 }
54199 #endif
54200 
54201 
54202 /*
54203 ** Defragment the page given.  All Cells are moved to the
54204 ** end of the page and all free space is collected into one
54205 ** big FreeBlk that occurs in between the header and cell
54206 ** pointer array and the cell content area.
54207 **
54208 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
54209 ** b-tree page so that there are no freeblocks or fragment bytes, all
54210 ** unused bytes are contained in the unallocated space region, and all
54211 ** cells are packed tightly at the end of the page.
54212 */
54213 static int defragmentPage(MemPage *pPage){
54214   int i;                     /* Loop counter */
54215   int pc;                    /* Address of the i-th cell */
54216   int hdr;                   /* Offset to the page header */
54217   int size;                  /* Size of a cell */
54218   int usableSize;            /* Number of usable bytes on a page */
54219   int cellOffset;            /* Offset to the cell pointer array */
54220   int cbrk;                  /* Offset to the cell content area */
54221   int nCell;                 /* Number of cells on the page */
54222   unsigned char *data;       /* The page data */
54223   unsigned char *temp;       /* Temp area for cell content */
54224   unsigned char *src;        /* Source of content */
54225   int iCellFirst;            /* First allowable cell index */
54226   int iCellLast;             /* Last possible cell index */
54227 
54228 
54229   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54230   assert( pPage->pBt!=0 );
54231   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
54232   assert( pPage->nOverflow==0 );
54233   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54234   temp = 0;
54235   src = data = pPage->aData;
54236   hdr = pPage->hdrOffset;
54237   cellOffset = pPage->cellOffset;
54238   nCell = pPage->nCell;
54239   assert( nCell==get2byte(&data[hdr+3]) );
54240   usableSize = pPage->pBt->usableSize;
54241   cbrk = usableSize;
54242   iCellFirst = cellOffset + 2*nCell;
54243   iCellLast = usableSize - 4;
54244   for(i=0; i<nCell; i++){
54245     u8 *pAddr;     /* The i-th cell pointer */
54246     pAddr = &data[cellOffset + i*2];
54247     pc = get2byte(pAddr);
54248     testcase( pc==iCellFirst );
54249     testcase( pc==iCellLast );
54250 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
54251     /* These conditions have already been verified in btreeInitPage()
54252     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
54253     */
54254     if( pc<iCellFirst || pc>iCellLast ){
54255       return SQLITE_CORRUPT_BKPT;
54256     }
54257 #endif
54258     assert( pc>=iCellFirst && pc<=iCellLast );
54259     size = cellSizePtr(pPage, &src[pc]);
54260     cbrk -= size;
54261 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
54262     if( cbrk<iCellFirst ){
54263       return SQLITE_CORRUPT_BKPT;
54264     }
54265 #else
54266     if( cbrk<iCellFirst || pc+size>usableSize ){
54267       return SQLITE_CORRUPT_BKPT;
54268     }
54269 #endif
54270     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
54271     testcase( cbrk+size==usableSize );
54272     testcase( pc+size==usableSize );
54273     put2byte(pAddr, cbrk);
54274     if( temp==0 ){
54275       int x;
54276       if( cbrk==pc ) continue;
54277       temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
54278       x = get2byte(&data[hdr+5]);
54279       memcpy(&temp[x], &data[x], (cbrk+size) - x);
54280       src = temp;
54281     }
54282     memcpy(&data[cbrk], &src[pc], size);
54283   }
54284   assert( cbrk>=iCellFirst );
54285   put2byte(&data[hdr+5], cbrk);
54286   data[hdr+1] = 0;
54287   data[hdr+2] = 0;
54288   data[hdr+7] = 0;
54289   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
54290   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54291   if( cbrk-iCellFirst!=pPage->nFree ){
54292     return SQLITE_CORRUPT_BKPT;
54293   }
54294   return SQLITE_OK;
54295 }
54296 
54297 /*
54298 ** Search the free-list on page pPg for space to store a cell nByte bytes in
54299 ** size. If one can be found, return a pointer to the space and remove it
54300 ** from the free-list.
54301 **
54302 ** If no suitable space can be found on the free-list, return NULL.
54303 **
54304 ** This function may detect corruption within pPg.  If corruption is
54305 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
54306 **
54307 ** If a slot of at least nByte bytes is found but cannot be used because
54308 ** there are already at least 60 fragmented bytes on the page, return NULL.
54309 ** In this case, if pbDefrag parameter is not NULL, set *pbDefrag to true.
54310 */
54311 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc, int *pbDefrag){
54312   const int hdr = pPg->hdrOffset;
54313   u8 * const aData = pPg->aData;
54314   int iAddr;
54315   int pc;
54316   int usableSize = pPg->pBt->usableSize;
54317 
54318   for(iAddr=hdr+1; (pc = get2byte(&aData[iAddr]))>0; iAddr=pc){
54319     int size;            /* Size of the free slot */
54320     /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
54321     ** increasing offset. */
54322     if( pc>usableSize-4 || pc<iAddr+4 ){
54323       *pRc = SQLITE_CORRUPT_BKPT;
54324       return 0;
54325     }
54326     /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
54327     ** freeblock form a big-endian integer which is the size of the freeblock
54328     ** in bytes, including the 4-byte header. */
54329     size = get2byte(&aData[pc+2]);
54330     if( size>=nByte ){
54331       int x = size - nByte;
54332       testcase( x==4 );
54333       testcase( x==3 );
54334       if( x<4 ){
54335         /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
54336         ** number of bytes in fragments may not exceed 60. */
54337         if( aData[hdr+7]>=60 ){
54338           if( pbDefrag ) *pbDefrag = 1;
54339           return 0;
54340         }
54341         /* Remove the slot from the free-list. Update the number of
54342         ** fragmented bytes within the page. */
54343         memcpy(&aData[iAddr], &aData[pc], 2);
54344         aData[hdr+7] += (u8)x;
54345       }else if( size+pc > usableSize ){
54346         *pRc = SQLITE_CORRUPT_BKPT;
54347         return 0;
54348       }else{
54349         /* The slot remains on the free-list. Reduce its size to account
54350          ** for the portion used by the new allocation. */
54351         put2byte(&aData[pc+2], x);
54352       }
54353       return &aData[pc + x];
54354     }
54355   }
54356 
54357   return 0;
54358 }
54359 
54360 /*
54361 ** Allocate nByte bytes of space from within the B-Tree page passed
54362 ** as the first argument. Write into *pIdx the index into pPage->aData[]
54363 ** of the first byte of allocated space. Return either SQLITE_OK or
54364 ** an error code (usually SQLITE_CORRUPT).
54365 **
54366 ** The caller guarantees that there is sufficient space to make the
54367 ** allocation.  This routine might need to defragment in order to bring
54368 ** all the space together, however.  This routine will avoid using
54369 ** the first two bytes past the cell pointer area since presumably this
54370 ** allocation is being made in order to insert a new cell, so we will
54371 ** also end up needing a new cell pointer.
54372 */
54373 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
54374   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
54375   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
54376   int top;                             /* First byte of cell content area */
54377   int rc = SQLITE_OK;                  /* Integer return code */
54378   int gap;        /* First byte of gap between cell pointers and cell content */
54379 
54380   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54381   assert( pPage->pBt );
54382   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54383   assert( nByte>=0 );  /* Minimum cell size is 4 */
54384   assert( pPage->nFree>=nByte );
54385   assert( pPage->nOverflow==0 );
54386   assert( nByte < (int)(pPage->pBt->usableSize-8) );
54387 
54388   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
54389   gap = pPage->cellOffset + 2*pPage->nCell;
54390   assert( gap<=65536 );
54391   /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
54392   ** and the reserved space is zero (the usual value for reserved space)
54393   ** then the cell content offset of an empty page wants to be 65536.
54394   ** However, that integer is too large to be stored in a 2-byte unsigned
54395   ** integer, so a value of 0 is used in its place. */
54396   top = get2byteNotZero(&data[hdr+5]);
54397   if( gap>top ) return SQLITE_CORRUPT_BKPT;
54398 
54399   /* If there is enough space between gap and top for one more cell pointer
54400   ** array entry offset, and if the freelist is not empty, then search the
54401   ** freelist looking for a free slot big enough to satisfy the request.
54402   */
54403   testcase( gap+2==top );
54404   testcase( gap+1==top );
54405   testcase( gap==top );
54406   if( gap+2<=top && (data[hdr+1] || data[hdr+2]) ){
54407     int bDefrag = 0;
54408     u8 *pSpace = pageFindSlot(pPage, nByte, &rc, &bDefrag);
54409     if( rc ) return rc;
54410     if( bDefrag ) goto defragment_page;
54411     if( pSpace ){
54412       assert( pSpace>=data && (pSpace - data)<65536 );
54413       *pIdx = (int)(pSpace - data);
54414       return SQLITE_OK;
54415     }
54416   }
54417 
54418   /* The request could not be fulfilled using a freelist slot.  Check
54419   ** to see if defragmentation is necessary.
54420   */
54421   testcase( gap+2+nByte==top );
54422   if( gap+2+nByte>top ){
54423  defragment_page:
54424     assert( pPage->nCell>0 || CORRUPT_DB );
54425     rc = defragmentPage(pPage);
54426     if( rc ) return rc;
54427     top = get2byteNotZero(&data[hdr+5]);
54428     assert( gap+nByte<=top );
54429   }
54430 
54431 
54432   /* Allocate memory from the gap in between the cell pointer array
54433   ** and the cell content area.  The btreeInitPage() call has already
54434   ** validated the freelist.  Given that the freelist is valid, there
54435   ** is no way that the allocation can extend off the end of the page.
54436   ** The assert() below verifies the previous sentence.
54437   */
54438   top -= nByte;
54439   put2byte(&data[hdr+5], top);
54440   assert( top+nByte <= (int)pPage->pBt->usableSize );
54441   *pIdx = top;
54442   return SQLITE_OK;
54443 }
54444 
54445 /*
54446 ** Return a section of the pPage->aData to the freelist.
54447 ** The first byte of the new free block is pPage->aData[iStart]
54448 ** and the size of the block is iSize bytes.
54449 **
54450 ** Adjacent freeblocks are coalesced.
54451 **
54452 ** Note that even though the freeblock list was checked by btreeInitPage(),
54453 ** that routine will not detect overlap between cells or freeblocks.  Nor
54454 ** does it detect cells or freeblocks that encrouch into the reserved bytes
54455 ** at the end of the page.  So do additional corruption checks inside this
54456 ** routine and return SQLITE_CORRUPT if any problems are found.
54457 */
54458 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
54459   u16 iPtr;                             /* Address of ptr to next freeblock */
54460   u16 iFreeBlk;                         /* Address of the next freeblock */
54461   u8 hdr;                               /* Page header size.  0 or 100 */
54462   u8 nFrag = 0;                         /* Reduction in fragmentation */
54463   u16 iOrigSize = iSize;                /* Original value of iSize */
54464   u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
54465   u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
54466   unsigned char *data = pPage->aData;   /* Page content */
54467 
54468   assert( pPage->pBt!=0 );
54469   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54470   assert( iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
54471   assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
54472   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54473   assert( iSize>=4 );   /* Minimum cell size is 4 */
54474   assert( iStart<=iLast );
54475 
54476   /* Overwrite deleted information with zeros when the secure_delete
54477   ** option is enabled */
54478   if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
54479     memset(&data[iStart], 0, iSize);
54480   }
54481 
54482   /* The list of freeblocks must be in ascending order.  Find the
54483   ** spot on the list where iStart should be inserted.
54484   */
54485   hdr = pPage->hdrOffset;
54486   iPtr = hdr + 1;
54487   if( data[iPtr+1]==0 && data[iPtr]==0 ){
54488     iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
54489   }else{
54490     while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
54491       if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
54492       iPtr = iFreeBlk;
54493     }
54494     if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
54495     assert( iFreeBlk>iPtr || iFreeBlk==0 );
54496 
54497     /* At this point:
54498     **    iFreeBlk:   First freeblock after iStart, or zero if none
54499     **    iPtr:       The address of a pointer iFreeBlk
54500     **
54501     ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
54502     */
54503     if( iFreeBlk && iEnd+3>=iFreeBlk ){
54504       nFrag = iFreeBlk - iEnd;
54505       if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
54506       iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
54507       iSize = iEnd - iStart;
54508       iFreeBlk = get2byte(&data[iFreeBlk]);
54509     }
54510 
54511     /* If iPtr is another freeblock (that is, if iPtr is not the freelist
54512     ** pointer in the page header) then check to see if iStart should be
54513     ** coalesced onto the end of iPtr.
54514     */
54515     if( iPtr>hdr+1 ){
54516       int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
54517       if( iPtrEnd+3>=iStart ){
54518         if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
54519         nFrag += iStart - iPtrEnd;
54520         iSize = iEnd - iPtr;
54521         iStart = iPtr;
54522       }
54523     }
54524     if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
54525     data[hdr+7] -= nFrag;
54526   }
54527   if( iStart==get2byte(&data[hdr+5]) ){
54528     /* The new freeblock is at the beginning of the cell content area,
54529     ** so just extend the cell content area rather than create another
54530     ** freelist entry */
54531     if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
54532     put2byte(&data[hdr+1], iFreeBlk);
54533     put2byte(&data[hdr+5], iEnd);
54534   }else{
54535     /* Insert the new freeblock into the freelist */
54536     put2byte(&data[iPtr], iStart);
54537     put2byte(&data[iStart], iFreeBlk);
54538     put2byte(&data[iStart+2], iSize);
54539   }
54540   pPage->nFree += iOrigSize;
54541   return SQLITE_OK;
54542 }
54543 
54544 /*
54545 ** Decode the flags byte (the first byte of the header) for a page
54546 ** and initialize fields of the MemPage structure accordingly.
54547 **
54548 ** Only the following combinations are supported.  Anything different
54549 ** indicates a corrupt database files:
54550 **
54551 **         PTF_ZERODATA
54552 **         PTF_ZERODATA | PTF_LEAF
54553 **         PTF_LEAFDATA | PTF_INTKEY
54554 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
54555 */
54556 static int decodeFlags(MemPage *pPage, int flagByte){
54557   BtShared *pBt;     /* A copy of pPage->pBt */
54558 
54559   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
54560   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54561   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
54562   flagByte &= ~PTF_LEAF;
54563   pPage->childPtrSize = 4-4*pPage->leaf;
54564   pBt = pPage->pBt;
54565   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
54566     /* EVIDENCE-OF: R-03640-13415 A value of 5 means the page is an interior
54567     ** table b-tree page. */
54568     assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
54569     /* EVIDENCE-OF: R-20501-61796 A value of 13 means the page is a leaf
54570     ** table b-tree page. */
54571     assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
54572     pPage->intKey = 1;
54573     pPage->intKeyLeaf = pPage->leaf;
54574     pPage->noPayload = !pPage->leaf;
54575     pPage->maxLocal = pBt->maxLeaf;
54576     pPage->minLocal = pBt->minLeaf;
54577   }else if( flagByte==PTF_ZERODATA ){
54578     /* EVIDENCE-OF: R-27225-53936 A value of 2 means the page is an interior
54579     ** index b-tree page. */
54580     assert( (PTF_ZERODATA)==2 );
54581     /* EVIDENCE-OF: R-16571-11615 A value of 10 means the page is a leaf
54582     ** index b-tree page. */
54583     assert( (PTF_ZERODATA|PTF_LEAF)==10 );
54584     pPage->intKey = 0;
54585     pPage->intKeyLeaf = 0;
54586     pPage->noPayload = 0;
54587     pPage->maxLocal = pBt->maxLocal;
54588     pPage->minLocal = pBt->minLocal;
54589   }else{
54590     /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
54591     ** an error. */
54592     return SQLITE_CORRUPT_BKPT;
54593   }
54594   pPage->max1bytePayload = pBt->max1bytePayload;
54595   return SQLITE_OK;
54596 }
54597 
54598 /*
54599 ** Initialize the auxiliary information for a disk block.
54600 **
54601 ** Return SQLITE_OK on success.  If we see that the page does
54602 ** not contain a well-formed database page, then return
54603 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
54604 ** guarantee that the page is well-formed.  It only shows that
54605 ** we failed to detect any corruption.
54606 */
54607 static int btreeInitPage(MemPage *pPage){
54608 
54609   assert( pPage->pBt!=0 );
54610   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54611   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
54612   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
54613   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
54614 
54615   if( !pPage->isInit ){
54616     u16 pc;            /* Address of a freeblock within pPage->aData[] */
54617     u8 hdr;            /* Offset to beginning of page header */
54618     u8 *data;          /* Equal to pPage->aData */
54619     BtShared *pBt;        /* The main btree structure */
54620     int usableSize;    /* Amount of usable space on each page */
54621     u16 cellOffset;    /* Offset from start of page to first cell pointer */
54622     int nFree;         /* Number of unused bytes on the page */
54623     int top;           /* First byte of the cell content area */
54624     int iCellFirst;    /* First allowable cell or freeblock offset */
54625     int iCellLast;     /* Last possible cell or freeblock offset */
54626 
54627     pBt = pPage->pBt;
54628 
54629     hdr = pPage->hdrOffset;
54630     data = pPage->aData;
54631     /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
54632     ** the b-tree page type. */
54633     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
54634     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
54635     pPage->maskPage = (u16)(pBt->pageSize - 1);
54636     pPage->nOverflow = 0;
54637     usableSize = pBt->usableSize;
54638     pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
54639     pPage->aDataEnd = &data[usableSize];
54640     pPage->aCellIdx = &data[cellOffset];
54641     /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
54642     ** the start of the cell content area. A zero value for this integer is
54643     ** interpreted as 65536. */
54644     top = get2byteNotZero(&data[hdr+5]);
54645     /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
54646     ** number of cells on the page. */
54647     pPage->nCell = get2byte(&data[hdr+3]);
54648     if( pPage->nCell>MX_CELL(pBt) ){
54649       /* To many cells for a single page.  The page must be corrupt */
54650       return SQLITE_CORRUPT_BKPT;
54651     }
54652     testcase( pPage->nCell==MX_CELL(pBt) );
54653     /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
54654     ** possible for a root page of a table that contains no rows) then the
54655     ** offset to the cell content area will equal the page size minus the
54656     ** bytes of reserved space. */
54657     assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
54658 
54659     /* A malformed database page might cause us to read past the end
54660     ** of page when parsing a cell.
54661     **
54662     ** The following block of code checks early to see if a cell extends
54663     ** past the end of a page boundary and causes SQLITE_CORRUPT to be
54664     ** returned if it does.
54665     */
54666     iCellFirst = cellOffset + 2*pPage->nCell;
54667     iCellLast = usableSize - 4;
54668 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
54669     {
54670       int i;            /* Index into the cell pointer array */
54671       int sz;           /* Size of a cell */
54672 
54673       if( !pPage->leaf ) iCellLast--;
54674       for(i=0; i<pPage->nCell; i++){
54675         pc = get2byte(&data[cellOffset+i*2]);
54676         testcase( pc==iCellFirst );
54677         testcase( pc==iCellLast );
54678         if( pc<iCellFirst || pc>iCellLast ){
54679           return SQLITE_CORRUPT_BKPT;
54680         }
54681         sz = cellSizePtr(pPage, &data[pc]);
54682         testcase( pc+sz==usableSize );
54683         if( pc+sz>usableSize ){
54684           return SQLITE_CORRUPT_BKPT;
54685         }
54686       }
54687       if( !pPage->leaf ) iCellLast++;
54688     }
54689 #endif
54690 
54691     /* Compute the total free space on the page
54692     ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
54693     ** start of the first freeblock on the page, or is zero if there are no
54694     ** freeblocks. */
54695     pc = get2byte(&data[hdr+1]);
54696     nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
54697     while( pc>0 ){
54698       u16 next, size;
54699       if( pc<iCellFirst || pc>iCellLast ){
54700         /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
54701         ** always be at least one cell before the first freeblock.
54702         **
54703         ** Or, the freeblock is off the end of the page
54704         */
54705         return SQLITE_CORRUPT_BKPT;
54706       }
54707       next = get2byte(&data[pc]);
54708       size = get2byte(&data[pc+2]);
54709       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
54710         /* Free blocks must be in ascending order. And the last byte of
54711         ** the free-block must lie on the database page.  */
54712         return SQLITE_CORRUPT_BKPT;
54713       }
54714       nFree = nFree + size;
54715       pc = next;
54716     }
54717 
54718     /* At this point, nFree contains the sum of the offset to the start
54719     ** of the cell-content area plus the number of free bytes within
54720     ** the cell-content area. If this is greater than the usable-size
54721     ** of the page, then the page must be corrupted. This check also
54722     ** serves to verify that the offset to the start of the cell-content
54723     ** area, according to the page header, lies within the page.
54724     */
54725     if( nFree>usableSize ){
54726       return SQLITE_CORRUPT_BKPT;
54727     }
54728     pPage->nFree = (u16)(nFree - iCellFirst);
54729     pPage->isInit = 1;
54730   }
54731   return SQLITE_OK;
54732 }
54733 
54734 /*
54735 ** Set up a raw page so that it looks like a database page holding
54736 ** no entries.
54737 */
54738 static void zeroPage(MemPage *pPage, int flags){
54739   unsigned char *data = pPage->aData;
54740   BtShared *pBt = pPage->pBt;
54741   u8 hdr = pPage->hdrOffset;
54742   u16 first;
54743 
54744   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
54745   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
54746   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
54747   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54748   assert( sqlite3_mutex_held(pBt->mutex) );
54749   if( pBt->btsFlags & BTS_SECURE_DELETE ){
54750     memset(&data[hdr], 0, pBt->usableSize - hdr);
54751   }
54752   data[hdr] = (char)flags;
54753   first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
54754   memset(&data[hdr+1], 0, 4);
54755   data[hdr+7] = 0;
54756   put2byte(&data[hdr+5], pBt->usableSize);
54757   pPage->nFree = (u16)(pBt->usableSize - first);
54758   decodeFlags(pPage, flags);
54759   pPage->cellOffset = first;
54760   pPage->aDataEnd = &data[pBt->usableSize];
54761   pPage->aCellIdx = &data[first];
54762   pPage->nOverflow = 0;
54763   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
54764   pPage->maskPage = (u16)(pBt->pageSize - 1);
54765   pPage->nCell = 0;
54766   pPage->isInit = 1;
54767 }
54768 
54769 
54770 /*
54771 ** Convert a DbPage obtained from the pager into a MemPage used by
54772 ** the btree layer.
54773 */
54774 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
54775   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
54776   pPage->aData = sqlite3PagerGetData(pDbPage);
54777   pPage->pDbPage = pDbPage;
54778   pPage->pBt = pBt;
54779   pPage->pgno = pgno;
54780   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
54781   return pPage;
54782 }
54783 
54784 /*
54785 ** Get a page from the pager.  Initialize the MemPage.pBt and
54786 ** MemPage.aData elements if needed.
54787 **
54788 ** If the noContent flag is set, it means that we do not care about
54789 ** the content of the page at this time.  So do not go to the disk
54790 ** to fetch the content.  Just fill in the content with zeros for now.
54791 ** If in the future we call sqlite3PagerWrite() on this page, that
54792 ** means we have started to be concerned about content and the disk
54793 ** read should occur at that point.
54794 */
54795 static int btreeGetPage(
54796   BtShared *pBt,       /* The btree */
54797   Pgno pgno,           /* Number of the page to fetch */
54798   MemPage **ppPage,    /* Return the page in this parameter */
54799   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
54800 ){
54801   int rc;
54802   DbPage *pDbPage;
54803 
54804   assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
54805   assert( sqlite3_mutex_held(pBt->mutex) );
54806   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
54807   if( rc ) return rc;
54808   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
54809   return SQLITE_OK;
54810 }
54811 
54812 /*
54813 ** Retrieve a page from the pager cache. If the requested page is not
54814 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
54815 ** MemPage.aData elements if needed.
54816 */
54817 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
54818   DbPage *pDbPage;
54819   assert( sqlite3_mutex_held(pBt->mutex) );
54820   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
54821   if( pDbPage ){
54822     return btreePageFromDbPage(pDbPage, pgno, pBt);
54823   }
54824   return 0;
54825 }
54826 
54827 /*
54828 ** Return the size of the database file in pages. If there is any kind of
54829 ** error, return ((unsigned int)-1).
54830 */
54831 static Pgno btreePagecount(BtShared *pBt){
54832   return pBt->nPage;
54833 }
54834 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
54835   assert( sqlite3BtreeHoldsMutex(p) );
54836   assert( ((p->pBt->nPage)&0x8000000)==0 );
54837   return btreePagecount(p->pBt);
54838 }
54839 
54840 /*
54841 ** Get a page from the pager and initialize it.  This routine is just a
54842 ** convenience wrapper around separate calls to btreeGetPage() and
54843 ** btreeInitPage().
54844 **
54845 ** If an error occurs, then the value *ppPage is set to is undefined. It
54846 ** may remain unchanged, or it may be set to an invalid value.
54847 */
54848 static int getAndInitPage(
54849   BtShared *pBt,                  /* The database file */
54850   Pgno pgno,                      /* Number of the page to get */
54851   MemPage **ppPage,               /* Write the page pointer here */
54852   int bReadonly                   /* PAGER_GET_READONLY or 0 */
54853 ){
54854   int rc;
54855   assert( sqlite3_mutex_held(pBt->mutex) );
54856   assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
54857 
54858   if( pgno>btreePagecount(pBt) ){
54859     rc = SQLITE_CORRUPT_BKPT;
54860   }else{
54861     rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
54862     if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
54863       rc = btreeInitPage(*ppPage);
54864       if( rc!=SQLITE_OK ){
54865         releasePage(*ppPage);
54866       }
54867     }
54868   }
54869 
54870   testcase( pgno==0 );
54871   assert( pgno!=0 || rc==SQLITE_CORRUPT );
54872   return rc;
54873 }
54874 
54875 /*
54876 ** Release a MemPage.  This should be called once for each prior
54877 ** call to btreeGetPage.
54878 */
54879 static void releasePage(MemPage *pPage){
54880   if( pPage ){
54881     assert( pPage->aData );
54882     assert( pPage->pBt );
54883     assert( pPage->pDbPage!=0 );
54884     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
54885     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
54886     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54887     sqlite3PagerUnrefNotNull(pPage->pDbPage);
54888   }
54889 }
54890 
54891 /*
54892 ** During a rollback, when the pager reloads information into the cache
54893 ** so that the cache is restored to its original state at the start of
54894 ** the transaction, for each page restored this routine is called.
54895 **
54896 ** This routine needs to reset the extra data section at the end of the
54897 ** page to agree with the restored data.
54898 */
54899 static void pageReinit(DbPage *pData){
54900   MemPage *pPage;
54901   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
54902   assert( sqlite3PagerPageRefcount(pData)>0 );
54903   if( pPage->isInit ){
54904     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54905     pPage->isInit = 0;
54906     if( sqlite3PagerPageRefcount(pData)>1 ){
54907       /* pPage might not be a btree page;  it might be an overflow page
54908       ** or ptrmap page or a free page.  In those cases, the following
54909       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
54910       ** But no harm is done by this.  And it is very important that
54911       ** btreeInitPage() be called on every btree page so we make
54912       ** the call for every page that comes in for re-initing. */
54913       btreeInitPage(pPage);
54914     }
54915   }
54916 }
54917 
54918 /*
54919 ** Invoke the busy handler for a btree.
54920 */
54921 static int btreeInvokeBusyHandler(void *pArg){
54922   BtShared *pBt = (BtShared*)pArg;
54923   assert( pBt->db );
54924   assert( sqlite3_mutex_held(pBt->db->mutex) );
54925   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
54926 }
54927 
54928 /*
54929 ** Open a database file.
54930 **
54931 ** zFilename is the name of the database file.  If zFilename is NULL
54932 ** then an ephemeral database is created.  The ephemeral database might
54933 ** be exclusively in memory, or it might use a disk-based memory cache.
54934 ** Either way, the ephemeral database will be automatically deleted
54935 ** when sqlite3BtreeClose() is called.
54936 **
54937 ** If zFilename is ":memory:" then an in-memory database is created
54938 ** that is automatically destroyed when it is closed.
54939 **
54940 ** The "flags" parameter is a bitmask that might contain bits like
54941 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
54942 **
54943 ** If the database is already opened in the same database connection
54944 ** and we are in shared cache mode, then the open will fail with an
54945 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
54946 ** objects in the same database connection since doing so will lead
54947 ** to problems with locking.
54948 */
54949 SQLITE_PRIVATE int sqlite3BtreeOpen(
54950   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
54951   const char *zFilename,  /* Name of the file containing the BTree database */
54952   sqlite3 *db,            /* Associated database handle */
54953   Btree **ppBtree,        /* Pointer to new Btree object written here */
54954   int flags,              /* Options */
54955   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
54956 ){
54957   BtShared *pBt = 0;             /* Shared part of btree structure */
54958   Btree *p;                      /* Handle to return */
54959   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
54960   int rc = SQLITE_OK;            /* Result code from this function */
54961   u8 nReserve;                   /* Byte of unused space on each page */
54962   unsigned char zDbHeader[100];  /* Database header content */
54963 
54964   /* True if opening an ephemeral, temporary database */
54965   const int isTempDb = zFilename==0 || zFilename[0]==0;
54966 
54967   /* Set the variable isMemdb to true for an in-memory database, or
54968   ** false for a file-based database.
54969   */
54970 #ifdef SQLITE_OMIT_MEMORYDB
54971   const int isMemdb = 0;
54972 #else
54973   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
54974                        || (isTempDb && sqlite3TempInMemory(db))
54975                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
54976 #endif
54977 
54978   assert( db!=0 );
54979   assert( pVfs!=0 );
54980   assert( sqlite3_mutex_held(db->mutex) );
54981   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
54982 
54983   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
54984   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
54985 
54986   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
54987   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
54988 
54989   if( isMemdb ){
54990     flags |= BTREE_MEMORY;
54991   }
54992   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
54993     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
54994   }
54995   p = sqlite3MallocZero(sizeof(Btree));
54996   if( !p ){
54997     return SQLITE_NOMEM;
54998   }
54999   p->inTrans = TRANS_NONE;
55000   p->db = db;
55001 #ifndef SQLITE_OMIT_SHARED_CACHE
55002   p->lock.pBtree = p;
55003   p->lock.iTable = 1;
55004 #endif
55005 
55006 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
55007   /*
55008   ** If this Btree is a candidate for shared cache, try to find an
55009   ** existing BtShared object that we can share with
55010   */
55011   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
55012     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
55013       int nFilename = sqlite3Strlen30(zFilename)+1;
55014       int nFullPathname = pVfs->mxPathname+1;
55015       char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
55016       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
55017 
55018       p->sharable = 1;
55019       if( !zFullPathname ){
55020         sqlite3_free(p);
55021         return SQLITE_NOMEM;
55022       }
55023       if( isMemdb ){
55024         memcpy(zFullPathname, zFilename, nFilename);
55025       }else{
55026         rc = sqlite3OsFullPathname(pVfs, zFilename,
55027                                    nFullPathname, zFullPathname);
55028         if( rc ){
55029           sqlite3_free(zFullPathname);
55030           sqlite3_free(p);
55031           return rc;
55032         }
55033       }
55034 #if SQLITE_THREADSAFE
55035       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
55036       sqlite3_mutex_enter(mutexOpen);
55037       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
55038       sqlite3_mutex_enter(mutexShared);
55039 #endif
55040       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
55041         assert( pBt->nRef>0 );
55042         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
55043                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
55044           int iDb;
55045           for(iDb=db->nDb-1; iDb>=0; iDb--){
55046             Btree *pExisting = db->aDb[iDb].pBt;
55047             if( pExisting && pExisting->pBt==pBt ){
55048               sqlite3_mutex_leave(mutexShared);
55049               sqlite3_mutex_leave(mutexOpen);
55050               sqlite3_free(zFullPathname);
55051               sqlite3_free(p);
55052               return SQLITE_CONSTRAINT;
55053             }
55054           }
55055           p->pBt = pBt;
55056           pBt->nRef++;
55057           break;
55058         }
55059       }
55060       sqlite3_mutex_leave(mutexShared);
55061       sqlite3_free(zFullPathname);
55062     }
55063 #ifdef SQLITE_DEBUG
55064     else{
55065       /* In debug mode, we mark all persistent databases as sharable
55066       ** even when they are not.  This exercises the locking code and
55067       ** gives more opportunity for asserts(sqlite3_mutex_held())
55068       ** statements to find locking problems.
55069       */
55070       p->sharable = 1;
55071     }
55072 #endif
55073   }
55074 #endif
55075   if( pBt==0 ){
55076     /*
55077     ** The following asserts make sure that structures used by the btree are
55078     ** the right size.  This is to guard against size changes that result
55079     ** when compiling on a different architecture.
55080     */
55081     assert( sizeof(i64)==8 );
55082     assert( sizeof(u64)==8 );
55083     assert( sizeof(u32)==4 );
55084     assert( sizeof(u16)==2 );
55085     assert( sizeof(Pgno)==4 );
55086 
55087     pBt = sqlite3MallocZero( sizeof(*pBt) );
55088     if( pBt==0 ){
55089       rc = SQLITE_NOMEM;
55090       goto btree_open_out;
55091     }
55092     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
55093                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
55094     if( rc==SQLITE_OK ){
55095       sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
55096       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
55097     }
55098     if( rc!=SQLITE_OK ){
55099       goto btree_open_out;
55100     }
55101     pBt->openFlags = (u8)flags;
55102     pBt->db = db;
55103     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
55104     p->pBt = pBt;
55105 
55106     pBt->pCursor = 0;
55107     pBt->pPage1 = 0;
55108     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
55109 #ifdef SQLITE_SECURE_DELETE
55110     pBt->btsFlags |= BTS_SECURE_DELETE;
55111 #endif
55112     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
55113     ** determined by the 2-byte integer located at an offset of 16 bytes from
55114     ** the beginning of the database file. */
55115     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
55116     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
55117          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
55118       pBt->pageSize = 0;
55119 #ifndef SQLITE_OMIT_AUTOVACUUM
55120       /* If the magic name ":memory:" will create an in-memory database, then
55121       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
55122       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
55123       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
55124       ** regular file-name. In this case the auto-vacuum applies as per normal.
55125       */
55126       if( zFilename && !isMemdb ){
55127         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
55128         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
55129       }
55130 #endif
55131       nReserve = 0;
55132     }else{
55133       /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
55134       ** determined by the one-byte unsigned integer found at an offset of 20
55135       ** into the database file header. */
55136       nReserve = zDbHeader[20];
55137       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
55138 #ifndef SQLITE_OMIT_AUTOVACUUM
55139       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
55140       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
55141 #endif
55142     }
55143     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
55144     if( rc ) goto btree_open_out;
55145     pBt->usableSize = pBt->pageSize - nReserve;
55146     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
55147 
55148 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
55149     /* Add the new BtShared object to the linked list sharable BtShareds.
55150     */
55151     if( p->sharable ){
55152       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
55153       pBt->nRef = 1;
55154       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
55155       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
55156         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
55157         if( pBt->mutex==0 ){
55158           rc = SQLITE_NOMEM;
55159           db->mallocFailed = 0;
55160           goto btree_open_out;
55161         }
55162       }
55163       sqlite3_mutex_enter(mutexShared);
55164       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
55165       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
55166       sqlite3_mutex_leave(mutexShared);
55167     }
55168 #endif
55169   }
55170 
55171 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
55172   /* If the new Btree uses a sharable pBtShared, then link the new
55173   ** Btree into the list of all sharable Btrees for the same connection.
55174   ** The list is kept in ascending order by pBt address.
55175   */
55176   if( p->sharable ){
55177     int i;
55178     Btree *pSib;
55179     for(i=0; i<db->nDb; i++){
55180       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
55181         while( pSib->pPrev ){ pSib = pSib->pPrev; }
55182         if( p->pBt<pSib->pBt ){
55183           p->pNext = pSib;
55184           p->pPrev = 0;
55185           pSib->pPrev = p;
55186         }else{
55187           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
55188             pSib = pSib->pNext;
55189           }
55190           p->pNext = pSib->pNext;
55191           p->pPrev = pSib;
55192           if( p->pNext ){
55193             p->pNext->pPrev = p;
55194           }
55195           pSib->pNext = p;
55196         }
55197         break;
55198       }
55199     }
55200   }
55201 #endif
55202   *ppBtree = p;
55203 
55204 btree_open_out:
55205   if( rc!=SQLITE_OK ){
55206     if( pBt && pBt->pPager ){
55207       sqlite3PagerClose(pBt->pPager);
55208     }
55209     sqlite3_free(pBt);
55210     sqlite3_free(p);
55211     *ppBtree = 0;
55212   }else{
55213     /* If the B-Tree was successfully opened, set the pager-cache size to the
55214     ** default value. Except, when opening on an existing shared pager-cache,
55215     ** do not change the pager-cache size.
55216     */
55217     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
55218       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
55219     }
55220   }
55221   if( mutexOpen ){
55222     assert( sqlite3_mutex_held(mutexOpen) );
55223     sqlite3_mutex_leave(mutexOpen);
55224   }
55225   return rc;
55226 }
55227 
55228 /*
55229 ** Decrement the BtShared.nRef counter.  When it reaches zero,
55230 ** remove the BtShared structure from the sharing list.  Return
55231 ** true if the BtShared.nRef counter reaches zero and return
55232 ** false if it is still positive.
55233 */
55234 static int removeFromSharingList(BtShared *pBt){
55235 #ifndef SQLITE_OMIT_SHARED_CACHE
55236   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
55237   BtShared *pList;
55238   int removed = 0;
55239 
55240   assert( sqlite3_mutex_notheld(pBt->mutex) );
55241   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
55242   sqlite3_mutex_enter(pMaster);
55243   pBt->nRef--;
55244   if( pBt->nRef<=0 ){
55245     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
55246       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
55247     }else{
55248       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
55249       while( ALWAYS(pList) && pList->pNext!=pBt ){
55250         pList=pList->pNext;
55251       }
55252       if( ALWAYS(pList) ){
55253         pList->pNext = pBt->pNext;
55254       }
55255     }
55256     if( SQLITE_THREADSAFE ){
55257       sqlite3_mutex_free(pBt->mutex);
55258     }
55259     removed = 1;
55260   }
55261   sqlite3_mutex_leave(pMaster);
55262   return removed;
55263 #else
55264   return 1;
55265 #endif
55266 }
55267 
55268 /*
55269 ** Make sure pBt->pTmpSpace points to an allocation of
55270 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
55271 ** pointer.
55272 */
55273 static void allocateTempSpace(BtShared *pBt){
55274   if( !pBt->pTmpSpace ){
55275     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
55276 
55277     /* One of the uses of pBt->pTmpSpace is to format cells before
55278     ** inserting them into a leaf page (function fillInCell()). If
55279     ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
55280     ** by the various routines that manipulate binary cells. Which
55281     ** can mean that fillInCell() only initializes the first 2 or 3
55282     ** bytes of pTmpSpace, but that the first 4 bytes are copied from
55283     ** it into a database page. This is not actually a problem, but it
55284     ** does cause a valgrind error when the 1 or 2 bytes of unitialized
55285     ** data is passed to system call write(). So to avoid this error,
55286     ** zero the first 4 bytes of temp space here.
55287     **
55288     ** Also:  Provide four bytes of initialized space before the
55289     ** beginning of pTmpSpace as an area available to prepend the
55290     ** left-child pointer to the beginning of a cell.
55291     */
55292     if( pBt->pTmpSpace ){
55293       memset(pBt->pTmpSpace, 0, 8);
55294       pBt->pTmpSpace += 4;
55295     }
55296   }
55297 }
55298 
55299 /*
55300 ** Free the pBt->pTmpSpace allocation
55301 */
55302 static void freeTempSpace(BtShared *pBt){
55303   if( pBt->pTmpSpace ){
55304     pBt->pTmpSpace -= 4;
55305     sqlite3PageFree(pBt->pTmpSpace);
55306     pBt->pTmpSpace = 0;
55307   }
55308 }
55309 
55310 /*
55311 ** Close an open database and invalidate all cursors.
55312 */
55313 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
55314   BtShared *pBt = p->pBt;
55315   BtCursor *pCur;
55316 
55317   /* Close all cursors opened via this handle.  */
55318   assert( sqlite3_mutex_held(p->db->mutex) );
55319   sqlite3BtreeEnter(p);
55320   pCur = pBt->pCursor;
55321   while( pCur ){
55322     BtCursor *pTmp = pCur;
55323     pCur = pCur->pNext;
55324     if( pTmp->pBtree==p ){
55325       sqlite3BtreeCloseCursor(pTmp);
55326     }
55327   }
55328 
55329   /* Rollback any active transaction and free the handle structure.
55330   ** The call to sqlite3BtreeRollback() drops any table-locks held by
55331   ** this handle.
55332   */
55333   sqlite3BtreeRollback(p, SQLITE_OK, 0);
55334   sqlite3BtreeLeave(p);
55335 
55336   /* If there are still other outstanding references to the shared-btree
55337   ** structure, return now. The remainder of this procedure cleans
55338   ** up the shared-btree.
55339   */
55340   assert( p->wantToLock==0 && p->locked==0 );
55341   if( !p->sharable || removeFromSharingList(pBt) ){
55342     /* The pBt is no longer on the sharing list, so we can access
55343     ** it without having to hold the mutex.
55344     **
55345     ** Clean out and delete the BtShared object.
55346     */
55347     assert( !pBt->pCursor );
55348     sqlite3PagerClose(pBt->pPager);
55349     if( pBt->xFreeSchema && pBt->pSchema ){
55350       pBt->xFreeSchema(pBt->pSchema);
55351     }
55352     sqlite3DbFree(0, pBt->pSchema);
55353     freeTempSpace(pBt);
55354     sqlite3_free(pBt);
55355   }
55356 
55357 #ifndef SQLITE_OMIT_SHARED_CACHE
55358   assert( p->wantToLock==0 );
55359   assert( p->locked==0 );
55360   if( p->pPrev ) p->pPrev->pNext = p->pNext;
55361   if( p->pNext ) p->pNext->pPrev = p->pPrev;
55362 #endif
55363 
55364   sqlite3_free(p);
55365   return SQLITE_OK;
55366 }
55367 
55368 /*
55369 ** Change the limit on the number of pages allowed in the cache.
55370 **
55371 ** The maximum number of cache pages is set to the absolute
55372 ** value of mxPage.  If mxPage is negative, the pager will
55373 ** operate asynchronously - it will not stop to do fsync()s
55374 ** to insure data is written to the disk surface before
55375 ** continuing.  Transactions still work if synchronous is off,
55376 ** and the database cannot be corrupted if this program
55377 ** crashes.  But if the operating system crashes or there is
55378 ** an abrupt power failure when synchronous is off, the database
55379 ** could be left in an inconsistent and unrecoverable state.
55380 ** Synchronous is on by default so database corruption is not
55381 ** normally a worry.
55382 */
55383 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
55384   BtShared *pBt = p->pBt;
55385   assert( sqlite3_mutex_held(p->db->mutex) );
55386   sqlite3BtreeEnter(p);
55387   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
55388   sqlite3BtreeLeave(p);
55389   return SQLITE_OK;
55390 }
55391 
55392 #if SQLITE_MAX_MMAP_SIZE>0
55393 /*
55394 ** Change the limit on the amount of the database file that may be
55395 ** memory mapped.
55396 */
55397 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
55398   BtShared *pBt = p->pBt;
55399   assert( sqlite3_mutex_held(p->db->mutex) );
55400   sqlite3BtreeEnter(p);
55401   sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
55402   sqlite3BtreeLeave(p);
55403   return SQLITE_OK;
55404 }
55405 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
55406 
55407 /*
55408 ** Change the way data is synced to disk in order to increase or decrease
55409 ** how well the database resists damage due to OS crashes and power
55410 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
55411 ** there is a high probability of damage)  Level 2 is the default.  There
55412 ** is a very low but non-zero probability of damage.  Level 3 reduces the
55413 ** probability of damage to near zero but with a write performance reduction.
55414 */
55415 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
55416 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
55417   Btree *p,              /* The btree to set the safety level on */
55418   unsigned pgFlags       /* Various PAGER_* flags */
55419 ){
55420   BtShared *pBt = p->pBt;
55421   assert( sqlite3_mutex_held(p->db->mutex) );
55422   sqlite3BtreeEnter(p);
55423   sqlite3PagerSetFlags(pBt->pPager, pgFlags);
55424   sqlite3BtreeLeave(p);
55425   return SQLITE_OK;
55426 }
55427 #endif
55428 
55429 /*
55430 ** Return TRUE if the given btree is set to safety level 1.  In other
55431 ** words, return TRUE if no sync() occurs on the disk files.
55432 */
55433 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
55434   BtShared *pBt = p->pBt;
55435   int rc;
55436   assert( sqlite3_mutex_held(p->db->mutex) );
55437   sqlite3BtreeEnter(p);
55438   assert( pBt && pBt->pPager );
55439   rc = sqlite3PagerNosync(pBt->pPager);
55440   sqlite3BtreeLeave(p);
55441   return rc;
55442 }
55443 
55444 /*
55445 ** Change the default pages size and the number of reserved bytes per page.
55446 ** Or, if the page size has already been fixed, return SQLITE_READONLY
55447 ** without changing anything.
55448 **
55449 ** The page size must be a power of 2 between 512 and 65536.  If the page
55450 ** size supplied does not meet this constraint then the page size is not
55451 ** changed.
55452 **
55453 ** Page sizes are constrained to be a power of two so that the region
55454 ** of the database file used for locking (beginning at PENDING_BYTE,
55455 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
55456 ** at the beginning of a page.
55457 **
55458 ** If parameter nReserve is less than zero, then the number of reserved
55459 ** bytes per page is left unchanged.
55460 **
55461 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
55462 ** and autovacuum mode can no longer be changed.
55463 */
55464 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
55465   int rc = SQLITE_OK;
55466   BtShared *pBt = p->pBt;
55467   assert( nReserve>=-1 && nReserve<=255 );
55468   sqlite3BtreeEnter(p);
55469 #if SQLITE_HAS_CODEC
55470   if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
55471 #endif
55472   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
55473     sqlite3BtreeLeave(p);
55474     return SQLITE_READONLY;
55475   }
55476   if( nReserve<0 ){
55477     nReserve = pBt->pageSize - pBt->usableSize;
55478   }
55479   assert( nReserve>=0 && nReserve<=255 );
55480   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
55481         ((pageSize-1)&pageSize)==0 ){
55482     assert( (pageSize & 7)==0 );
55483     assert( !pBt->pCursor );
55484     pBt->pageSize = (u32)pageSize;
55485     freeTempSpace(pBt);
55486   }
55487   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
55488   pBt->usableSize = pBt->pageSize - (u16)nReserve;
55489   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
55490   sqlite3BtreeLeave(p);
55491   return rc;
55492 }
55493 
55494 /*
55495 ** Return the currently defined page size
55496 */
55497 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
55498   return p->pBt->pageSize;
55499 }
55500 
55501 /*
55502 ** This function is similar to sqlite3BtreeGetReserve(), except that it
55503 ** may only be called if it is guaranteed that the b-tree mutex is already
55504 ** held.
55505 **
55506 ** This is useful in one special case in the backup API code where it is
55507 ** known that the shared b-tree mutex is held, but the mutex on the
55508 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
55509 ** were to be called, it might collide with some other operation on the
55510 ** database handle that owns *p, causing undefined behavior.
55511 */
55512 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
55513   int n;
55514   assert( sqlite3_mutex_held(p->pBt->mutex) );
55515   n = p->pBt->pageSize - p->pBt->usableSize;
55516   return n;
55517 }
55518 
55519 /*
55520 ** Return the number of bytes of space at the end of every page that
55521 ** are intentually left unused.  This is the "reserved" space that is
55522 ** sometimes used by extensions.
55523 **
55524 ** If SQLITE_HAS_MUTEX is defined then the number returned is the
55525 ** greater of the current reserved space and the maximum requested
55526 ** reserve space.
55527 */
55528 SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
55529   int n;
55530   sqlite3BtreeEnter(p);
55531   n = sqlite3BtreeGetReserveNoMutex(p);
55532 #ifdef SQLITE_HAS_CODEC
55533   if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
55534 #endif
55535   sqlite3BtreeLeave(p);
55536   return n;
55537 }
55538 
55539 
55540 /*
55541 ** Set the maximum page count for a database if mxPage is positive.
55542 ** No changes are made if mxPage is 0 or negative.
55543 ** Regardless of the value of mxPage, return the maximum page count.
55544 */
55545 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
55546   int n;
55547   sqlite3BtreeEnter(p);
55548   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
55549   sqlite3BtreeLeave(p);
55550   return n;
55551 }
55552 
55553 /*
55554 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
55555 ** then make no changes.  Always return the value of the BTS_SECURE_DELETE
55556 ** setting after the change.
55557 */
55558 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
55559   int b;
55560   if( p==0 ) return 0;
55561   sqlite3BtreeEnter(p);
55562   if( newFlag>=0 ){
55563     p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
55564     if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
55565   }
55566   b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
55567   sqlite3BtreeLeave(p);
55568   return b;
55569 }
55570 
55571 /*
55572 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
55573 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
55574 ** is disabled. The default value for the auto-vacuum property is
55575 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
55576 */
55577 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
55578 #ifdef SQLITE_OMIT_AUTOVACUUM
55579   return SQLITE_READONLY;
55580 #else
55581   BtShared *pBt = p->pBt;
55582   int rc = SQLITE_OK;
55583   u8 av = (u8)autoVacuum;
55584 
55585   sqlite3BtreeEnter(p);
55586   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
55587     rc = SQLITE_READONLY;
55588   }else{
55589     pBt->autoVacuum = av ?1:0;
55590     pBt->incrVacuum = av==2 ?1:0;
55591   }
55592   sqlite3BtreeLeave(p);
55593   return rc;
55594 #endif
55595 }
55596 
55597 /*
55598 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
55599 ** enabled 1 is returned. Otherwise 0.
55600 */
55601 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
55602 #ifdef SQLITE_OMIT_AUTOVACUUM
55603   return BTREE_AUTOVACUUM_NONE;
55604 #else
55605   int rc;
55606   sqlite3BtreeEnter(p);
55607   rc = (
55608     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
55609     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
55610     BTREE_AUTOVACUUM_INCR
55611   );
55612   sqlite3BtreeLeave(p);
55613   return rc;
55614 #endif
55615 }
55616 
55617 
55618 /*
55619 ** Get a reference to pPage1 of the database file.  This will
55620 ** also acquire a readlock on that file.
55621 **
55622 ** SQLITE_OK is returned on success.  If the file is not a
55623 ** well-formed database file, then SQLITE_CORRUPT is returned.
55624 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
55625 ** is returned if we run out of memory.
55626 */
55627 static int lockBtree(BtShared *pBt){
55628   int rc;              /* Result code from subfunctions */
55629   MemPage *pPage1;     /* Page 1 of the database file */
55630   int nPage;           /* Number of pages in the database */
55631   int nPageFile = 0;   /* Number of pages in the database file */
55632   int nPageHeader;     /* Number of pages in the database according to hdr */
55633 
55634   assert( sqlite3_mutex_held(pBt->mutex) );
55635   assert( pBt->pPage1==0 );
55636   rc = sqlite3PagerSharedLock(pBt->pPager);
55637   if( rc!=SQLITE_OK ) return rc;
55638   rc = btreeGetPage(pBt, 1, &pPage1, 0);
55639   if( rc!=SQLITE_OK ) return rc;
55640 
55641   /* Do some checking to help insure the file we opened really is
55642   ** a valid database file.
55643   */
55644   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
55645   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
55646   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
55647     nPage = nPageFile;
55648   }
55649   if( nPage>0 ){
55650     u32 pageSize;
55651     u32 usableSize;
55652     u8 *page1 = pPage1->aData;
55653     rc = SQLITE_NOTADB;
55654     /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
55655     ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
55656     ** 61 74 20 33 00. */
55657     if( memcmp(page1, zMagicHeader, 16)!=0 ){
55658       goto page1_init_failed;
55659     }
55660 
55661 #ifdef SQLITE_OMIT_WAL
55662     if( page1[18]>1 ){
55663       pBt->btsFlags |= BTS_READ_ONLY;
55664     }
55665     if( page1[19]>1 ){
55666       goto page1_init_failed;
55667     }
55668 #else
55669     if( page1[18]>2 ){
55670       pBt->btsFlags |= BTS_READ_ONLY;
55671     }
55672     if( page1[19]>2 ){
55673       goto page1_init_failed;
55674     }
55675 
55676     /* If the write version is set to 2, this database should be accessed
55677     ** in WAL mode. If the log is not already open, open it now. Then
55678     ** return SQLITE_OK and return without populating BtShared.pPage1.
55679     ** The caller detects this and calls this function again. This is
55680     ** required as the version of page 1 currently in the page1 buffer
55681     ** may not be the latest version - there may be a newer one in the log
55682     ** file.
55683     */
55684     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
55685       int isOpen = 0;
55686       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
55687       if( rc!=SQLITE_OK ){
55688         goto page1_init_failed;
55689       }else if( isOpen==0 ){
55690         releasePage(pPage1);
55691         return SQLITE_OK;
55692       }
55693       rc = SQLITE_NOTADB;
55694     }
55695 #endif
55696 
55697     /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
55698     ** fractions and the leaf payload fraction values must be 64, 32, and 32.
55699     **
55700     ** The original design allowed these amounts to vary, but as of
55701     ** version 3.6.0, we require them to be fixed.
55702     */
55703     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
55704       goto page1_init_failed;
55705     }
55706     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
55707     ** determined by the 2-byte integer located at an offset of 16 bytes from
55708     ** the beginning of the database file. */
55709     pageSize = (page1[16]<<8) | (page1[17]<<16);
55710     /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
55711     ** between 512 and 65536 inclusive. */
55712     if( ((pageSize-1)&pageSize)!=0
55713      || pageSize>SQLITE_MAX_PAGE_SIZE
55714      || pageSize<=256
55715     ){
55716       goto page1_init_failed;
55717     }
55718     assert( (pageSize & 7)==0 );
55719     /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
55720     ** integer at offset 20 is the number of bytes of space at the end of
55721     ** each page to reserve for extensions.
55722     **
55723     ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
55724     ** determined by the one-byte unsigned integer found at an offset of 20
55725     ** into the database file header. */
55726     usableSize = pageSize - page1[20];
55727     if( (u32)pageSize!=pBt->pageSize ){
55728       /* After reading the first page of the database assuming a page size
55729       ** of BtShared.pageSize, we have discovered that the page-size is
55730       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
55731       ** zero and return SQLITE_OK. The caller will call this function
55732       ** again with the correct page-size.
55733       */
55734       releasePage(pPage1);
55735       pBt->usableSize = usableSize;
55736       pBt->pageSize = pageSize;
55737       freeTempSpace(pBt);
55738       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
55739                                    pageSize-usableSize);
55740       return rc;
55741     }
55742     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
55743       rc = SQLITE_CORRUPT_BKPT;
55744       goto page1_init_failed;
55745     }
55746     /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
55747     ** be less than 480. In other words, if the page size is 512, then the
55748     ** reserved space size cannot exceed 32. */
55749     if( usableSize<480 ){
55750       goto page1_init_failed;
55751     }
55752     pBt->pageSize = pageSize;
55753     pBt->usableSize = usableSize;
55754 #ifndef SQLITE_OMIT_AUTOVACUUM
55755     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
55756     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
55757 #endif
55758   }
55759 
55760   /* maxLocal is the maximum amount of payload to store locally for
55761   ** a cell.  Make sure it is small enough so that at least minFanout
55762   ** cells can will fit on one page.  We assume a 10-byte page header.
55763   ** Besides the payload, the cell must store:
55764   **     2-byte pointer to the cell
55765   **     4-byte child pointer
55766   **     9-byte nKey value
55767   **     4-byte nData value
55768   **     4-byte overflow page pointer
55769   ** So a cell consists of a 2-byte pointer, a header which is as much as
55770   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
55771   ** page pointer.
55772   */
55773   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
55774   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
55775   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
55776   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
55777   if( pBt->maxLocal>127 ){
55778     pBt->max1bytePayload = 127;
55779   }else{
55780     pBt->max1bytePayload = (u8)pBt->maxLocal;
55781   }
55782   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
55783   pBt->pPage1 = pPage1;
55784   pBt->nPage = nPage;
55785   return SQLITE_OK;
55786 
55787 page1_init_failed:
55788   releasePage(pPage1);
55789   pBt->pPage1 = 0;
55790   return rc;
55791 }
55792 
55793 #ifndef NDEBUG
55794 /*
55795 ** Return the number of cursors open on pBt. This is for use
55796 ** in assert() expressions, so it is only compiled if NDEBUG is not
55797 ** defined.
55798 **
55799 ** Only write cursors are counted if wrOnly is true.  If wrOnly is
55800 ** false then all cursors are counted.
55801 **
55802 ** For the purposes of this routine, a cursor is any cursor that
55803 ** is capable of reading or writing to the database.  Cursors that
55804 ** have been tripped into the CURSOR_FAULT state are not counted.
55805 */
55806 static int countValidCursors(BtShared *pBt, int wrOnly){
55807   BtCursor *pCur;
55808   int r = 0;
55809   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
55810     if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
55811      && pCur->eState!=CURSOR_FAULT ) r++;
55812   }
55813   return r;
55814 }
55815 #endif
55816 
55817 /*
55818 ** If there are no outstanding cursors and we are not in the middle
55819 ** of a transaction but there is a read lock on the database, then
55820 ** this routine unrefs the first page of the database file which
55821 ** has the effect of releasing the read lock.
55822 **
55823 ** If there is a transaction in progress, this routine is a no-op.
55824 */
55825 static void unlockBtreeIfUnused(BtShared *pBt){
55826   assert( sqlite3_mutex_held(pBt->mutex) );
55827   assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
55828   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
55829     MemPage *pPage1 = pBt->pPage1;
55830     assert( pPage1->aData );
55831     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
55832     pBt->pPage1 = 0;
55833     releasePage(pPage1);
55834   }
55835 }
55836 
55837 /*
55838 ** If pBt points to an empty file then convert that empty file
55839 ** into a new empty database by initializing the first page of
55840 ** the database.
55841 */
55842 static int newDatabase(BtShared *pBt){
55843   MemPage *pP1;
55844   unsigned char *data;
55845   int rc;
55846 
55847   assert( sqlite3_mutex_held(pBt->mutex) );
55848   if( pBt->nPage>0 ){
55849     return SQLITE_OK;
55850   }
55851   pP1 = pBt->pPage1;
55852   assert( pP1!=0 );
55853   data = pP1->aData;
55854   rc = sqlite3PagerWrite(pP1->pDbPage);
55855   if( rc ) return rc;
55856   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
55857   assert( sizeof(zMagicHeader)==16 );
55858   data[16] = (u8)((pBt->pageSize>>8)&0xff);
55859   data[17] = (u8)((pBt->pageSize>>16)&0xff);
55860   data[18] = 1;
55861   data[19] = 1;
55862   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
55863   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
55864   data[21] = 64;
55865   data[22] = 32;
55866   data[23] = 32;
55867   memset(&data[24], 0, 100-24);
55868   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
55869   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
55870 #ifndef SQLITE_OMIT_AUTOVACUUM
55871   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
55872   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
55873   put4byte(&data[36 + 4*4], pBt->autoVacuum);
55874   put4byte(&data[36 + 7*4], pBt->incrVacuum);
55875 #endif
55876   pBt->nPage = 1;
55877   data[31] = 1;
55878   return SQLITE_OK;
55879 }
55880 
55881 /*
55882 ** Initialize the first page of the database file (creating a database
55883 ** consisting of a single page and no schema objects). Return SQLITE_OK
55884 ** if successful, or an SQLite error code otherwise.
55885 */
55886 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
55887   int rc;
55888   sqlite3BtreeEnter(p);
55889   p->pBt->nPage = 0;
55890   rc = newDatabase(p->pBt);
55891   sqlite3BtreeLeave(p);
55892   return rc;
55893 }
55894 
55895 /*
55896 ** Attempt to start a new transaction. A write-transaction
55897 ** is started if the second argument is nonzero, otherwise a read-
55898 ** transaction.  If the second argument is 2 or more and exclusive
55899 ** transaction is started, meaning that no other process is allowed
55900 ** to access the database.  A preexisting transaction may not be
55901 ** upgraded to exclusive by calling this routine a second time - the
55902 ** exclusivity flag only works for a new transaction.
55903 **
55904 ** A write-transaction must be started before attempting any
55905 ** changes to the database.  None of the following routines
55906 ** will work unless a transaction is started first:
55907 **
55908 **      sqlite3BtreeCreateTable()
55909 **      sqlite3BtreeCreateIndex()
55910 **      sqlite3BtreeClearTable()
55911 **      sqlite3BtreeDropTable()
55912 **      sqlite3BtreeInsert()
55913 **      sqlite3BtreeDelete()
55914 **      sqlite3BtreeUpdateMeta()
55915 **
55916 ** If an initial attempt to acquire the lock fails because of lock contention
55917 ** and the database was previously unlocked, then invoke the busy handler
55918 ** if there is one.  But if there was previously a read-lock, do not
55919 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
55920 ** returned when there is already a read-lock in order to avoid a deadlock.
55921 **
55922 ** Suppose there are two processes A and B.  A has a read lock and B has
55923 ** a reserved lock.  B tries to promote to exclusive but is blocked because
55924 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
55925 ** One or the other of the two processes must give way or there can be
55926 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
55927 ** when A already has a read lock, we encourage A to give up and let B
55928 ** proceed.
55929 */
55930 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
55931   sqlite3 *pBlock = 0;
55932   BtShared *pBt = p->pBt;
55933   int rc = SQLITE_OK;
55934 
55935   sqlite3BtreeEnter(p);
55936   btreeIntegrity(p);
55937 
55938   /* If the btree is already in a write-transaction, or it
55939   ** is already in a read-transaction and a read-transaction
55940   ** is requested, this is a no-op.
55941   */
55942   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
55943     goto trans_begun;
55944   }
55945   assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
55946 
55947   /* Write transactions are not possible on a read-only database */
55948   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
55949     rc = SQLITE_READONLY;
55950     goto trans_begun;
55951   }
55952 
55953 #ifndef SQLITE_OMIT_SHARED_CACHE
55954   /* If another database handle has already opened a write transaction
55955   ** on this shared-btree structure and a second write transaction is
55956   ** requested, return SQLITE_LOCKED.
55957   */
55958   if( (wrflag && pBt->inTransaction==TRANS_WRITE)
55959    || (pBt->btsFlags & BTS_PENDING)!=0
55960   ){
55961     pBlock = pBt->pWriter->db;
55962   }else if( wrflag>1 ){
55963     BtLock *pIter;
55964     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
55965       if( pIter->pBtree!=p ){
55966         pBlock = pIter->pBtree->db;
55967         break;
55968       }
55969     }
55970   }
55971   if( pBlock ){
55972     sqlite3ConnectionBlocked(p->db, pBlock);
55973     rc = SQLITE_LOCKED_SHAREDCACHE;
55974     goto trans_begun;
55975   }
55976 #endif
55977 
55978   /* Any read-only or read-write transaction implies a read-lock on
55979   ** page 1. So if some other shared-cache client already has a write-lock
55980   ** on page 1, the transaction cannot be opened. */
55981   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
55982   if( SQLITE_OK!=rc ) goto trans_begun;
55983 
55984   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
55985   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
55986   do {
55987     /* Call lockBtree() until either pBt->pPage1 is populated or
55988     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
55989     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
55990     ** reading page 1 it discovers that the page-size of the database
55991     ** file is not pBt->pageSize. In this case lockBtree() will update
55992     ** pBt->pageSize to the page-size of the file on disk.
55993     */
55994     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
55995 
55996     if( rc==SQLITE_OK && wrflag ){
55997       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
55998         rc = SQLITE_READONLY;
55999       }else{
56000         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
56001         if( rc==SQLITE_OK ){
56002           rc = newDatabase(pBt);
56003         }
56004       }
56005     }
56006 
56007     if( rc!=SQLITE_OK ){
56008       unlockBtreeIfUnused(pBt);
56009     }
56010   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
56011           btreeInvokeBusyHandler(pBt) );
56012 
56013   if( rc==SQLITE_OK ){
56014     if( p->inTrans==TRANS_NONE ){
56015       pBt->nTransaction++;
56016 #ifndef SQLITE_OMIT_SHARED_CACHE
56017       if( p->sharable ){
56018         assert( p->lock.pBtree==p && p->lock.iTable==1 );
56019         p->lock.eLock = READ_LOCK;
56020         p->lock.pNext = pBt->pLock;
56021         pBt->pLock = &p->lock;
56022       }
56023 #endif
56024     }
56025     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
56026     if( p->inTrans>pBt->inTransaction ){
56027       pBt->inTransaction = p->inTrans;
56028     }
56029     if( wrflag ){
56030       MemPage *pPage1 = pBt->pPage1;
56031 #ifndef SQLITE_OMIT_SHARED_CACHE
56032       assert( !pBt->pWriter );
56033       pBt->pWriter = p;
56034       pBt->btsFlags &= ~BTS_EXCLUSIVE;
56035       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
56036 #endif
56037 
56038       /* If the db-size header field is incorrect (as it may be if an old
56039       ** client has been writing the database file), update it now. Doing
56040       ** this sooner rather than later means the database size can safely
56041       ** re-read the database size from page 1 if a savepoint or transaction
56042       ** rollback occurs within the transaction.
56043       */
56044       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
56045         rc = sqlite3PagerWrite(pPage1->pDbPage);
56046         if( rc==SQLITE_OK ){
56047           put4byte(&pPage1->aData[28], pBt->nPage);
56048         }
56049       }
56050     }
56051   }
56052 
56053 
56054 trans_begun:
56055   if( rc==SQLITE_OK && wrflag ){
56056     /* This call makes sure that the pager has the correct number of
56057     ** open savepoints. If the second parameter is greater than 0 and
56058     ** the sub-journal is not already open, then it will be opened here.
56059     */
56060     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
56061   }
56062 
56063   btreeIntegrity(p);
56064   sqlite3BtreeLeave(p);
56065   return rc;
56066 }
56067 
56068 #ifndef SQLITE_OMIT_AUTOVACUUM
56069 
56070 /*
56071 ** Set the pointer-map entries for all children of page pPage. Also, if
56072 ** pPage contains cells that point to overflow pages, set the pointer
56073 ** map entries for the overflow pages as well.
56074 */
56075 static int setChildPtrmaps(MemPage *pPage){
56076   int i;                             /* Counter variable */
56077   int nCell;                         /* Number of cells in page pPage */
56078   int rc;                            /* Return code */
56079   BtShared *pBt = pPage->pBt;
56080   u8 isInitOrig = pPage->isInit;
56081   Pgno pgno = pPage->pgno;
56082 
56083   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56084   rc = btreeInitPage(pPage);
56085   if( rc!=SQLITE_OK ){
56086     goto set_child_ptrmaps_out;
56087   }
56088   nCell = pPage->nCell;
56089 
56090   for(i=0; i<nCell; i++){
56091     u8 *pCell = findCell(pPage, i);
56092 
56093     ptrmapPutOvflPtr(pPage, pCell, &rc);
56094 
56095     if( !pPage->leaf ){
56096       Pgno childPgno = get4byte(pCell);
56097       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
56098     }
56099   }
56100 
56101   if( !pPage->leaf ){
56102     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
56103     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
56104   }
56105 
56106 set_child_ptrmaps_out:
56107   pPage->isInit = isInitOrig;
56108   return rc;
56109 }
56110 
56111 /*
56112 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
56113 ** that it points to iTo. Parameter eType describes the type of pointer to
56114 ** be modified, as  follows:
56115 **
56116 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
56117 **                   page of pPage.
56118 **
56119 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
56120 **                   page pointed to by one of the cells on pPage.
56121 **
56122 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
56123 **                   overflow page in the list.
56124 */
56125 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
56126   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56127   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
56128   if( eType==PTRMAP_OVERFLOW2 ){
56129     /* The pointer is always the first 4 bytes of the page in this case.  */
56130     if( get4byte(pPage->aData)!=iFrom ){
56131       return SQLITE_CORRUPT_BKPT;
56132     }
56133     put4byte(pPage->aData, iTo);
56134   }else{
56135     u8 isInitOrig = pPage->isInit;
56136     int i;
56137     int nCell;
56138 
56139     btreeInitPage(pPage);
56140     nCell = pPage->nCell;
56141 
56142     for(i=0; i<nCell; i++){
56143       u8 *pCell = findCell(pPage, i);
56144       if( eType==PTRMAP_OVERFLOW1 ){
56145         CellInfo info;
56146         btreeParseCellPtr(pPage, pCell, &info);
56147         if( info.iOverflow
56148          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
56149          && iFrom==get4byte(&pCell[info.iOverflow])
56150         ){
56151           put4byte(&pCell[info.iOverflow], iTo);
56152           break;
56153         }
56154       }else{
56155         if( get4byte(pCell)==iFrom ){
56156           put4byte(pCell, iTo);
56157           break;
56158         }
56159       }
56160     }
56161 
56162     if( i==nCell ){
56163       if( eType!=PTRMAP_BTREE ||
56164           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
56165         return SQLITE_CORRUPT_BKPT;
56166       }
56167       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
56168     }
56169 
56170     pPage->isInit = isInitOrig;
56171   }
56172   return SQLITE_OK;
56173 }
56174 
56175 
56176 /*
56177 ** Move the open database page pDbPage to location iFreePage in the
56178 ** database. The pDbPage reference remains valid.
56179 **
56180 ** The isCommit flag indicates that there is no need to remember that
56181 ** the journal needs to be sync()ed before database page pDbPage->pgno
56182 ** can be written to. The caller has already promised not to write to that
56183 ** page.
56184 */
56185 static int relocatePage(
56186   BtShared *pBt,           /* Btree */
56187   MemPage *pDbPage,        /* Open page to move */
56188   u8 eType,                /* Pointer map 'type' entry for pDbPage */
56189   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
56190   Pgno iFreePage,          /* The location to move pDbPage to */
56191   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
56192 ){
56193   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
56194   Pgno iDbPage = pDbPage->pgno;
56195   Pager *pPager = pBt->pPager;
56196   int rc;
56197 
56198   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
56199       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
56200   assert( sqlite3_mutex_held(pBt->mutex) );
56201   assert( pDbPage->pBt==pBt );
56202 
56203   /* Move page iDbPage from its current location to page number iFreePage */
56204   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
56205       iDbPage, iFreePage, iPtrPage, eType));
56206   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
56207   if( rc!=SQLITE_OK ){
56208     return rc;
56209   }
56210   pDbPage->pgno = iFreePage;
56211 
56212   /* If pDbPage was a btree-page, then it may have child pages and/or cells
56213   ** that point to overflow pages. The pointer map entries for all these
56214   ** pages need to be changed.
56215   **
56216   ** If pDbPage is an overflow page, then the first 4 bytes may store a
56217   ** pointer to a subsequent overflow page. If this is the case, then
56218   ** the pointer map needs to be updated for the subsequent overflow page.
56219   */
56220   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
56221     rc = setChildPtrmaps(pDbPage);
56222     if( rc!=SQLITE_OK ){
56223       return rc;
56224     }
56225   }else{
56226     Pgno nextOvfl = get4byte(pDbPage->aData);
56227     if( nextOvfl!=0 ){
56228       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
56229       if( rc!=SQLITE_OK ){
56230         return rc;
56231       }
56232     }
56233   }
56234 
56235   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
56236   ** that it points at iFreePage. Also fix the pointer map entry for
56237   ** iPtrPage.
56238   */
56239   if( eType!=PTRMAP_ROOTPAGE ){
56240     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
56241     if( rc!=SQLITE_OK ){
56242       return rc;
56243     }
56244     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
56245     if( rc!=SQLITE_OK ){
56246       releasePage(pPtrPage);
56247       return rc;
56248     }
56249     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
56250     releasePage(pPtrPage);
56251     if( rc==SQLITE_OK ){
56252       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
56253     }
56254   }
56255   return rc;
56256 }
56257 
56258 /* Forward declaration required by incrVacuumStep(). */
56259 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
56260 
56261 /*
56262 ** Perform a single step of an incremental-vacuum. If successful, return
56263 ** SQLITE_OK. If there is no work to do (and therefore no point in
56264 ** calling this function again), return SQLITE_DONE. Or, if an error
56265 ** occurs, return some other error code.
56266 **
56267 ** More specifically, this function attempts to re-organize the database so
56268 ** that the last page of the file currently in use is no longer in use.
56269 **
56270 ** Parameter nFin is the number of pages that this database would contain
56271 ** were this function called until it returns SQLITE_DONE.
56272 **
56273 ** If the bCommit parameter is non-zero, this function assumes that the
56274 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
56275 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
56276 ** operation, or false for an incremental vacuum.
56277 */
56278 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
56279   Pgno nFreeList;           /* Number of pages still on the free-list */
56280   int rc;
56281 
56282   assert( sqlite3_mutex_held(pBt->mutex) );
56283   assert( iLastPg>nFin );
56284 
56285   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
56286     u8 eType;
56287     Pgno iPtrPage;
56288 
56289     nFreeList = get4byte(&pBt->pPage1->aData[36]);
56290     if( nFreeList==0 ){
56291       return SQLITE_DONE;
56292     }
56293 
56294     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
56295     if( rc!=SQLITE_OK ){
56296       return rc;
56297     }
56298     if( eType==PTRMAP_ROOTPAGE ){
56299       return SQLITE_CORRUPT_BKPT;
56300     }
56301 
56302     if( eType==PTRMAP_FREEPAGE ){
56303       if( bCommit==0 ){
56304         /* Remove the page from the files free-list. This is not required
56305         ** if bCommit is non-zero. In that case, the free-list will be
56306         ** truncated to zero after this function returns, so it doesn't
56307         ** matter if it still contains some garbage entries.
56308         */
56309         Pgno iFreePg;
56310         MemPage *pFreePg;
56311         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
56312         if( rc!=SQLITE_OK ){
56313           return rc;
56314         }
56315         assert( iFreePg==iLastPg );
56316         releasePage(pFreePg);
56317       }
56318     } else {
56319       Pgno iFreePg;             /* Index of free page to move pLastPg to */
56320       MemPage *pLastPg;
56321       u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
56322       Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
56323 
56324       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
56325       if( rc!=SQLITE_OK ){
56326         return rc;
56327       }
56328 
56329       /* If bCommit is zero, this loop runs exactly once and page pLastPg
56330       ** is swapped with the first free page pulled off the free list.
56331       **
56332       ** On the other hand, if bCommit is greater than zero, then keep
56333       ** looping until a free-page located within the first nFin pages
56334       ** of the file is found.
56335       */
56336       if( bCommit==0 ){
56337         eMode = BTALLOC_LE;
56338         iNear = nFin;
56339       }
56340       do {
56341         MemPage *pFreePg;
56342         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
56343         if( rc!=SQLITE_OK ){
56344           releasePage(pLastPg);
56345           return rc;
56346         }
56347         releasePage(pFreePg);
56348       }while( bCommit && iFreePg>nFin );
56349       assert( iFreePg<iLastPg );
56350 
56351       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
56352       releasePage(pLastPg);
56353       if( rc!=SQLITE_OK ){
56354         return rc;
56355       }
56356     }
56357   }
56358 
56359   if( bCommit==0 ){
56360     do {
56361       iLastPg--;
56362     }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
56363     pBt->bDoTruncate = 1;
56364     pBt->nPage = iLastPg;
56365   }
56366   return SQLITE_OK;
56367 }
56368 
56369 /*
56370 ** The database opened by the first argument is an auto-vacuum database
56371 ** nOrig pages in size containing nFree free pages. Return the expected
56372 ** size of the database in pages following an auto-vacuum operation.
56373 */
56374 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
56375   int nEntry;                     /* Number of entries on one ptrmap page */
56376   Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
56377   Pgno nFin;                      /* Return value */
56378 
56379   nEntry = pBt->usableSize/5;
56380   nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
56381   nFin = nOrig - nFree - nPtrmap;
56382   if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
56383     nFin--;
56384   }
56385   while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
56386     nFin--;
56387   }
56388 
56389   return nFin;
56390 }
56391 
56392 /*
56393 ** A write-transaction must be opened before calling this function.
56394 ** It performs a single unit of work towards an incremental vacuum.
56395 **
56396 ** If the incremental vacuum is finished after this function has run,
56397 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
56398 ** SQLITE_OK is returned. Otherwise an SQLite error code.
56399 */
56400 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
56401   int rc;
56402   BtShared *pBt = p->pBt;
56403 
56404   sqlite3BtreeEnter(p);
56405   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
56406   if( !pBt->autoVacuum ){
56407     rc = SQLITE_DONE;
56408   }else{
56409     Pgno nOrig = btreePagecount(pBt);
56410     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
56411     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
56412 
56413     if( nOrig<nFin ){
56414       rc = SQLITE_CORRUPT_BKPT;
56415     }else if( nFree>0 ){
56416       rc = saveAllCursors(pBt, 0, 0);
56417       if( rc==SQLITE_OK ){
56418         invalidateAllOverflowCache(pBt);
56419         rc = incrVacuumStep(pBt, nFin, nOrig, 0);
56420       }
56421       if( rc==SQLITE_OK ){
56422         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
56423         put4byte(&pBt->pPage1->aData[28], pBt->nPage);
56424       }
56425     }else{
56426       rc = SQLITE_DONE;
56427     }
56428   }
56429   sqlite3BtreeLeave(p);
56430   return rc;
56431 }
56432 
56433 /*
56434 ** This routine is called prior to sqlite3PagerCommit when a transaction
56435 ** is committed for an auto-vacuum database.
56436 **
56437 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
56438 ** the database file should be truncated to during the commit process.
56439 ** i.e. the database has been reorganized so that only the first *pnTrunc
56440 ** pages are in use.
56441 */
56442 static int autoVacuumCommit(BtShared *pBt){
56443   int rc = SQLITE_OK;
56444   Pager *pPager = pBt->pPager;
56445   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
56446 
56447   assert( sqlite3_mutex_held(pBt->mutex) );
56448   invalidateAllOverflowCache(pBt);
56449   assert(pBt->autoVacuum);
56450   if( !pBt->incrVacuum ){
56451     Pgno nFin;         /* Number of pages in database after autovacuuming */
56452     Pgno nFree;        /* Number of pages on the freelist initially */
56453     Pgno iFree;        /* The next page to be freed */
56454     Pgno nOrig;        /* Database size before freeing */
56455 
56456     nOrig = btreePagecount(pBt);
56457     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
56458       /* It is not possible to create a database for which the final page
56459       ** is either a pointer-map page or the pending-byte page. If one
56460       ** is encountered, this indicates corruption.
56461       */
56462       return SQLITE_CORRUPT_BKPT;
56463     }
56464 
56465     nFree = get4byte(&pBt->pPage1->aData[36]);
56466     nFin = finalDbSize(pBt, nOrig, nFree);
56467     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
56468     if( nFin<nOrig ){
56469       rc = saveAllCursors(pBt, 0, 0);
56470     }
56471     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
56472       rc = incrVacuumStep(pBt, nFin, iFree, 1);
56473     }
56474     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
56475       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
56476       put4byte(&pBt->pPage1->aData[32], 0);
56477       put4byte(&pBt->pPage1->aData[36], 0);
56478       put4byte(&pBt->pPage1->aData[28], nFin);
56479       pBt->bDoTruncate = 1;
56480       pBt->nPage = nFin;
56481     }
56482     if( rc!=SQLITE_OK ){
56483       sqlite3PagerRollback(pPager);
56484     }
56485   }
56486 
56487   assert( nRef>=sqlite3PagerRefcount(pPager) );
56488   return rc;
56489 }
56490 
56491 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
56492 # define setChildPtrmaps(x) SQLITE_OK
56493 #endif
56494 
56495 /*
56496 ** This routine does the first phase of a two-phase commit.  This routine
56497 ** causes a rollback journal to be created (if it does not already exist)
56498 ** and populated with enough information so that if a power loss occurs
56499 ** the database can be restored to its original state by playing back
56500 ** the journal.  Then the contents of the journal are flushed out to
56501 ** the disk.  After the journal is safely on oxide, the changes to the
56502 ** database are written into the database file and flushed to oxide.
56503 ** At the end of this call, the rollback journal still exists on the
56504 ** disk and we are still holding all locks, so the transaction has not
56505 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
56506 ** commit process.
56507 **
56508 ** This call is a no-op if no write-transaction is currently active on pBt.
56509 **
56510 ** Otherwise, sync the database file for the btree pBt. zMaster points to
56511 ** the name of a master journal file that should be written into the
56512 ** individual journal file, or is NULL, indicating no master journal file
56513 ** (single database transaction).
56514 **
56515 ** When this is called, the master journal should already have been
56516 ** created, populated with this journal pointer and synced to disk.
56517 **
56518 ** Once this is routine has returned, the only thing required to commit
56519 ** the write-transaction for this database file is to delete the journal.
56520 */
56521 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
56522   int rc = SQLITE_OK;
56523   if( p->inTrans==TRANS_WRITE ){
56524     BtShared *pBt = p->pBt;
56525     sqlite3BtreeEnter(p);
56526 #ifndef SQLITE_OMIT_AUTOVACUUM
56527     if( pBt->autoVacuum ){
56528       rc = autoVacuumCommit(pBt);
56529       if( rc!=SQLITE_OK ){
56530         sqlite3BtreeLeave(p);
56531         return rc;
56532       }
56533     }
56534     if( pBt->bDoTruncate ){
56535       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
56536     }
56537 #endif
56538     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
56539     sqlite3BtreeLeave(p);
56540   }
56541   return rc;
56542 }
56543 
56544 /*
56545 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
56546 ** at the conclusion of a transaction.
56547 */
56548 static void btreeEndTransaction(Btree *p){
56549   BtShared *pBt = p->pBt;
56550   sqlite3 *db = p->db;
56551   assert( sqlite3BtreeHoldsMutex(p) );
56552 
56553 #ifndef SQLITE_OMIT_AUTOVACUUM
56554   pBt->bDoTruncate = 0;
56555 #endif
56556   if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
56557     /* If there are other active statements that belong to this database
56558     ** handle, downgrade to a read-only transaction. The other statements
56559     ** may still be reading from the database.  */
56560     downgradeAllSharedCacheTableLocks(p);
56561     p->inTrans = TRANS_READ;
56562   }else{
56563     /* If the handle had any kind of transaction open, decrement the
56564     ** transaction count of the shared btree. If the transaction count
56565     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
56566     ** call below will unlock the pager.  */
56567     if( p->inTrans!=TRANS_NONE ){
56568       clearAllSharedCacheTableLocks(p);
56569       pBt->nTransaction--;
56570       if( 0==pBt->nTransaction ){
56571         pBt->inTransaction = TRANS_NONE;
56572       }
56573     }
56574 
56575     /* Set the current transaction state to TRANS_NONE and unlock the
56576     ** pager if this call closed the only read or write transaction.  */
56577     p->inTrans = TRANS_NONE;
56578     unlockBtreeIfUnused(pBt);
56579   }
56580 
56581   btreeIntegrity(p);
56582 }
56583 
56584 /*
56585 ** Commit the transaction currently in progress.
56586 **
56587 ** This routine implements the second phase of a 2-phase commit.  The
56588 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
56589 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
56590 ** routine did all the work of writing information out to disk and flushing the
56591 ** contents so that they are written onto the disk platter.  All this
56592 ** routine has to do is delete or truncate or zero the header in the
56593 ** the rollback journal (which causes the transaction to commit) and
56594 ** drop locks.
56595 **
56596 ** Normally, if an error occurs while the pager layer is attempting to
56597 ** finalize the underlying journal file, this function returns an error and
56598 ** the upper layer will attempt a rollback. However, if the second argument
56599 ** is non-zero then this b-tree transaction is part of a multi-file
56600 ** transaction. In this case, the transaction has already been committed
56601 ** (by deleting a master journal file) and the caller will ignore this
56602 ** functions return code. So, even if an error occurs in the pager layer,
56603 ** reset the b-tree objects internal state to indicate that the write
56604 ** transaction has been closed. This is quite safe, as the pager will have
56605 ** transitioned to the error state.
56606 **
56607 ** This will release the write lock on the database file.  If there
56608 ** are no active cursors, it also releases the read lock.
56609 */
56610 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
56611 
56612   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
56613   sqlite3BtreeEnter(p);
56614   btreeIntegrity(p);
56615 
56616   /* If the handle has a write-transaction open, commit the shared-btrees
56617   ** transaction and set the shared state to TRANS_READ.
56618   */
56619   if( p->inTrans==TRANS_WRITE ){
56620     int rc;
56621     BtShared *pBt = p->pBt;
56622     assert( pBt->inTransaction==TRANS_WRITE );
56623     assert( pBt->nTransaction>0 );
56624     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
56625     if( rc!=SQLITE_OK && bCleanup==0 ){
56626       sqlite3BtreeLeave(p);
56627       return rc;
56628     }
56629     p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
56630     pBt->inTransaction = TRANS_READ;
56631     btreeClearHasContent(pBt);
56632   }
56633 
56634   btreeEndTransaction(p);
56635   sqlite3BtreeLeave(p);
56636   return SQLITE_OK;
56637 }
56638 
56639 /*
56640 ** Do both phases of a commit.
56641 */
56642 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
56643   int rc;
56644   sqlite3BtreeEnter(p);
56645   rc = sqlite3BtreeCommitPhaseOne(p, 0);
56646   if( rc==SQLITE_OK ){
56647     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
56648   }
56649   sqlite3BtreeLeave(p);
56650   return rc;
56651 }
56652 
56653 /*
56654 ** This routine sets the state to CURSOR_FAULT and the error
56655 ** code to errCode for every cursor on any BtShared that pBtree
56656 ** references.  Or if the writeOnly flag is set to 1, then only
56657 ** trip write cursors and leave read cursors unchanged.
56658 **
56659 ** Every cursor is a candidate to be tripped, including cursors
56660 ** that belong to other database connections that happen to be
56661 ** sharing the cache with pBtree.
56662 **
56663 ** This routine gets called when a rollback occurs. If the writeOnly
56664 ** flag is true, then only write-cursors need be tripped - read-only
56665 ** cursors save their current positions so that they may continue
56666 ** following the rollback. Or, if writeOnly is false, all cursors are
56667 ** tripped. In general, writeOnly is false if the transaction being
56668 ** rolled back modified the database schema. In this case b-tree root
56669 ** pages may be moved or deleted from the database altogether, making
56670 ** it unsafe for read cursors to continue.
56671 **
56672 ** If the writeOnly flag is true and an error is encountered while
56673 ** saving the current position of a read-only cursor, all cursors,
56674 ** including all read-cursors are tripped.
56675 **
56676 ** SQLITE_OK is returned if successful, or if an error occurs while
56677 ** saving a cursor position, an SQLite error code.
56678 */
56679 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
56680   BtCursor *p;
56681   int rc = SQLITE_OK;
56682 
56683   assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
56684   if( pBtree ){
56685     sqlite3BtreeEnter(pBtree);
56686     for(p=pBtree->pBt->pCursor; p; p=p->pNext){
56687       int i;
56688       if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
56689         if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
56690           rc = saveCursorPosition(p);
56691           if( rc!=SQLITE_OK ){
56692             (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
56693             break;
56694           }
56695         }
56696       }else{
56697         sqlite3BtreeClearCursor(p);
56698         p->eState = CURSOR_FAULT;
56699         p->skipNext = errCode;
56700       }
56701       for(i=0; i<=p->iPage; i++){
56702         releasePage(p->apPage[i]);
56703         p->apPage[i] = 0;
56704       }
56705     }
56706     sqlite3BtreeLeave(pBtree);
56707   }
56708   return rc;
56709 }
56710 
56711 /*
56712 ** Rollback the transaction in progress.
56713 **
56714 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
56715 ** Only write cursors are tripped if writeOnly is true but all cursors are
56716 ** tripped if writeOnly is false.  Any attempt to use
56717 ** a tripped cursor will result in an error.
56718 **
56719 ** This will release the write lock on the database file.  If there
56720 ** are no active cursors, it also releases the read lock.
56721 */
56722 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
56723   int rc;
56724   BtShared *pBt = p->pBt;
56725   MemPage *pPage1;
56726 
56727   assert( writeOnly==1 || writeOnly==0 );
56728   assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
56729   sqlite3BtreeEnter(p);
56730   if( tripCode==SQLITE_OK ){
56731     rc = tripCode = saveAllCursors(pBt, 0, 0);
56732     if( rc ) writeOnly = 0;
56733   }else{
56734     rc = SQLITE_OK;
56735   }
56736   if( tripCode ){
56737     int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
56738     assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
56739     if( rc2!=SQLITE_OK ) rc = rc2;
56740   }
56741   btreeIntegrity(p);
56742 
56743   if( p->inTrans==TRANS_WRITE ){
56744     int rc2;
56745 
56746     assert( TRANS_WRITE==pBt->inTransaction );
56747     rc2 = sqlite3PagerRollback(pBt->pPager);
56748     if( rc2!=SQLITE_OK ){
56749       rc = rc2;
56750     }
56751 
56752     /* The rollback may have destroyed the pPage1->aData value.  So
56753     ** call btreeGetPage() on page 1 again to make
56754     ** sure pPage1->aData is set correctly. */
56755     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
56756       int nPage = get4byte(28+(u8*)pPage1->aData);
56757       testcase( nPage==0 );
56758       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
56759       testcase( pBt->nPage!=nPage );
56760       pBt->nPage = nPage;
56761       releasePage(pPage1);
56762     }
56763     assert( countValidCursors(pBt, 1)==0 );
56764     pBt->inTransaction = TRANS_READ;
56765     btreeClearHasContent(pBt);
56766   }
56767 
56768   btreeEndTransaction(p);
56769   sqlite3BtreeLeave(p);
56770   return rc;
56771 }
56772 
56773 /*
56774 ** Start a statement subtransaction. The subtransaction can be rolled
56775 ** back independently of the main transaction. You must start a transaction
56776 ** before starting a subtransaction. The subtransaction is ended automatically
56777 ** if the main transaction commits or rolls back.
56778 **
56779 ** Statement subtransactions are used around individual SQL statements
56780 ** that are contained within a BEGIN...COMMIT block.  If a constraint
56781 ** error occurs within the statement, the effect of that one statement
56782 ** can be rolled back without having to rollback the entire transaction.
56783 **
56784 ** A statement sub-transaction is implemented as an anonymous savepoint. The
56785 ** value passed as the second parameter is the total number of savepoints,
56786 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
56787 ** are no active savepoints and no other statement-transactions open,
56788 ** iStatement is 1. This anonymous savepoint can be released or rolled back
56789 ** using the sqlite3BtreeSavepoint() function.
56790 */
56791 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
56792   int rc;
56793   BtShared *pBt = p->pBt;
56794   sqlite3BtreeEnter(p);
56795   assert( p->inTrans==TRANS_WRITE );
56796   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
56797   assert( iStatement>0 );
56798   assert( iStatement>p->db->nSavepoint );
56799   assert( pBt->inTransaction==TRANS_WRITE );
56800   /* At the pager level, a statement transaction is a savepoint with
56801   ** an index greater than all savepoints created explicitly using
56802   ** SQL statements. It is illegal to open, release or rollback any
56803   ** such savepoints while the statement transaction savepoint is active.
56804   */
56805   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
56806   sqlite3BtreeLeave(p);
56807   return rc;
56808 }
56809 
56810 /*
56811 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
56812 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
56813 ** savepoint identified by parameter iSavepoint, depending on the value
56814 ** of op.
56815 **
56816 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
56817 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
56818 ** contents of the entire transaction are rolled back. This is different
56819 ** from a normal transaction rollback, as no locks are released and the
56820 ** transaction remains open.
56821 */
56822 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
56823   int rc = SQLITE_OK;
56824   if( p && p->inTrans==TRANS_WRITE ){
56825     BtShared *pBt = p->pBt;
56826     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
56827     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
56828     sqlite3BtreeEnter(p);
56829     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
56830     if( rc==SQLITE_OK ){
56831       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
56832         pBt->nPage = 0;
56833       }
56834       rc = newDatabase(pBt);
56835       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
56836 
56837       /* The database size was written into the offset 28 of the header
56838       ** when the transaction started, so we know that the value at offset
56839       ** 28 is nonzero. */
56840       assert( pBt->nPage>0 );
56841     }
56842     sqlite3BtreeLeave(p);
56843   }
56844   return rc;
56845 }
56846 
56847 /*
56848 ** Create a new cursor for the BTree whose root is on the page
56849 ** iTable. If a read-only cursor is requested, it is assumed that
56850 ** the caller already has at least a read-only transaction open
56851 ** on the database already. If a write-cursor is requested, then
56852 ** the caller is assumed to have an open write transaction.
56853 **
56854 ** If wrFlag==0, then the cursor can only be used for reading.
56855 ** If wrFlag==1, then the cursor can be used for reading or for
56856 ** writing if other conditions for writing are also met.  These
56857 ** are the conditions that must be met in order for writing to
56858 ** be allowed:
56859 **
56860 ** 1:  The cursor must have been opened with wrFlag==1
56861 **
56862 ** 2:  Other database connections that share the same pager cache
56863 **     but which are not in the READ_UNCOMMITTED state may not have
56864 **     cursors open with wrFlag==0 on the same table.  Otherwise
56865 **     the changes made by this write cursor would be visible to
56866 **     the read cursors in the other database connection.
56867 **
56868 ** 3:  The database must be writable (not on read-only media)
56869 **
56870 ** 4:  There must be an active transaction.
56871 **
56872 ** No checking is done to make sure that page iTable really is the
56873 ** root page of a b-tree.  If it is not, then the cursor acquired
56874 ** will not work correctly.
56875 **
56876 ** It is assumed that the sqlite3BtreeCursorZero() has been called
56877 ** on pCur to initialize the memory space prior to invoking this routine.
56878 */
56879 static int btreeCursor(
56880   Btree *p,                              /* The btree */
56881   int iTable,                            /* Root page of table to open */
56882   int wrFlag,                            /* 1 to write. 0 read-only */
56883   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
56884   BtCursor *pCur                         /* Space for new cursor */
56885 ){
56886   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
56887 
56888   assert( sqlite3BtreeHoldsMutex(p) );
56889   assert( wrFlag==0 || wrFlag==1 );
56890 
56891   /* The following assert statements verify that if this is a sharable
56892   ** b-tree database, the connection is holding the required table locks,
56893   ** and that no other connection has any open cursor that conflicts with
56894   ** this lock.  */
56895   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
56896   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
56897 
56898   /* Assert that the caller has opened the required transaction. */
56899   assert( p->inTrans>TRANS_NONE );
56900   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
56901   assert( pBt->pPage1 && pBt->pPage1->aData );
56902 
56903   if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
56904     return SQLITE_READONLY;
56905   }
56906   if( wrFlag ){
56907     allocateTempSpace(pBt);
56908     if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
56909   }
56910   if( iTable==1 && btreePagecount(pBt)==0 ){
56911     assert( wrFlag==0 );
56912     iTable = 0;
56913   }
56914 
56915   /* Now that no other errors can occur, finish filling in the BtCursor
56916   ** variables and link the cursor into the BtShared list.  */
56917   pCur->pgnoRoot = (Pgno)iTable;
56918   pCur->iPage = -1;
56919   pCur->pKeyInfo = pKeyInfo;
56920   pCur->pBtree = p;
56921   pCur->pBt = pBt;
56922   assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
56923   pCur->curFlags = wrFlag;
56924   pCur->pNext = pBt->pCursor;
56925   if( pCur->pNext ){
56926     pCur->pNext->pPrev = pCur;
56927   }
56928   pBt->pCursor = pCur;
56929   pCur->eState = CURSOR_INVALID;
56930   return SQLITE_OK;
56931 }
56932 SQLITE_PRIVATE int sqlite3BtreeCursor(
56933   Btree *p,                                   /* The btree */
56934   int iTable,                                 /* Root page of table to open */
56935   int wrFlag,                                 /* 1 to write. 0 read-only */
56936   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
56937   BtCursor *pCur                              /* Write new cursor here */
56938 ){
56939   int rc;
56940   sqlite3BtreeEnter(p);
56941   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
56942   sqlite3BtreeLeave(p);
56943   return rc;
56944 }
56945 
56946 /*
56947 ** Return the size of a BtCursor object in bytes.
56948 **
56949 ** This interfaces is needed so that users of cursors can preallocate
56950 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
56951 ** to users so they cannot do the sizeof() themselves - they must call
56952 ** this routine.
56953 */
56954 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
56955   return ROUND8(sizeof(BtCursor));
56956 }
56957 
56958 /*
56959 ** Initialize memory that will be converted into a BtCursor object.
56960 **
56961 ** The simple approach here would be to memset() the entire object
56962 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
56963 ** do not need to be zeroed and they are large, so we can save a lot
56964 ** of run-time by skipping the initialization of those elements.
56965 */
56966 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
56967   memset(p, 0, offsetof(BtCursor, iPage));
56968 }
56969 
56970 /*
56971 ** Close a cursor.  The read lock on the database file is released
56972 ** when the last cursor is closed.
56973 */
56974 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
56975   Btree *pBtree = pCur->pBtree;
56976   if( pBtree ){
56977     int i;
56978     BtShared *pBt = pCur->pBt;
56979     sqlite3BtreeEnter(pBtree);
56980     sqlite3BtreeClearCursor(pCur);
56981     if( pCur->pPrev ){
56982       pCur->pPrev->pNext = pCur->pNext;
56983     }else{
56984       pBt->pCursor = pCur->pNext;
56985     }
56986     if( pCur->pNext ){
56987       pCur->pNext->pPrev = pCur->pPrev;
56988     }
56989     for(i=0; i<=pCur->iPage; i++){
56990       releasePage(pCur->apPage[i]);
56991     }
56992     unlockBtreeIfUnused(pBt);
56993     sqlite3_free(pCur->aOverflow);
56994     /* sqlite3_free(pCur); */
56995     sqlite3BtreeLeave(pBtree);
56996   }
56997   return SQLITE_OK;
56998 }
56999 
57000 /*
57001 ** Make sure the BtCursor* given in the argument has a valid
57002 ** BtCursor.info structure.  If it is not already valid, call
57003 ** btreeParseCell() to fill it in.
57004 **
57005 ** BtCursor.info is a cache of the information in the current cell.
57006 ** Using this cache reduces the number of calls to btreeParseCell().
57007 **
57008 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
57009 ** compiler to crash when getCellInfo() is implemented as a macro.
57010 ** But there is a measureable speed advantage to using the macro on gcc
57011 ** (when less compiler optimizations like -Os or -O0 are used and the
57012 ** compiler is not doing aggressive inlining.)  So we use a real function
57013 ** for MSVC and a macro for everything else.  Ticket #2457.
57014 */
57015 #ifndef NDEBUG
57016   static void assertCellInfo(BtCursor *pCur){
57017     CellInfo info;
57018     int iPage = pCur->iPage;
57019     memset(&info, 0, sizeof(info));
57020     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
57021     assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
57022   }
57023 #else
57024   #define assertCellInfo(x)
57025 #endif
57026 #ifdef _MSC_VER
57027   /* Use a real function in MSVC to work around bugs in that compiler. */
57028   static void getCellInfo(BtCursor *pCur){
57029     if( pCur->info.nSize==0 ){
57030       int iPage = pCur->iPage;
57031       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
57032       pCur->curFlags |= BTCF_ValidNKey;
57033     }else{
57034       assertCellInfo(pCur);
57035     }
57036   }
57037 #else /* if not _MSC_VER */
57038   /* Use a macro in all other compilers so that the function is inlined */
57039 #define getCellInfo(pCur)                                                      \
57040   if( pCur->info.nSize==0 ){                                                   \
57041     int iPage = pCur->iPage;                                                   \
57042     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);        \
57043     pCur->curFlags |= BTCF_ValidNKey;                                          \
57044   }else{                                                                       \
57045     assertCellInfo(pCur);                                                      \
57046   }
57047 #endif /* _MSC_VER */
57048 
57049 #ifndef NDEBUG  /* The next routine used only within assert() statements */
57050 /*
57051 ** Return true if the given BtCursor is valid.  A valid cursor is one
57052 ** that is currently pointing to a row in a (non-empty) table.
57053 ** This is a verification routine is used only within assert() statements.
57054 */
57055 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
57056   return pCur && pCur->eState==CURSOR_VALID;
57057 }
57058 #endif /* NDEBUG */
57059 
57060 /*
57061 ** Set *pSize to the size of the buffer needed to hold the value of
57062 ** the key for the current entry.  If the cursor is not pointing
57063 ** to a valid entry, *pSize is set to 0.
57064 **
57065 ** For a table with the INTKEY flag set, this routine returns the key
57066 ** itself, not the number of bytes in the key.
57067 **
57068 ** The caller must position the cursor prior to invoking this routine.
57069 **
57070 ** This routine cannot fail.  It always returns SQLITE_OK.
57071 */
57072 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
57073   assert( cursorHoldsMutex(pCur) );
57074   assert( pCur->eState==CURSOR_VALID );
57075   getCellInfo(pCur);
57076   *pSize = pCur->info.nKey;
57077   return SQLITE_OK;
57078 }
57079 
57080 /*
57081 ** Set *pSize to the number of bytes of data in the entry the
57082 ** cursor currently points to.
57083 **
57084 ** The caller must guarantee that the cursor is pointing to a non-NULL
57085 ** valid entry.  In other words, the calling procedure must guarantee
57086 ** that the cursor has Cursor.eState==CURSOR_VALID.
57087 **
57088 ** Failure is not possible.  This function always returns SQLITE_OK.
57089 ** It might just as well be a procedure (returning void) but we continue
57090 ** to return an integer result code for historical reasons.
57091 */
57092 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
57093   assert( cursorHoldsMutex(pCur) );
57094   assert( pCur->eState==CURSOR_VALID );
57095   assert( pCur->iPage>=0 );
57096   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
57097   assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
57098   getCellInfo(pCur);
57099   *pSize = pCur->info.nPayload;
57100   return SQLITE_OK;
57101 }
57102 
57103 /*
57104 ** Given the page number of an overflow page in the database (parameter
57105 ** ovfl), this function finds the page number of the next page in the
57106 ** linked list of overflow pages. If possible, it uses the auto-vacuum
57107 ** pointer-map data instead of reading the content of page ovfl to do so.
57108 **
57109 ** If an error occurs an SQLite error code is returned. Otherwise:
57110 **
57111 ** The page number of the next overflow page in the linked list is
57112 ** written to *pPgnoNext. If page ovfl is the last page in its linked
57113 ** list, *pPgnoNext is set to zero.
57114 **
57115 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
57116 ** to page number pOvfl was obtained, then *ppPage is set to point to that
57117 ** reference. It is the responsibility of the caller to call releasePage()
57118 ** on *ppPage to free the reference. In no reference was obtained (because
57119 ** the pointer-map was used to obtain the value for *pPgnoNext), then
57120 ** *ppPage is set to zero.
57121 */
57122 static int getOverflowPage(
57123   BtShared *pBt,               /* The database file */
57124   Pgno ovfl,                   /* Current overflow page number */
57125   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
57126   Pgno *pPgnoNext              /* OUT: Next overflow page number */
57127 ){
57128   Pgno next = 0;
57129   MemPage *pPage = 0;
57130   int rc = SQLITE_OK;
57131 
57132   assert( sqlite3_mutex_held(pBt->mutex) );
57133   assert(pPgnoNext);
57134 
57135 #ifndef SQLITE_OMIT_AUTOVACUUM
57136   /* Try to find the next page in the overflow list using the
57137   ** autovacuum pointer-map pages. Guess that the next page in
57138   ** the overflow list is page number (ovfl+1). If that guess turns
57139   ** out to be wrong, fall back to loading the data of page
57140   ** number ovfl to determine the next page number.
57141   */
57142   if( pBt->autoVacuum ){
57143     Pgno pgno;
57144     Pgno iGuess = ovfl+1;
57145     u8 eType;
57146 
57147     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
57148       iGuess++;
57149     }
57150 
57151     if( iGuess<=btreePagecount(pBt) ){
57152       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
57153       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
57154         next = iGuess;
57155         rc = SQLITE_DONE;
57156       }
57157     }
57158   }
57159 #endif
57160 
57161   assert( next==0 || rc==SQLITE_DONE );
57162   if( rc==SQLITE_OK ){
57163     rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
57164     assert( rc==SQLITE_OK || pPage==0 );
57165     if( rc==SQLITE_OK ){
57166       next = get4byte(pPage->aData);
57167     }
57168   }
57169 
57170   *pPgnoNext = next;
57171   if( ppPage ){
57172     *ppPage = pPage;
57173   }else{
57174     releasePage(pPage);
57175   }
57176   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
57177 }
57178 
57179 /*
57180 ** Copy data from a buffer to a page, or from a page to a buffer.
57181 **
57182 ** pPayload is a pointer to data stored on database page pDbPage.
57183 ** If argument eOp is false, then nByte bytes of data are copied
57184 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
57185 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
57186 ** of data are copied from the buffer pBuf to pPayload.
57187 **
57188 ** SQLITE_OK is returned on success, otherwise an error code.
57189 */
57190 static int copyPayload(
57191   void *pPayload,           /* Pointer to page data */
57192   void *pBuf,               /* Pointer to buffer */
57193   int nByte,                /* Number of bytes to copy */
57194   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
57195   DbPage *pDbPage           /* Page containing pPayload */
57196 ){
57197   if( eOp ){
57198     /* Copy data from buffer to page (a write operation) */
57199     int rc = sqlite3PagerWrite(pDbPage);
57200     if( rc!=SQLITE_OK ){
57201       return rc;
57202     }
57203     memcpy(pPayload, pBuf, nByte);
57204   }else{
57205     /* Copy data from page to buffer (a read operation) */
57206     memcpy(pBuf, pPayload, nByte);
57207   }
57208   return SQLITE_OK;
57209 }
57210 
57211 /*
57212 ** This function is used to read or overwrite payload information
57213 ** for the entry that the pCur cursor is pointing to. The eOp
57214 ** argument is interpreted as follows:
57215 **
57216 **   0: The operation is a read. Populate the overflow cache.
57217 **   1: The operation is a write. Populate the overflow cache.
57218 **   2: The operation is a read. Do not populate the overflow cache.
57219 **
57220 ** A total of "amt" bytes are read or written beginning at "offset".
57221 ** Data is read to or from the buffer pBuf.
57222 **
57223 ** The content being read or written might appear on the main page
57224 ** or be scattered out on multiple overflow pages.
57225 **
57226 ** If the current cursor entry uses one or more overflow pages and the
57227 ** eOp argument is not 2, this function may allocate space for and lazily
57228 ** populates the overflow page-list cache array (BtCursor.aOverflow).
57229 ** Subsequent calls use this cache to make seeking to the supplied offset
57230 ** more efficient.
57231 **
57232 ** Once an overflow page-list cache has been allocated, it may be
57233 ** invalidated if some other cursor writes to the same table, or if
57234 ** the cursor is moved to a different row. Additionally, in auto-vacuum
57235 ** mode, the following events may invalidate an overflow page-list cache.
57236 **
57237 **   * An incremental vacuum,
57238 **   * A commit in auto_vacuum="full" mode,
57239 **   * Creating a table (may require moving an overflow page).
57240 */
57241 static int accessPayload(
57242   BtCursor *pCur,      /* Cursor pointing to entry to read from */
57243   u32 offset,          /* Begin reading this far into payload */
57244   u32 amt,             /* Read this many bytes */
57245   unsigned char *pBuf, /* Write the bytes into this buffer */
57246   int eOp              /* zero to read. non-zero to write. */
57247 ){
57248   unsigned char *aPayload;
57249   int rc = SQLITE_OK;
57250   int iIdx = 0;
57251   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
57252   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
57253 #ifdef SQLITE_DIRECT_OVERFLOW_READ
57254   unsigned char * const pBufStart = pBuf;
57255   int bEnd;                                 /* True if reading to end of data */
57256 #endif
57257 
57258   assert( pPage );
57259   assert( pCur->eState==CURSOR_VALID );
57260   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
57261   assert( cursorHoldsMutex(pCur) );
57262   assert( eOp!=2 || offset==0 );    /* Always start from beginning for eOp==2 */
57263 
57264   getCellInfo(pCur);
57265   aPayload = pCur->info.pPayload;
57266 #ifdef SQLITE_DIRECT_OVERFLOW_READ
57267   bEnd = offset+amt==pCur->info.nPayload;
57268 #endif
57269   assert( offset+amt <= pCur->info.nPayload );
57270 
57271   if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
57272     /* Trying to read or write past the end of the data is an error */
57273     return SQLITE_CORRUPT_BKPT;
57274   }
57275 
57276   /* Check if data must be read/written to/from the btree page itself. */
57277   if( offset<pCur->info.nLocal ){
57278     int a = amt;
57279     if( a+offset>pCur->info.nLocal ){
57280       a = pCur->info.nLocal - offset;
57281     }
57282     rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
57283     offset = 0;
57284     pBuf += a;
57285     amt -= a;
57286   }else{
57287     offset -= pCur->info.nLocal;
57288   }
57289 
57290 
57291   if( rc==SQLITE_OK && amt>0 ){
57292     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
57293     Pgno nextPage;
57294 
57295     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
57296 
57297     /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
57298     ** Except, do not allocate aOverflow[] for eOp==2.
57299     **
57300     ** The aOverflow[] array is sized at one entry for each overflow page
57301     ** in the overflow chain. The page number of the first overflow page is
57302     ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
57303     ** means "not yet known" (the cache is lazily populated).
57304     */
57305     if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
57306       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
57307       if( nOvfl>pCur->nOvflAlloc ){
57308         Pgno *aNew = (Pgno*)sqlite3Realloc(
57309             pCur->aOverflow, nOvfl*2*sizeof(Pgno)
57310         );
57311         if( aNew==0 ){
57312           rc = SQLITE_NOMEM;
57313         }else{
57314           pCur->nOvflAlloc = nOvfl*2;
57315           pCur->aOverflow = aNew;
57316         }
57317       }
57318       if( rc==SQLITE_OK ){
57319         memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
57320         pCur->curFlags |= BTCF_ValidOvfl;
57321       }
57322     }
57323 
57324     /* If the overflow page-list cache has been allocated and the
57325     ** entry for the first required overflow page is valid, skip
57326     ** directly to it.
57327     */
57328     if( (pCur->curFlags & BTCF_ValidOvfl)!=0
57329      && pCur->aOverflow[offset/ovflSize]
57330     ){
57331       iIdx = (offset/ovflSize);
57332       nextPage = pCur->aOverflow[iIdx];
57333       offset = (offset%ovflSize);
57334     }
57335 
57336     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
57337 
57338       /* If required, populate the overflow page-list cache. */
57339       if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
57340         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
57341         pCur->aOverflow[iIdx] = nextPage;
57342       }
57343 
57344       if( offset>=ovflSize ){
57345         /* The only reason to read this page is to obtain the page
57346         ** number for the next page in the overflow chain. The page
57347         ** data is not required. So first try to lookup the overflow
57348         ** page-list cache, if any, then fall back to the getOverflowPage()
57349         ** function.
57350         **
57351         ** Note that the aOverflow[] array must be allocated because eOp!=2
57352         ** here.  If eOp==2, then offset==0 and this branch is never taken.
57353         */
57354         assert( eOp!=2 );
57355         assert( pCur->curFlags & BTCF_ValidOvfl );
57356         assert( pCur->pBtree->db==pBt->db );
57357         if( pCur->aOverflow[iIdx+1] ){
57358           nextPage = pCur->aOverflow[iIdx+1];
57359         }else{
57360           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
57361         }
57362         offset -= ovflSize;
57363       }else{
57364         /* Need to read this page properly. It contains some of the
57365         ** range of data that is being read (eOp==0) or written (eOp!=0).
57366         */
57367 #ifdef SQLITE_DIRECT_OVERFLOW_READ
57368         sqlite3_file *fd;
57369 #endif
57370         int a = amt;
57371         if( a + offset > ovflSize ){
57372           a = ovflSize - offset;
57373         }
57374 
57375 #ifdef SQLITE_DIRECT_OVERFLOW_READ
57376         /* If all the following are true:
57377         **
57378         **   1) this is a read operation, and
57379         **   2) data is required from the start of this overflow page, and
57380         **   3) the database is file-backed, and
57381         **   4) there is no open write-transaction, and
57382         **   5) the database is not a WAL database,
57383         **   6) all data from the page is being read.
57384         **   7) at least 4 bytes have already been read into the output buffer
57385         **
57386         ** then data can be read directly from the database file into the
57387         ** output buffer, bypassing the page-cache altogether. This speeds
57388         ** up loading large records that span many overflow pages.
57389         */
57390         if( (eOp&0x01)==0                                      /* (1) */
57391          && offset==0                                          /* (2) */
57392          && (bEnd || a==ovflSize)                              /* (6) */
57393          && pBt->inTransaction==TRANS_READ                     /* (4) */
57394          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
57395          && pBt->pPage1->aData[19]==0x01                       /* (5) */
57396          && &pBuf[-4]>=pBufStart                               /* (7) */
57397         ){
57398           u8 aSave[4];
57399           u8 *aWrite = &pBuf[-4];
57400           assert( aWrite>=pBufStart );                         /* hence (7) */
57401           memcpy(aSave, aWrite, 4);
57402           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
57403           nextPage = get4byte(aWrite);
57404           memcpy(aWrite, aSave, 4);
57405         }else
57406 #endif
57407 
57408         {
57409           DbPage *pDbPage;
57410           rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
57411               ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
57412           );
57413           if( rc==SQLITE_OK ){
57414             aPayload = sqlite3PagerGetData(pDbPage);
57415             nextPage = get4byte(aPayload);
57416             rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
57417             sqlite3PagerUnref(pDbPage);
57418             offset = 0;
57419           }
57420         }
57421         amt -= a;
57422         pBuf += a;
57423       }
57424     }
57425   }
57426 
57427   if( rc==SQLITE_OK && amt>0 ){
57428     return SQLITE_CORRUPT_BKPT;
57429   }
57430   return rc;
57431 }
57432 
57433 /*
57434 ** Read part of the key associated with cursor pCur.  Exactly
57435 ** "amt" bytes will be transferred into pBuf[].  The transfer
57436 ** begins at "offset".
57437 **
57438 ** The caller must ensure that pCur is pointing to a valid row
57439 ** in the table.
57440 **
57441 ** Return SQLITE_OK on success or an error code if anything goes
57442 ** wrong.  An error is returned if "offset+amt" is larger than
57443 ** the available payload.
57444 */
57445 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
57446   assert( cursorHoldsMutex(pCur) );
57447   assert( pCur->eState==CURSOR_VALID );
57448   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
57449   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
57450   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
57451 }
57452 
57453 /*
57454 ** Read part of the data associated with cursor pCur.  Exactly
57455 ** "amt" bytes will be transfered into pBuf[].  The transfer
57456 ** begins at "offset".
57457 **
57458 ** Return SQLITE_OK on success or an error code if anything goes
57459 ** wrong.  An error is returned if "offset+amt" is larger than
57460 ** the available payload.
57461 */
57462 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
57463   int rc;
57464 
57465 #ifndef SQLITE_OMIT_INCRBLOB
57466   if ( pCur->eState==CURSOR_INVALID ){
57467     return SQLITE_ABORT;
57468   }
57469 #endif
57470 
57471   assert( cursorHoldsMutex(pCur) );
57472   rc = restoreCursorPosition(pCur);
57473   if( rc==SQLITE_OK ){
57474     assert( pCur->eState==CURSOR_VALID );
57475     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
57476     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
57477     rc = accessPayload(pCur, offset, amt, pBuf, 0);
57478   }
57479   return rc;
57480 }
57481 
57482 /*
57483 ** Return a pointer to payload information from the entry that the
57484 ** pCur cursor is pointing to.  The pointer is to the beginning of
57485 ** the key if index btrees (pPage->intKey==0) and is the data for
57486 ** table btrees (pPage->intKey==1). The number of bytes of available
57487 ** key/data is written into *pAmt.  If *pAmt==0, then the value
57488 ** returned will not be a valid pointer.
57489 **
57490 ** This routine is an optimization.  It is common for the entire key
57491 ** and data to fit on the local page and for there to be no overflow
57492 ** pages.  When that is so, this routine can be used to access the
57493 ** key and data without making a copy.  If the key and/or data spills
57494 ** onto overflow pages, then accessPayload() must be used to reassemble
57495 ** the key/data and copy it into a preallocated buffer.
57496 **
57497 ** The pointer returned by this routine looks directly into the cached
57498 ** page of the database.  The data might change or move the next time
57499 ** any btree routine is called.
57500 */
57501 static const void *fetchPayload(
57502   BtCursor *pCur,      /* Cursor pointing to entry to read from */
57503   u32 *pAmt            /* Write the number of available bytes here */
57504 ){
57505   u32 amt;
57506   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
57507   assert( pCur->eState==CURSOR_VALID );
57508   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
57509   assert( cursorHoldsMutex(pCur) );
57510   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
57511   assert( pCur->info.nSize>0 );
57512   assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
57513   assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
57514   amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
57515   if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
57516   *pAmt = amt;
57517   return (void*)pCur->info.pPayload;
57518 }
57519 
57520 
57521 /*
57522 ** For the entry that cursor pCur is point to, return as
57523 ** many bytes of the key or data as are available on the local
57524 ** b-tree page.  Write the number of available bytes into *pAmt.
57525 **
57526 ** The pointer returned is ephemeral.  The key/data may move
57527 ** or be destroyed on the next call to any Btree routine,
57528 ** including calls from other threads against the same cache.
57529 ** Hence, a mutex on the BtShared should be held prior to calling
57530 ** this routine.
57531 **
57532 ** These routines is used to get quick access to key and data
57533 ** in the common case where no overflow pages are used.
57534 */
57535 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
57536   return fetchPayload(pCur, pAmt);
57537 }
57538 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
57539   return fetchPayload(pCur, pAmt);
57540 }
57541 
57542 
57543 /*
57544 ** Move the cursor down to a new child page.  The newPgno argument is the
57545 ** page number of the child page to move to.
57546 **
57547 ** This function returns SQLITE_CORRUPT if the page-header flags field of
57548 ** the new child page does not match the flags field of the parent (i.e.
57549 ** if an intkey page appears to be the parent of a non-intkey page, or
57550 ** vice-versa).
57551 */
57552 static int moveToChild(BtCursor *pCur, u32 newPgno){
57553   int rc;
57554   int i = pCur->iPage;
57555   MemPage *pNewPage;
57556   BtShared *pBt = pCur->pBt;
57557 
57558   assert( cursorHoldsMutex(pCur) );
57559   assert( pCur->eState==CURSOR_VALID );
57560   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
57561   assert( pCur->iPage>=0 );
57562   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
57563     return SQLITE_CORRUPT_BKPT;
57564   }
57565   rc = getAndInitPage(pBt, newPgno, &pNewPage,
57566                (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
57567   if( rc ) return rc;
57568   pCur->apPage[i+1] = pNewPage;
57569   pCur->aiIdx[i+1] = 0;
57570   pCur->iPage++;
57571 
57572   pCur->info.nSize = 0;
57573   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
57574   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
57575     return SQLITE_CORRUPT_BKPT;
57576   }
57577   return SQLITE_OK;
57578 }
57579 
57580 #if SQLITE_DEBUG
57581 /*
57582 ** Page pParent is an internal (non-leaf) tree page. This function
57583 ** asserts that page number iChild is the left-child if the iIdx'th
57584 ** cell in page pParent. Or, if iIdx is equal to the total number of
57585 ** cells in pParent, that page number iChild is the right-child of
57586 ** the page.
57587 */
57588 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
57589   if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
57590                             ** in a corrupt database */
57591   assert( iIdx<=pParent->nCell );
57592   if( iIdx==pParent->nCell ){
57593     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
57594   }else{
57595     assert( get4byte(findCell(pParent, iIdx))==iChild );
57596   }
57597 }
57598 #else
57599 #  define assertParentIndex(x,y,z)
57600 #endif
57601 
57602 /*
57603 ** Move the cursor up to the parent page.
57604 **
57605 ** pCur->idx is set to the cell index that contains the pointer
57606 ** to the page we are coming from.  If we are coming from the
57607 ** right-most child page then pCur->idx is set to one more than
57608 ** the largest cell index.
57609 */
57610 static void moveToParent(BtCursor *pCur){
57611   assert( cursorHoldsMutex(pCur) );
57612   assert( pCur->eState==CURSOR_VALID );
57613   assert( pCur->iPage>0 );
57614   assert( pCur->apPage[pCur->iPage] );
57615   assertParentIndex(
57616     pCur->apPage[pCur->iPage-1],
57617     pCur->aiIdx[pCur->iPage-1],
57618     pCur->apPage[pCur->iPage]->pgno
57619   );
57620   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
57621 
57622   releasePage(pCur->apPage[pCur->iPage]);
57623   pCur->iPage--;
57624   pCur->info.nSize = 0;
57625   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
57626 }
57627 
57628 /*
57629 ** Move the cursor to point to the root page of its b-tree structure.
57630 **
57631 ** If the table has a virtual root page, then the cursor is moved to point
57632 ** to the virtual root page instead of the actual root page. A table has a
57633 ** virtual root page when the actual root page contains no cells and a
57634 ** single child page. This can only happen with the table rooted at page 1.
57635 **
57636 ** If the b-tree structure is empty, the cursor state is set to
57637 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
57638 ** cell located on the root (or virtual root) page and the cursor state
57639 ** is set to CURSOR_VALID.
57640 **
57641 ** If this function returns successfully, it may be assumed that the
57642 ** page-header flags indicate that the [virtual] root-page is the expected
57643 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
57644 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
57645 ** indicating a table b-tree, or if the caller did specify a KeyInfo
57646 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
57647 ** b-tree).
57648 */
57649 static int moveToRoot(BtCursor *pCur){
57650   MemPage *pRoot;
57651   int rc = SQLITE_OK;
57652 
57653   assert( cursorHoldsMutex(pCur) );
57654   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
57655   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
57656   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
57657   if( pCur->eState>=CURSOR_REQUIRESEEK ){
57658     if( pCur->eState==CURSOR_FAULT ){
57659       assert( pCur->skipNext!=SQLITE_OK );
57660       return pCur->skipNext;
57661     }
57662     sqlite3BtreeClearCursor(pCur);
57663   }
57664 
57665   if( pCur->iPage>=0 ){
57666     while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
57667   }else if( pCur->pgnoRoot==0 ){
57668     pCur->eState = CURSOR_INVALID;
57669     return SQLITE_OK;
57670   }else{
57671     rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
57672                  (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
57673     if( rc!=SQLITE_OK ){
57674       pCur->eState = CURSOR_INVALID;
57675       return rc;
57676     }
57677     pCur->iPage = 0;
57678   }
57679   pRoot = pCur->apPage[0];
57680   assert( pRoot->pgno==pCur->pgnoRoot );
57681 
57682   /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
57683   ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
57684   ** NULL, the caller expects a table b-tree. If this is not the case,
57685   ** return an SQLITE_CORRUPT error.
57686   **
57687   ** Earlier versions of SQLite assumed that this test could not fail
57688   ** if the root page was already loaded when this function was called (i.e.
57689   ** if pCur->iPage>=0). But this is not so if the database is corrupted
57690   ** in such a way that page pRoot is linked into a second b-tree table
57691   ** (or the freelist).  */
57692   assert( pRoot->intKey==1 || pRoot->intKey==0 );
57693   if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
57694     return SQLITE_CORRUPT_BKPT;
57695   }
57696 
57697   pCur->aiIdx[0] = 0;
57698   pCur->info.nSize = 0;
57699   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
57700 
57701   if( pRoot->nCell>0 ){
57702     pCur->eState = CURSOR_VALID;
57703   }else if( !pRoot->leaf ){
57704     Pgno subpage;
57705     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
57706     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
57707     pCur->eState = CURSOR_VALID;
57708     rc = moveToChild(pCur, subpage);
57709   }else{
57710     pCur->eState = CURSOR_INVALID;
57711   }
57712   return rc;
57713 }
57714 
57715 /*
57716 ** Move the cursor down to the left-most leaf entry beneath the
57717 ** entry to which it is currently pointing.
57718 **
57719 ** The left-most leaf is the one with the smallest key - the first
57720 ** in ascending order.
57721 */
57722 static int moveToLeftmost(BtCursor *pCur){
57723   Pgno pgno;
57724   int rc = SQLITE_OK;
57725   MemPage *pPage;
57726 
57727   assert( cursorHoldsMutex(pCur) );
57728   assert( pCur->eState==CURSOR_VALID );
57729   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
57730     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
57731     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
57732     rc = moveToChild(pCur, pgno);
57733   }
57734   return rc;
57735 }
57736 
57737 /*
57738 ** Move the cursor down to the right-most leaf entry beneath the
57739 ** page to which it is currently pointing.  Notice the difference
57740 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
57741 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
57742 ** finds the right-most entry beneath the *page*.
57743 **
57744 ** The right-most entry is the one with the largest key - the last
57745 ** key in ascending order.
57746 */
57747 static int moveToRightmost(BtCursor *pCur){
57748   Pgno pgno;
57749   int rc = SQLITE_OK;
57750   MemPage *pPage = 0;
57751 
57752   assert( cursorHoldsMutex(pCur) );
57753   assert( pCur->eState==CURSOR_VALID );
57754   while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
57755     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57756     pCur->aiIdx[pCur->iPage] = pPage->nCell;
57757     rc = moveToChild(pCur, pgno);
57758     if( rc ) return rc;
57759   }
57760   pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
57761   assert( pCur->info.nSize==0 );
57762   assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
57763   return SQLITE_OK;
57764 }
57765 
57766 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
57767 ** on success.  Set *pRes to 0 if the cursor actually points to something
57768 ** or set *pRes to 1 if the table is empty.
57769 */
57770 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
57771   int rc;
57772 
57773   assert( cursorHoldsMutex(pCur) );
57774   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
57775   rc = moveToRoot(pCur);
57776   if( rc==SQLITE_OK ){
57777     if( pCur->eState==CURSOR_INVALID ){
57778       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
57779       *pRes = 1;
57780     }else{
57781       assert( pCur->apPage[pCur->iPage]->nCell>0 );
57782       *pRes = 0;
57783       rc = moveToLeftmost(pCur);
57784     }
57785   }
57786   return rc;
57787 }
57788 
57789 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
57790 ** on success.  Set *pRes to 0 if the cursor actually points to something
57791 ** or set *pRes to 1 if the table is empty.
57792 */
57793 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
57794   int rc;
57795 
57796   assert( cursorHoldsMutex(pCur) );
57797   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
57798 
57799   /* If the cursor already points to the last entry, this is a no-op. */
57800   if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
57801 #ifdef SQLITE_DEBUG
57802     /* This block serves to assert() that the cursor really does point
57803     ** to the last entry in the b-tree. */
57804     int ii;
57805     for(ii=0; ii<pCur->iPage; ii++){
57806       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
57807     }
57808     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
57809     assert( pCur->apPage[pCur->iPage]->leaf );
57810 #endif
57811     return SQLITE_OK;
57812   }
57813 
57814   rc = moveToRoot(pCur);
57815   if( rc==SQLITE_OK ){
57816     if( CURSOR_INVALID==pCur->eState ){
57817       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
57818       *pRes = 1;
57819     }else{
57820       assert( pCur->eState==CURSOR_VALID );
57821       *pRes = 0;
57822       rc = moveToRightmost(pCur);
57823       if( rc==SQLITE_OK ){
57824         pCur->curFlags |= BTCF_AtLast;
57825       }else{
57826         pCur->curFlags &= ~BTCF_AtLast;
57827       }
57828 
57829     }
57830   }
57831   return rc;
57832 }
57833 
57834 /* Move the cursor so that it points to an entry near the key
57835 ** specified by pIdxKey or intKey.   Return a success code.
57836 **
57837 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
57838 ** must be NULL.  For index tables, pIdxKey is used and intKey
57839 ** is ignored.
57840 **
57841 ** If an exact match is not found, then the cursor is always
57842 ** left pointing at a leaf page which would hold the entry if it
57843 ** were present.  The cursor might point to an entry that comes
57844 ** before or after the key.
57845 **
57846 ** An integer is written into *pRes which is the result of
57847 ** comparing the key with the entry to which the cursor is
57848 ** pointing.  The meaning of the integer written into
57849 ** *pRes is as follows:
57850 **
57851 **     *pRes<0      The cursor is left pointing at an entry that
57852 **                  is smaller than intKey/pIdxKey or if the table is empty
57853 **                  and the cursor is therefore left point to nothing.
57854 **
57855 **     *pRes==0     The cursor is left pointing at an entry that
57856 **                  exactly matches intKey/pIdxKey.
57857 **
57858 **     *pRes>0      The cursor is left pointing at an entry that
57859 **                  is larger than intKey/pIdxKey.
57860 **
57861 */
57862 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
57863   BtCursor *pCur,          /* The cursor to be moved */
57864   UnpackedRecord *pIdxKey, /* Unpacked index key */
57865   i64 intKey,              /* The table key */
57866   int biasRight,           /* If true, bias the search to the high end */
57867   int *pRes                /* Write search results here */
57868 ){
57869   int rc;
57870   RecordCompare xRecordCompare;
57871 
57872   assert( cursorHoldsMutex(pCur) );
57873   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
57874   assert( pRes );
57875   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
57876 
57877   /* If the cursor is already positioned at the point we are trying
57878   ** to move to, then just return without doing any work */
57879   if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
57880    && pCur->apPage[0]->intKey
57881   ){
57882     if( pCur->info.nKey==intKey ){
57883       *pRes = 0;
57884       return SQLITE_OK;
57885     }
57886     if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
57887       *pRes = -1;
57888       return SQLITE_OK;
57889     }
57890   }
57891 
57892   if( pIdxKey ){
57893     xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
57894     pIdxKey->errCode = 0;
57895     assert( pIdxKey->default_rc==1
57896          || pIdxKey->default_rc==0
57897          || pIdxKey->default_rc==-1
57898     );
57899   }else{
57900     xRecordCompare = 0; /* All keys are integers */
57901   }
57902 
57903   rc = moveToRoot(pCur);
57904   if( rc ){
57905     return rc;
57906   }
57907   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
57908   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
57909   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
57910   if( pCur->eState==CURSOR_INVALID ){
57911     *pRes = -1;
57912     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
57913     return SQLITE_OK;
57914   }
57915   assert( pCur->apPage[0]->intKey || pIdxKey );
57916   for(;;){
57917     int lwr, upr, idx, c;
57918     Pgno chldPg;
57919     MemPage *pPage = pCur->apPage[pCur->iPage];
57920     u8 *pCell;                          /* Pointer to current cell in pPage */
57921 
57922     /* pPage->nCell must be greater than zero. If this is the root-page
57923     ** the cursor would have been INVALID above and this for(;;) loop
57924     ** not run. If this is not the root-page, then the moveToChild() routine
57925     ** would have already detected db corruption. Similarly, pPage must
57926     ** be the right kind (index or table) of b-tree page. Otherwise
57927     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
57928     assert( pPage->nCell>0 );
57929     assert( pPage->intKey==(pIdxKey==0) );
57930     lwr = 0;
57931     upr = pPage->nCell-1;
57932     assert( biasRight==0 || biasRight==1 );
57933     idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
57934     pCur->aiIdx[pCur->iPage] = (u16)idx;
57935     if( xRecordCompare==0 ){
57936       for(;;){
57937         i64 nCellKey;
57938         pCell = findCell(pPage, idx) + pPage->childPtrSize;
57939         if( pPage->intKeyLeaf ){
57940           while( 0x80 <= *(pCell++) ){
57941             if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
57942           }
57943         }
57944         getVarint(pCell, (u64*)&nCellKey);
57945         if( nCellKey<intKey ){
57946           lwr = idx+1;
57947           if( lwr>upr ){ c = -1; break; }
57948         }else if( nCellKey>intKey ){
57949           upr = idx-1;
57950           if( lwr>upr ){ c = +1; break; }
57951         }else{
57952           assert( nCellKey==intKey );
57953           pCur->curFlags |= BTCF_ValidNKey;
57954           pCur->info.nKey = nCellKey;
57955           pCur->aiIdx[pCur->iPage] = (u16)idx;
57956           if( !pPage->leaf ){
57957             lwr = idx;
57958             goto moveto_next_layer;
57959           }else{
57960             *pRes = 0;
57961             rc = SQLITE_OK;
57962             goto moveto_finish;
57963           }
57964         }
57965         assert( lwr+upr>=0 );
57966         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
57967       }
57968     }else{
57969       for(;;){
57970         int nCell;
57971         pCell = findCell(pPage, idx) + pPage->childPtrSize;
57972 
57973         /* The maximum supported page-size is 65536 bytes. This means that
57974         ** the maximum number of record bytes stored on an index B-Tree
57975         ** page is less than 16384 bytes and may be stored as a 2-byte
57976         ** varint. This information is used to attempt to avoid parsing
57977         ** the entire cell by checking for the cases where the record is
57978         ** stored entirely within the b-tree page by inspecting the first
57979         ** 2 bytes of the cell.
57980         */
57981         nCell = pCell[0];
57982         if( nCell<=pPage->max1bytePayload ){
57983           /* This branch runs if the record-size field of the cell is a
57984           ** single byte varint and the record fits entirely on the main
57985           ** b-tree page.  */
57986           testcase( pCell+nCell+1==pPage->aDataEnd );
57987           c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
57988         }else if( !(pCell[1] & 0x80)
57989           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
57990         ){
57991           /* The record-size field is a 2 byte varint and the record
57992           ** fits entirely on the main b-tree page.  */
57993           testcase( pCell+nCell+2==pPage->aDataEnd );
57994           c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
57995         }else{
57996           /* The record flows over onto one or more overflow pages. In
57997           ** this case the whole cell needs to be parsed, a buffer allocated
57998           ** and accessPayload() used to retrieve the record into the
57999           ** buffer before VdbeRecordCompare() can be called. */
58000           void *pCellKey;
58001           u8 * const pCellBody = pCell - pPage->childPtrSize;
58002           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
58003           nCell = (int)pCur->info.nKey;
58004           pCellKey = sqlite3Malloc( nCell );
58005           if( pCellKey==0 ){
58006             rc = SQLITE_NOMEM;
58007             goto moveto_finish;
58008           }
58009           pCur->aiIdx[pCur->iPage] = (u16)idx;
58010           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
58011           if( rc ){
58012             sqlite3_free(pCellKey);
58013             goto moveto_finish;
58014           }
58015           c = xRecordCompare(nCell, pCellKey, pIdxKey);
58016           sqlite3_free(pCellKey);
58017         }
58018         assert(
58019             (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
58020          && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
58021         );
58022         if( c<0 ){
58023           lwr = idx+1;
58024         }else if( c>0 ){
58025           upr = idx-1;
58026         }else{
58027           assert( c==0 );
58028           *pRes = 0;
58029           rc = SQLITE_OK;
58030           pCur->aiIdx[pCur->iPage] = (u16)idx;
58031           if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
58032           goto moveto_finish;
58033         }
58034         if( lwr>upr ) break;
58035         assert( lwr+upr>=0 );
58036         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
58037       }
58038     }
58039     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
58040     assert( pPage->isInit );
58041     if( pPage->leaf ){
58042       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
58043       pCur->aiIdx[pCur->iPage] = (u16)idx;
58044       *pRes = c;
58045       rc = SQLITE_OK;
58046       goto moveto_finish;
58047     }
58048 moveto_next_layer:
58049     if( lwr>=pPage->nCell ){
58050       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
58051     }else{
58052       chldPg = get4byte(findCell(pPage, lwr));
58053     }
58054     pCur->aiIdx[pCur->iPage] = (u16)lwr;
58055     rc = moveToChild(pCur, chldPg);
58056     if( rc ) break;
58057   }
58058 moveto_finish:
58059   pCur->info.nSize = 0;
58060   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
58061   return rc;
58062 }
58063 
58064 
58065 /*
58066 ** Return TRUE if the cursor is not pointing at an entry of the table.
58067 **
58068 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
58069 ** past the last entry in the table or sqlite3BtreePrev() moves past
58070 ** the first entry.  TRUE is also returned if the table is empty.
58071 */
58072 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
58073   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
58074   ** have been deleted? This API will need to change to return an error code
58075   ** as well as the boolean result value.
58076   */
58077   return (CURSOR_VALID!=pCur->eState);
58078 }
58079 
58080 /*
58081 ** Advance the cursor to the next entry in the database.  If
58082 ** successful then set *pRes=0.  If the cursor
58083 ** was already pointing to the last entry in the database before
58084 ** this routine was called, then set *pRes=1.
58085 **
58086 ** The main entry point is sqlite3BtreeNext().  That routine is optimized
58087 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
58088 ** to the next cell on the current page.  The (slower) btreeNext() helper
58089 ** routine is called when it is necessary to move to a different page or
58090 ** to restore the cursor.
58091 **
58092 ** The calling function will set *pRes to 0 or 1.  The initial *pRes value
58093 ** will be 1 if the cursor being stepped corresponds to an SQL index and
58094 ** if this routine could have been skipped if that SQL index had been
58095 ** a unique index.  Otherwise the caller will have set *pRes to zero.
58096 ** Zero is the common case. The btree implementation is free to use the
58097 ** initial *pRes value as a hint to improve performance, but the current
58098 ** SQLite btree implementation does not. (Note that the comdb2 btree
58099 ** implementation does use this hint, however.)
58100 */
58101 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
58102   int rc;
58103   int idx;
58104   MemPage *pPage;
58105 
58106   assert( cursorHoldsMutex(pCur) );
58107   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
58108   assert( *pRes==0 );
58109   if( pCur->eState!=CURSOR_VALID ){
58110     assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
58111     rc = restoreCursorPosition(pCur);
58112     if( rc!=SQLITE_OK ){
58113       return rc;
58114     }
58115     if( CURSOR_INVALID==pCur->eState ){
58116       *pRes = 1;
58117       return SQLITE_OK;
58118     }
58119     if( pCur->skipNext ){
58120       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
58121       pCur->eState = CURSOR_VALID;
58122       if( pCur->skipNext>0 ){
58123         pCur->skipNext = 0;
58124         return SQLITE_OK;
58125       }
58126       pCur->skipNext = 0;
58127     }
58128   }
58129 
58130   pPage = pCur->apPage[pCur->iPage];
58131   idx = ++pCur->aiIdx[pCur->iPage];
58132   assert( pPage->isInit );
58133 
58134   /* If the database file is corrupt, it is possible for the value of idx
58135   ** to be invalid here. This can only occur if a second cursor modifies
58136   ** the page while cursor pCur is holding a reference to it. Which can
58137   ** only happen if the database is corrupt in such a way as to link the
58138   ** page into more than one b-tree structure. */
58139   testcase( idx>pPage->nCell );
58140 
58141   if( idx>=pPage->nCell ){
58142     if( !pPage->leaf ){
58143       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
58144       if( rc ) return rc;
58145       return moveToLeftmost(pCur);
58146     }
58147     do{
58148       if( pCur->iPage==0 ){
58149         *pRes = 1;
58150         pCur->eState = CURSOR_INVALID;
58151         return SQLITE_OK;
58152       }
58153       moveToParent(pCur);
58154       pPage = pCur->apPage[pCur->iPage];
58155     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
58156     if( pPage->intKey ){
58157       return sqlite3BtreeNext(pCur, pRes);
58158     }else{
58159       return SQLITE_OK;
58160     }
58161   }
58162   if( pPage->leaf ){
58163     return SQLITE_OK;
58164   }else{
58165     return moveToLeftmost(pCur);
58166   }
58167 }
58168 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
58169   MemPage *pPage;
58170   assert( cursorHoldsMutex(pCur) );
58171   assert( pRes!=0 );
58172   assert( *pRes==0 || *pRes==1 );
58173   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
58174   pCur->info.nSize = 0;
58175   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
58176   *pRes = 0;
58177   if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
58178   pPage = pCur->apPage[pCur->iPage];
58179   if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
58180     pCur->aiIdx[pCur->iPage]--;
58181     return btreeNext(pCur, pRes);
58182   }
58183   if( pPage->leaf ){
58184     return SQLITE_OK;
58185   }else{
58186     return moveToLeftmost(pCur);
58187   }
58188 }
58189 
58190 /*
58191 ** Step the cursor to the back to the previous entry in the database.  If
58192 ** successful then set *pRes=0.  If the cursor
58193 ** was already pointing to the first entry in the database before
58194 ** this routine was called, then set *pRes=1.
58195 **
58196 ** The main entry point is sqlite3BtreePrevious().  That routine is optimized
58197 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
58198 ** to the previous cell on the current page.  The (slower) btreePrevious()
58199 ** helper routine is called when it is necessary to move to a different page
58200 ** or to restore the cursor.
58201 **
58202 ** The calling function will set *pRes to 0 or 1.  The initial *pRes value
58203 ** will be 1 if the cursor being stepped corresponds to an SQL index and
58204 ** if this routine could have been skipped if that SQL index had been
58205 ** a unique index.  Otherwise the caller will have set *pRes to zero.
58206 ** Zero is the common case. The btree implementation is free to use the
58207 ** initial *pRes value as a hint to improve performance, but the current
58208 ** SQLite btree implementation does not. (Note that the comdb2 btree
58209 ** implementation does use this hint, however.)
58210 */
58211 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
58212   int rc;
58213   MemPage *pPage;
58214 
58215   assert( cursorHoldsMutex(pCur) );
58216   assert( pRes!=0 );
58217   assert( *pRes==0 );
58218   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
58219   assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
58220   assert( pCur->info.nSize==0 );
58221   if( pCur->eState!=CURSOR_VALID ){
58222     rc = restoreCursorPosition(pCur);
58223     if( rc!=SQLITE_OK ){
58224       return rc;
58225     }
58226     if( CURSOR_INVALID==pCur->eState ){
58227       *pRes = 1;
58228       return SQLITE_OK;
58229     }
58230     if( pCur->skipNext ){
58231       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
58232       pCur->eState = CURSOR_VALID;
58233       if( pCur->skipNext<0 ){
58234         pCur->skipNext = 0;
58235         return SQLITE_OK;
58236       }
58237       pCur->skipNext = 0;
58238     }
58239   }
58240 
58241   pPage = pCur->apPage[pCur->iPage];
58242   assert( pPage->isInit );
58243   if( !pPage->leaf ){
58244     int idx = pCur->aiIdx[pCur->iPage];
58245     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
58246     if( rc ) return rc;
58247     rc = moveToRightmost(pCur);
58248   }else{
58249     while( pCur->aiIdx[pCur->iPage]==0 ){
58250       if( pCur->iPage==0 ){
58251         pCur->eState = CURSOR_INVALID;
58252         *pRes = 1;
58253         return SQLITE_OK;
58254       }
58255       moveToParent(pCur);
58256     }
58257     assert( pCur->info.nSize==0 );
58258     assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
58259 
58260     pCur->aiIdx[pCur->iPage]--;
58261     pPage = pCur->apPage[pCur->iPage];
58262     if( pPage->intKey && !pPage->leaf ){
58263       rc = sqlite3BtreePrevious(pCur, pRes);
58264     }else{
58265       rc = SQLITE_OK;
58266     }
58267   }
58268   return rc;
58269 }
58270 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
58271   assert( cursorHoldsMutex(pCur) );
58272   assert( pRes!=0 );
58273   assert( *pRes==0 || *pRes==1 );
58274   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
58275   *pRes = 0;
58276   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
58277   pCur->info.nSize = 0;
58278   if( pCur->eState!=CURSOR_VALID
58279    || pCur->aiIdx[pCur->iPage]==0
58280    || pCur->apPage[pCur->iPage]->leaf==0
58281   ){
58282     return btreePrevious(pCur, pRes);
58283   }
58284   pCur->aiIdx[pCur->iPage]--;
58285   return SQLITE_OK;
58286 }
58287 
58288 /*
58289 ** Allocate a new page from the database file.
58290 **
58291 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
58292 ** has already been called on the new page.)  The new page has also
58293 ** been referenced and the calling routine is responsible for calling
58294 ** sqlite3PagerUnref() on the new page when it is done.
58295 **
58296 ** SQLITE_OK is returned on success.  Any other return value indicates
58297 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
58298 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
58299 **
58300 ** If the "nearby" parameter is not 0, then an effort is made to
58301 ** locate a page close to the page number "nearby".  This can be used in an
58302 ** attempt to keep related pages close to each other in the database file,
58303 ** which in turn can make database access faster.
58304 **
58305 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
58306 ** anywhere on the free-list, then it is guaranteed to be returned.  If
58307 ** eMode is BTALLOC_LT then the page returned will be less than or equal
58308 ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
58309 ** are no restrictions on which page is returned.
58310 */
58311 static int allocateBtreePage(
58312   BtShared *pBt,         /* The btree */
58313   MemPage **ppPage,      /* Store pointer to the allocated page here */
58314   Pgno *pPgno,           /* Store the page number here */
58315   Pgno nearby,           /* Search for a page near this one */
58316   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
58317 ){
58318   MemPage *pPage1;
58319   int rc;
58320   u32 n;     /* Number of pages on the freelist */
58321   u32 k;     /* Number of leaves on the trunk of the freelist */
58322   MemPage *pTrunk = 0;
58323   MemPage *pPrevTrunk = 0;
58324   Pgno mxPage;     /* Total size of the database file */
58325 
58326   assert( sqlite3_mutex_held(pBt->mutex) );
58327   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
58328   pPage1 = pBt->pPage1;
58329   mxPage = btreePagecount(pBt);
58330   /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
58331   ** stores stores the total number of pages on the freelist. */
58332   n = get4byte(&pPage1->aData[36]);
58333   testcase( n==mxPage-1 );
58334   if( n>=mxPage ){
58335     return SQLITE_CORRUPT_BKPT;
58336   }
58337   if( n>0 ){
58338     /* There are pages on the freelist.  Reuse one of those pages. */
58339     Pgno iTrunk;
58340     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
58341 
58342     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
58343     ** shows that the page 'nearby' is somewhere on the free-list, then
58344     ** the entire-list will be searched for that page.
58345     */
58346 #ifndef SQLITE_OMIT_AUTOVACUUM
58347     if( eMode==BTALLOC_EXACT ){
58348       if( nearby<=mxPage ){
58349         u8 eType;
58350         assert( nearby>0 );
58351         assert( pBt->autoVacuum );
58352         rc = ptrmapGet(pBt, nearby, &eType, 0);
58353         if( rc ) return rc;
58354         if( eType==PTRMAP_FREEPAGE ){
58355           searchList = 1;
58356         }
58357       }
58358     }else if( eMode==BTALLOC_LE ){
58359       searchList = 1;
58360     }
58361 #endif
58362 
58363     /* Decrement the free-list count by 1. Set iTrunk to the index of the
58364     ** first free-list trunk page. iPrevTrunk is initially 1.
58365     */
58366     rc = sqlite3PagerWrite(pPage1->pDbPage);
58367     if( rc ) return rc;
58368     put4byte(&pPage1->aData[36], n-1);
58369 
58370     /* The code within this loop is run only once if the 'searchList' variable
58371     ** is not true. Otherwise, it runs once for each trunk-page on the
58372     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
58373     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
58374     */
58375     do {
58376       pPrevTrunk = pTrunk;
58377       if( pPrevTrunk ){
58378         /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
58379         ** is the page number of the next freelist trunk page in the list or
58380         ** zero if this is the last freelist trunk page. */
58381         iTrunk = get4byte(&pPrevTrunk->aData[0]);
58382       }else{
58383         /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
58384         ** stores the page number of the first page of the freelist, or zero if
58385         ** the freelist is empty. */
58386         iTrunk = get4byte(&pPage1->aData[32]);
58387       }
58388       testcase( iTrunk==mxPage );
58389       if( iTrunk>mxPage ){
58390         rc = SQLITE_CORRUPT_BKPT;
58391       }else{
58392         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
58393       }
58394       if( rc ){
58395         pTrunk = 0;
58396         goto end_allocate_page;
58397       }
58398       assert( pTrunk!=0 );
58399       assert( pTrunk->aData!=0 );
58400       /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
58401       ** is the number of leaf page pointers to follow. */
58402       k = get4byte(&pTrunk->aData[4]);
58403       if( k==0 && !searchList ){
58404         /* The trunk has no leaves and the list is not being searched.
58405         ** So extract the trunk page itself and use it as the newly
58406         ** allocated page */
58407         assert( pPrevTrunk==0 );
58408         rc = sqlite3PagerWrite(pTrunk->pDbPage);
58409         if( rc ){
58410           goto end_allocate_page;
58411         }
58412         *pPgno = iTrunk;
58413         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
58414         *ppPage = pTrunk;
58415         pTrunk = 0;
58416         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
58417       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
58418         /* Value of k is out of range.  Database corruption */
58419         rc = SQLITE_CORRUPT_BKPT;
58420         goto end_allocate_page;
58421 #ifndef SQLITE_OMIT_AUTOVACUUM
58422       }else if( searchList
58423             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
58424       ){
58425         /* The list is being searched and this trunk page is the page
58426         ** to allocate, regardless of whether it has leaves.
58427         */
58428         *pPgno = iTrunk;
58429         *ppPage = pTrunk;
58430         searchList = 0;
58431         rc = sqlite3PagerWrite(pTrunk->pDbPage);
58432         if( rc ){
58433           goto end_allocate_page;
58434         }
58435         if( k==0 ){
58436           if( !pPrevTrunk ){
58437             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
58438           }else{
58439             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
58440             if( rc!=SQLITE_OK ){
58441               goto end_allocate_page;
58442             }
58443             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
58444           }
58445         }else{
58446           /* The trunk page is required by the caller but it contains
58447           ** pointers to free-list leaves. The first leaf becomes a trunk
58448           ** page in this case.
58449           */
58450           MemPage *pNewTrunk;
58451           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
58452           if( iNewTrunk>mxPage ){
58453             rc = SQLITE_CORRUPT_BKPT;
58454             goto end_allocate_page;
58455           }
58456           testcase( iNewTrunk==mxPage );
58457           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
58458           if( rc!=SQLITE_OK ){
58459             goto end_allocate_page;
58460           }
58461           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
58462           if( rc!=SQLITE_OK ){
58463             releasePage(pNewTrunk);
58464             goto end_allocate_page;
58465           }
58466           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
58467           put4byte(&pNewTrunk->aData[4], k-1);
58468           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
58469           releasePage(pNewTrunk);
58470           if( !pPrevTrunk ){
58471             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
58472             put4byte(&pPage1->aData[32], iNewTrunk);
58473           }else{
58474             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
58475             if( rc ){
58476               goto end_allocate_page;
58477             }
58478             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
58479           }
58480         }
58481         pTrunk = 0;
58482         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
58483 #endif
58484       }else if( k>0 ){
58485         /* Extract a leaf from the trunk */
58486         u32 closest;
58487         Pgno iPage;
58488         unsigned char *aData = pTrunk->aData;
58489         if( nearby>0 ){
58490           u32 i;
58491           closest = 0;
58492           if( eMode==BTALLOC_LE ){
58493             for(i=0; i<k; i++){
58494               iPage = get4byte(&aData[8+i*4]);
58495               if( iPage<=nearby ){
58496                 closest = i;
58497                 break;
58498               }
58499             }
58500           }else{
58501             int dist;
58502             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
58503             for(i=1; i<k; i++){
58504               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
58505               if( d2<dist ){
58506                 closest = i;
58507                 dist = d2;
58508               }
58509             }
58510           }
58511         }else{
58512           closest = 0;
58513         }
58514 
58515         iPage = get4byte(&aData[8+closest*4]);
58516         testcase( iPage==mxPage );
58517         if( iPage>mxPage ){
58518           rc = SQLITE_CORRUPT_BKPT;
58519           goto end_allocate_page;
58520         }
58521         testcase( iPage==mxPage );
58522         if( !searchList
58523          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
58524         ){
58525           int noContent;
58526           *pPgno = iPage;
58527           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
58528                  ": %d more free pages\n",
58529                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
58530           rc = sqlite3PagerWrite(pTrunk->pDbPage);
58531           if( rc ) goto end_allocate_page;
58532           if( closest<k-1 ){
58533             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
58534           }
58535           put4byte(&aData[4], k-1);
58536           noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
58537           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
58538           if( rc==SQLITE_OK ){
58539             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
58540             if( rc!=SQLITE_OK ){
58541               releasePage(*ppPage);
58542             }
58543           }
58544           searchList = 0;
58545         }
58546       }
58547       releasePage(pPrevTrunk);
58548       pPrevTrunk = 0;
58549     }while( searchList );
58550   }else{
58551     /* There are no pages on the freelist, so append a new page to the
58552     ** database image.
58553     **
58554     ** Normally, new pages allocated by this block can be requested from the
58555     ** pager layer with the 'no-content' flag set. This prevents the pager
58556     ** from trying to read the pages content from disk. However, if the
58557     ** current transaction has already run one or more incremental-vacuum
58558     ** steps, then the page we are about to allocate may contain content
58559     ** that is required in the event of a rollback. In this case, do
58560     ** not set the no-content flag. This causes the pager to load and journal
58561     ** the current page content before overwriting it.
58562     **
58563     ** Note that the pager will not actually attempt to load or journal
58564     ** content for any page that really does lie past the end of the database
58565     ** file on disk. So the effects of disabling the no-content optimization
58566     ** here are confined to those pages that lie between the end of the
58567     ** database image and the end of the database file.
58568     */
58569     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
58570 
58571     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
58572     if( rc ) return rc;
58573     pBt->nPage++;
58574     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
58575 
58576 #ifndef SQLITE_OMIT_AUTOVACUUM
58577     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
58578       /* If *pPgno refers to a pointer-map page, allocate two new pages
58579       ** at the end of the file instead of one. The first allocated page
58580       ** becomes a new pointer-map page, the second is used by the caller.
58581       */
58582       MemPage *pPg = 0;
58583       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
58584       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
58585       rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
58586       if( rc==SQLITE_OK ){
58587         rc = sqlite3PagerWrite(pPg->pDbPage);
58588         releasePage(pPg);
58589       }
58590       if( rc ) return rc;
58591       pBt->nPage++;
58592       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
58593     }
58594 #endif
58595     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
58596     *pPgno = pBt->nPage;
58597 
58598     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
58599     rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
58600     if( rc ) return rc;
58601     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
58602     if( rc!=SQLITE_OK ){
58603       releasePage(*ppPage);
58604     }
58605     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
58606   }
58607 
58608   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
58609 
58610 end_allocate_page:
58611   releasePage(pTrunk);
58612   releasePage(pPrevTrunk);
58613   if( rc==SQLITE_OK ){
58614     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
58615       releasePage(*ppPage);
58616       *ppPage = 0;
58617       return SQLITE_CORRUPT_BKPT;
58618     }
58619     (*ppPage)->isInit = 0;
58620   }else{
58621     *ppPage = 0;
58622   }
58623   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
58624   return rc;
58625 }
58626 
58627 /*
58628 ** This function is used to add page iPage to the database file free-list.
58629 ** It is assumed that the page is not already a part of the free-list.
58630 **
58631 ** The value passed as the second argument to this function is optional.
58632 ** If the caller happens to have a pointer to the MemPage object
58633 ** corresponding to page iPage handy, it may pass it as the second value.
58634 ** Otherwise, it may pass NULL.
58635 **
58636 ** If a pointer to a MemPage object is passed as the second argument,
58637 ** its reference count is not altered by this function.
58638 */
58639 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
58640   MemPage *pTrunk = 0;                /* Free-list trunk page */
58641   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
58642   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
58643   MemPage *pPage;                     /* Page being freed. May be NULL. */
58644   int rc;                             /* Return Code */
58645   int nFree;                          /* Initial number of pages on free-list */
58646 
58647   assert( sqlite3_mutex_held(pBt->mutex) );
58648   assert( iPage>1 );
58649   assert( !pMemPage || pMemPage->pgno==iPage );
58650 
58651   if( pMemPage ){
58652     pPage = pMemPage;
58653     sqlite3PagerRef(pPage->pDbPage);
58654   }else{
58655     pPage = btreePageLookup(pBt, iPage);
58656   }
58657 
58658   /* Increment the free page count on pPage1 */
58659   rc = sqlite3PagerWrite(pPage1->pDbPage);
58660   if( rc ) goto freepage_out;
58661   nFree = get4byte(&pPage1->aData[36]);
58662   put4byte(&pPage1->aData[36], nFree+1);
58663 
58664   if( pBt->btsFlags & BTS_SECURE_DELETE ){
58665     /* If the secure_delete option is enabled, then
58666     ** always fully overwrite deleted information with zeros.
58667     */
58668     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
58669      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
58670     ){
58671       goto freepage_out;
58672     }
58673     memset(pPage->aData, 0, pPage->pBt->pageSize);
58674   }
58675 
58676   /* If the database supports auto-vacuum, write an entry in the pointer-map
58677   ** to indicate that the page is free.
58678   */
58679   if( ISAUTOVACUUM ){
58680     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
58681     if( rc ) goto freepage_out;
58682   }
58683 
58684   /* Now manipulate the actual database free-list structure. There are two
58685   ** possibilities. If the free-list is currently empty, or if the first
58686   ** trunk page in the free-list is full, then this page will become a
58687   ** new free-list trunk page. Otherwise, it will become a leaf of the
58688   ** first trunk page in the current free-list. This block tests if it
58689   ** is possible to add the page as a new free-list leaf.
58690   */
58691   if( nFree!=0 ){
58692     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
58693 
58694     iTrunk = get4byte(&pPage1->aData[32]);
58695     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
58696     if( rc!=SQLITE_OK ){
58697       goto freepage_out;
58698     }
58699 
58700     nLeaf = get4byte(&pTrunk->aData[4]);
58701     assert( pBt->usableSize>32 );
58702     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
58703       rc = SQLITE_CORRUPT_BKPT;
58704       goto freepage_out;
58705     }
58706     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
58707       /* In this case there is room on the trunk page to insert the page
58708       ** being freed as a new leaf.
58709       **
58710       ** Note that the trunk page is not really full until it contains
58711       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
58712       ** coded.  But due to a coding error in versions of SQLite prior to
58713       ** 3.6.0, databases with freelist trunk pages holding more than
58714       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
58715       ** to maintain backwards compatibility with older versions of SQLite,
58716       ** we will continue to restrict the number of entries to usableSize/4 - 8
58717       ** for now.  At some point in the future (once everyone has upgraded
58718       ** to 3.6.0 or later) we should consider fixing the conditional above
58719       ** to read "usableSize/4-2" instead of "usableSize/4-8".
58720       **
58721       ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
58722       ** avoid using the last six entries in the freelist trunk page array in
58723       ** order that database files created by newer versions of SQLite can be
58724       ** read by older versions of SQLite.
58725       */
58726       rc = sqlite3PagerWrite(pTrunk->pDbPage);
58727       if( rc==SQLITE_OK ){
58728         put4byte(&pTrunk->aData[4], nLeaf+1);
58729         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
58730         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
58731           sqlite3PagerDontWrite(pPage->pDbPage);
58732         }
58733         rc = btreeSetHasContent(pBt, iPage);
58734       }
58735       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
58736       goto freepage_out;
58737     }
58738   }
58739 
58740   /* If control flows to this point, then it was not possible to add the
58741   ** the page being freed as a leaf page of the first trunk in the free-list.
58742   ** Possibly because the free-list is empty, or possibly because the
58743   ** first trunk in the free-list is full. Either way, the page being freed
58744   ** will become the new first trunk page in the free-list.
58745   */
58746   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
58747     goto freepage_out;
58748   }
58749   rc = sqlite3PagerWrite(pPage->pDbPage);
58750   if( rc!=SQLITE_OK ){
58751     goto freepage_out;
58752   }
58753   put4byte(pPage->aData, iTrunk);
58754   put4byte(&pPage->aData[4], 0);
58755   put4byte(&pPage1->aData[32], iPage);
58756   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
58757 
58758 freepage_out:
58759   if( pPage ){
58760     pPage->isInit = 0;
58761   }
58762   releasePage(pPage);
58763   releasePage(pTrunk);
58764   return rc;
58765 }
58766 static void freePage(MemPage *pPage, int *pRC){
58767   if( (*pRC)==SQLITE_OK ){
58768     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
58769   }
58770 }
58771 
58772 /*
58773 ** Free any overflow pages associated with the given Cell.  Write the
58774 ** local Cell size (the number of bytes on the original page, omitting
58775 ** overflow) into *pnSize.
58776 */
58777 static int clearCell(
58778   MemPage *pPage,          /* The page that contains the Cell */
58779   unsigned char *pCell,    /* First byte of the Cell */
58780   u16 *pnSize              /* Write the size of the Cell here */
58781 ){
58782   BtShared *pBt = pPage->pBt;
58783   CellInfo info;
58784   Pgno ovflPgno;
58785   int rc;
58786   int nOvfl;
58787   u32 ovflPageSize;
58788 
58789   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58790   btreeParseCellPtr(pPage, pCell, &info);
58791   *pnSize = info.nSize;
58792   if( info.iOverflow==0 ){
58793     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
58794   }
58795   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
58796     return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
58797   }
58798   ovflPgno = get4byte(&pCell[info.iOverflow]);
58799   assert( pBt->usableSize > 4 );
58800   ovflPageSize = pBt->usableSize - 4;
58801   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
58802   assert( ovflPgno==0 || nOvfl>0 );
58803   while( nOvfl-- ){
58804     Pgno iNext = 0;
58805     MemPage *pOvfl = 0;
58806     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
58807       /* 0 is not a legal page number and page 1 cannot be an
58808       ** overflow page. Therefore if ovflPgno<2 or past the end of the
58809       ** file the database must be corrupt. */
58810       return SQLITE_CORRUPT_BKPT;
58811     }
58812     if( nOvfl ){
58813       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
58814       if( rc ) return rc;
58815     }
58816 
58817     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
58818      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
58819     ){
58820       /* There is no reason any cursor should have an outstanding reference
58821       ** to an overflow page belonging to a cell that is being deleted/updated.
58822       ** So if there exists more than one reference to this page, then it
58823       ** must not really be an overflow page and the database must be corrupt.
58824       ** It is helpful to detect this before calling freePage2(), as
58825       ** freePage2() may zero the page contents if secure-delete mode is
58826       ** enabled. If this 'overflow' page happens to be a page that the
58827       ** caller is iterating through or using in some other way, this
58828       ** can be problematic.
58829       */
58830       rc = SQLITE_CORRUPT_BKPT;
58831     }else{
58832       rc = freePage2(pBt, pOvfl, ovflPgno);
58833     }
58834 
58835     if( pOvfl ){
58836       sqlite3PagerUnref(pOvfl->pDbPage);
58837     }
58838     if( rc ) return rc;
58839     ovflPgno = iNext;
58840   }
58841   return SQLITE_OK;
58842 }
58843 
58844 /*
58845 ** Create the byte sequence used to represent a cell on page pPage
58846 ** and write that byte sequence into pCell[].  Overflow pages are
58847 ** allocated and filled in as necessary.  The calling procedure
58848 ** is responsible for making sure sufficient space has been allocated
58849 ** for pCell[].
58850 **
58851 ** Note that pCell does not necessary need to point to the pPage->aData
58852 ** area.  pCell might point to some temporary storage.  The cell will
58853 ** be constructed in this temporary area then copied into pPage->aData
58854 ** later.
58855 */
58856 static int fillInCell(
58857   MemPage *pPage,                /* The page that contains the cell */
58858   unsigned char *pCell,          /* Complete text of the cell */
58859   const void *pKey, i64 nKey,    /* The key */
58860   const void *pData,int nData,   /* The data */
58861   int nZero,                     /* Extra zero bytes to append to pData */
58862   int *pnSize                    /* Write cell size here */
58863 ){
58864   int nPayload;
58865   const u8 *pSrc;
58866   int nSrc, n, rc;
58867   int spaceLeft;
58868   MemPage *pOvfl = 0;
58869   MemPage *pToRelease = 0;
58870   unsigned char *pPrior;
58871   unsigned char *pPayload;
58872   BtShared *pBt = pPage->pBt;
58873   Pgno pgnoOvfl = 0;
58874   int nHeader;
58875 
58876   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58877 
58878   /* pPage is not necessarily writeable since pCell might be auxiliary
58879   ** buffer space that is separate from the pPage buffer area */
58880   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
58881             || sqlite3PagerIswriteable(pPage->pDbPage) );
58882 
58883   /* Fill in the header. */
58884   nHeader = pPage->childPtrSize;
58885   nPayload = nData + nZero;
58886   if( pPage->intKeyLeaf ){
58887     nHeader += putVarint32(&pCell[nHeader], nPayload);
58888   }else{
58889     assert( nData==0 );
58890     assert( nZero==0 );
58891   }
58892   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
58893 
58894   /* Fill in the payload size */
58895   if( pPage->intKey ){
58896     pSrc = pData;
58897     nSrc = nData;
58898     nData = 0;
58899   }else{
58900     if( NEVER(nKey>0x7fffffff || pKey==0) ){
58901       return SQLITE_CORRUPT_BKPT;
58902     }
58903     nPayload = (int)nKey;
58904     pSrc = pKey;
58905     nSrc = (int)nKey;
58906   }
58907   if( nPayload<=pPage->maxLocal ){
58908     n = nHeader + nPayload;
58909     testcase( n==3 );
58910     testcase( n==4 );
58911     if( n<4 ) n = 4;
58912     *pnSize = n;
58913     spaceLeft = nPayload;
58914     pPrior = pCell;
58915   }else{
58916     int mn = pPage->minLocal;
58917     n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
58918     testcase( n==pPage->maxLocal );
58919     testcase( n==pPage->maxLocal+1 );
58920     if( n > pPage->maxLocal ) n = mn;
58921     spaceLeft = n;
58922     *pnSize = n + nHeader + 4;
58923     pPrior = &pCell[nHeader+n];
58924   }
58925   pPayload = &pCell[nHeader];
58926 
58927   /* At this point variables should be set as follows:
58928   **
58929   **   nPayload           Total payload size in bytes
58930   **   pPayload           Begin writing payload here
58931   **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
58932   **                      that means content must spill into overflow pages.
58933   **   *pnSize            Size of the local cell (not counting overflow pages)
58934   **   pPrior             Where to write the pgno of the first overflow page
58935   **
58936   ** Use a call to btreeParseCellPtr() to verify that the values above
58937   ** were computed correctly.
58938   */
58939 #if SQLITE_DEBUG
58940   {
58941     CellInfo info;
58942     btreeParseCellPtr(pPage, pCell, &info);
58943     assert( nHeader=(int)(info.pPayload - pCell) );
58944     assert( info.nKey==nKey );
58945     assert( *pnSize == info.nSize );
58946     assert( spaceLeft == info.nLocal );
58947     assert( pPrior == &pCell[info.iOverflow] );
58948   }
58949 #endif
58950 
58951   /* Write the payload into the local Cell and any extra into overflow pages */
58952   while( nPayload>0 ){
58953     if( spaceLeft==0 ){
58954 #ifndef SQLITE_OMIT_AUTOVACUUM
58955       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
58956       if( pBt->autoVacuum ){
58957         do{
58958           pgnoOvfl++;
58959         } while(
58960           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
58961         );
58962       }
58963 #endif
58964       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
58965 #ifndef SQLITE_OMIT_AUTOVACUUM
58966       /* If the database supports auto-vacuum, and the second or subsequent
58967       ** overflow page is being allocated, add an entry to the pointer-map
58968       ** for that page now.
58969       **
58970       ** If this is the first overflow page, then write a partial entry
58971       ** to the pointer-map. If we write nothing to this pointer-map slot,
58972       ** then the optimistic overflow chain processing in clearCell()
58973       ** may misinterpret the uninitialized values and delete the
58974       ** wrong pages from the database.
58975       */
58976       if( pBt->autoVacuum && rc==SQLITE_OK ){
58977         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
58978         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
58979         if( rc ){
58980           releasePage(pOvfl);
58981         }
58982       }
58983 #endif
58984       if( rc ){
58985         releasePage(pToRelease);
58986         return rc;
58987       }
58988 
58989       /* If pToRelease is not zero than pPrior points into the data area
58990       ** of pToRelease.  Make sure pToRelease is still writeable. */
58991       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
58992 
58993       /* If pPrior is part of the data area of pPage, then make sure pPage
58994       ** is still writeable */
58995       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
58996             || sqlite3PagerIswriteable(pPage->pDbPage) );
58997 
58998       put4byte(pPrior, pgnoOvfl);
58999       releasePage(pToRelease);
59000       pToRelease = pOvfl;
59001       pPrior = pOvfl->aData;
59002       put4byte(pPrior, 0);
59003       pPayload = &pOvfl->aData[4];
59004       spaceLeft = pBt->usableSize - 4;
59005     }
59006     n = nPayload;
59007     if( n>spaceLeft ) n = spaceLeft;
59008 
59009     /* If pToRelease is not zero than pPayload points into the data area
59010     ** of pToRelease.  Make sure pToRelease is still writeable. */
59011     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
59012 
59013     /* If pPayload is part of the data area of pPage, then make sure pPage
59014     ** is still writeable */
59015     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
59016             || sqlite3PagerIswriteable(pPage->pDbPage) );
59017 
59018     if( nSrc>0 ){
59019       if( n>nSrc ) n = nSrc;
59020       assert( pSrc );
59021       memcpy(pPayload, pSrc, n);
59022     }else{
59023       memset(pPayload, 0, n);
59024     }
59025     nPayload -= n;
59026     pPayload += n;
59027     pSrc += n;
59028     nSrc -= n;
59029     spaceLeft -= n;
59030     if( nSrc==0 ){
59031       nSrc = nData;
59032       pSrc = pData;
59033     }
59034   }
59035   releasePage(pToRelease);
59036   return SQLITE_OK;
59037 }
59038 
59039 /*
59040 ** Remove the i-th cell from pPage.  This routine effects pPage only.
59041 ** The cell content is not freed or deallocated.  It is assumed that
59042 ** the cell content has been copied someplace else.  This routine just
59043 ** removes the reference to the cell from pPage.
59044 **
59045 ** "sz" must be the number of bytes in the cell.
59046 */
59047 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
59048   u32 pc;         /* Offset to cell content of cell being deleted */
59049   u8 *data;       /* pPage->aData */
59050   u8 *ptr;        /* Used to move bytes around within data[] */
59051   int rc;         /* The return code */
59052   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
59053 
59054   if( *pRC ) return;
59055 
59056   assert( idx>=0 && idx<pPage->nCell );
59057   assert( sz==cellSize(pPage, idx) );
59058   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59059   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59060   data = pPage->aData;
59061   ptr = &pPage->aCellIdx[2*idx];
59062   pc = get2byte(ptr);
59063   hdr = pPage->hdrOffset;
59064   testcase( pc==get2byte(&data[hdr+5]) );
59065   testcase( pc+sz==pPage->pBt->usableSize );
59066   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
59067     *pRC = SQLITE_CORRUPT_BKPT;
59068     return;
59069   }
59070   rc = freeSpace(pPage, pc, sz);
59071   if( rc ){
59072     *pRC = rc;
59073     return;
59074   }
59075   pPage->nCell--;
59076   if( pPage->nCell==0 ){
59077     memset(&data[hdr+1], 0, 4);
59078     data[hdr+7] = 0;
59079     put2byte(&data[hdr+5], pPage->pBt->usableSize);
59080     pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
59081                        - pPage->childPtrSize - 8;
59082   }else{
59083     memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
59084     put2byte(&data[hdr+3], pPage->nCell);
59085     pPage->nFree += 2;
59086   }
59087 }
59088 
59089 /*
59090 ** Insert a new cell on pPage at cell index "i".  pCell points to the
59091 ** content of the cell.
59092 **
59093 ** If the cell content will fit on the page, then put it there.  If it
59094 ** will not fit, then make a copy of the cell content into pTemp if
59095 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
59096 ** in pPage->apOvfl[] and make it point to the cell content (either
59097 ** in pTemp or the original pCell) and also record its index.
59098 ** Allocating a new entry in pPage->aCell[] implies that
59099 ** pPage->nOverflow is incremented.
59100 */
59101 static void insertCell(
59102   MemPage *pPage,   /* Page into which we are copying */
59103   int i,            /* New cell becomes the i-th cell of the page */
59104   u8 *pCell,        /* Content of the new cell */
59105   int sz,           /* Bytes of content in pCell */
59106   u8 *pTemp,        /* Temp storage space for pCell, if needed */
59107   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
59108   int *pRC          /* Read and write return code from here */
59109 ){
59110   int idx = 0;      /* Where to write new cell content in data[] */
59111   int j;            /* Loop counter */
59112   int end;          /* First byte past the last cell pointer in data[] */
59113   int ins;          /* Index in data[] where new cell pointer is inserted */
59114   int cellOffset;   /* Address of first cell pointer in data[] */
59115   u8 *data;         /* The content of the whole page */
59116 
59117   if( *pRC ) return;
59118 
59119   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
59120   assert( MX_CELL(pPage->pBt)<=10921 );
59121   assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
59122   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
59123   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
59124   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59125   /* The cell should normally be sized correctly.  However, when moving a
59126   ** malformed cell from a leaf page to an interior page, if the cell size
59127   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
59128   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
59129   ** the term after the || in the following assert(). */
59130   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
59131   if( pPage->nOverflow || sz+2>pPage->nFree ){
59132     if( pTemp ){
59133       memcpy(pTemp, pCell, sz);
59134       pCell = pTemp;
59135     }
59136     if( iChild ){
59137       put4byte(pCell, iChild);
59138     }
59139     j = pPage->nOverflow++;
59140     assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
59141     pPage->apOvfl[j] = pCell;
59142     pPage->aiOvfl[j] = (u16)i;
59143   }else{
59144     int rc = sqlite3PagerWrite(pPage->pDbPage);
59145     if( rc!=SQLITE_OK ){
59146       *pRC = rc;
59147       return;
59148     }
59149     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59150     data = pPage->aData;
59151     cellOffset = pPage->cellOffset;
59152     end = cellOffset + 2*pPage->nCell;
59153     ins = cellOffset + 2*i;
59154     rc = allocateSpace(pPage, sz, &idx);
59155     if( rc ){ *pRC = rc; return; }
59156     /* The allocateSpace() routine guarantees the following two properties
59157     ** if it returns success */
59158     assert( idx >= end+2 );
59159     assert( idx+sz <= (int)pPage->pBt->usableSize );
59160     pPage->nCell++;
59161     pPage->nFree -= (u16)(2 + sz);
59162     memcpy(&data[idx], pCell, sz);
59163     if( iChild ){
59164       put4byte(&data[idx], iChild);
59165     }
59166     memmove(&data[ins+2], &data[ins], end-ins);
59167     put2byte(&data[ins], idx);
59168     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
59169 #ifndef SQLITE_OMIT_AUTOVACUUM
59170     if( pPage->pBt->autoVacuum ){
59171       /* The cell may contain a pointer to an overflow page. If so, write
59172       ** the entry for the overflow page into the pointer map.
59173       */
59174       ptrmapPutOvflPtr(pPage, pCell, pRC);
59175     }
59176 #endif
59177   }
59178 }
59179 
59180 /*
59181 ** Array apCell[] contains pointers to nCell b-tree page cells. The
59182 ** szCell[] array contains the size in bytes of each cell. This function
59183 ** replaces the current contents of page pPg with the contents of the cell
59184 ** array.
59185 **
59186 ** Some of the cells in apCell[] may currently be stored in pPg. This
59187 ** function works around problems caused by this by making a copy of any
59188 ** such cells before overwriting the page data.
59189 **
59190 ** The MemPage.nFree field is invalidated by this function. It is the
59191 ** responsibility of the caller to set it correctly.
59192 */
59193 static void rebuildPage(
59194   MemPage *pPg,                   /* Edit this page */
59195   int nCell,                      /* Final number of cells on page */
59196   u8 **apCell,                    /* Array of cells */
59197   u16 *szCell                     /* Array of cell sizes */
59198 ){
59199   const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
59200   u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
59201   const int usableSize = pPg->pBt->usableSize;
59202   u8 * const pEnd = &aData[usableSize];
59203   int i;
59204   u8 *pCellptr = pPg->aCellIdx;
59205   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
59206   u8 *pData;
59207 
59208   i = get2byte(&aData[hdr+5]);
59209   memcpy(&pTmp[i], &aData[i], usableSize - i);
59210 
59211   pData = pEnd;
59212   for(i=0; i<nCell; i++){
59213     u8 *pCell = apCell[i];
59214     if( pCell>aData && pCell<pEnd ){
59215       pCell = &pTmp[pCell - aData];
59216     }
59217     pData -= szCell[i];
59218     memcpy(pData, pCell, szCell[i]);
59219     put2byte(pCellptr, (pData - aData));
59220     pCellptr += 2;
59221     assert( szCell[i]==cellSizePtr(pPg, pCell) );
59222   }
59223 
59224   /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
59225   pPg->nCell = nCell;
59226   pPg->nOverflow = 0;
59227 
59228   put2byte(&aData[hdr+1], 0);
59229   put2byte(&aData[hdr+3], pPg->nCell);
59230   put2byte(&aData[hdr+5], pData - aData);
59231   aData[hdr+7] = 0x00;
59232 }
59233 
59234 /*
59235 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
59236 ** contains the size in bytes of each such cell. This function attempts to
59237 ** add the cells stored in the array to page pPg. If it cannot (because
59238 ** the page needs to be defragmented before the cells will fit), non-zero
59239 ** is returned. Otherwise, if the cells are added successfully, zero is
59240 ** returned.
59241 **
59242 ** Argument pCellptr points to the first entry in the cell-pointer array
59243 ** (part of page pPg) to populate. After cell apCell[0] is written to the
59244 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
59245 ** cell in the array. It is the responsibility of the caller to ensure
59246 ** that it is safe to overwrite this part of the cell-pointer array.
59247 **
59248 ** When this function is called, *ppData points to the start of the
59249 ** content area on page pPg. If the size of the content area is extended,
59250 ** *ppData is updated to point to the new start of the content area
59251 ** before returning.
59252 **
59253 ** Finally, argument pBegin points to the byte immediately following the
59254 ** end of the space required by this page for the cell-pointer area (for
59255 ** all cells - not just those inserted by the current call). If the content
59256 ** area must be extended to before this point in order to accomodate all
59257 ** cells in apCell[], then the cells do not fit and non-zero is returned.
59258 */
59259 static int pageInsertArray(
59260   MemPage *pPg,                   /* Page to add cells to */
59261   u8 *pBegin,                     /* End of cell-pointer array */
59262   u8 **ppData,                    /* IN/OUT: Page content -area pointer */
59263   u8 *pCellptr,                   /* Pointer to cell-pointer area */
59264   int nCell,                      /* Number of cells to add to pPg */
59265   u8 **apCell,                    /* Array of cells */
59266   u16 *szCell                     /* Array of cell sizes */
59267 ){
59268   int i;
59269   u8 *aData = pPg->aData;
59270   u8 *pData = *ppData;
59271   const int bFreelist = aData[1] || aData[2];
59272   assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
59273   for(i=0; i<nCell; i++){
59274     int sz = szCell[i];
59275     int rc;
59276     u8 *pSlot;
59277     if( bFreelist==0 || (pSlot = pageFindSlot(pPg, sz, &rc, 0))==0 ){
59278       pData -= sz;
59279       if( pData<pBegin ) return 1;
59280       pSlot = pData;
59281     }
59282     memcpy(pSlot, apCell[i], sz);
59283     put2byte(pCellptr, (pSlot - aData));
59284     pCellptr += 2;
59285   }
59286   *ppData = pData;
59287   return 0;
59288 }
59289 
59290 /*
59291 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
59292 ** contains the size in bytes of each such cell. This function adds the
59293 ** space associated with each cell in the array that is currently stored
59294 ** within the body of pPg to the pPg free-list. The cell-pointers and other
59295 ** fields of the page are not updated.
59296 **
59297 ** This function returns the total number of cells added to the free-list.
59298 */
59299 static int pageFreeArray(
59300   MemPage *pPg,                   /* Page to edit */
59301   int nCell,                      /* Cells to delete */
59302   u8 **apCell,                    /* Array of cells */
59303   u16 *szCell                     /* Array of cell sizes */
59304 ){
59305   u8 * const aData = pPg->aData;
59306   u8 * const pEnd = &aData[pPg->pBt->usableSize];
59307   u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
59308   int nRet = 0;
59309   int i;
59310   u8 *pFree = 0;
59311   int szFree = 0;
59312 
59313   for(i=0; i<nCell; i++){
59314     u8 *pCell = apCell[i];
59315     if( pCell>=pStart && pCell<pEnd ){
59316       int sz = szCell[i];
59317       if( pFree!=(pCell + sz) ){
59318         if( pFree ){
59319           assert( pFree>aData && (pFree - aData)<65536 );
59320           freeSpace(pPg, (u16)(pFree - aData), szFree);
59321         }
59322         pFree = pCell;
59323         szFree = sz;
59324         if( pFree+sz>pEnd ) return 0;
59325       }else{
59326         pFree = pCell;
59327         szFree += sz;
59328       }
59329       nRet++;
59330     }
59331   }
59332   if( pFree ){
59333     assert( pFree>aData && (pFree - aData)<65536 );
59334     freeSpace(pPg, (u16)(pFree - aData), szFree);
59335   }
59336   return nRet;
59337 }
59338 
59339 /*
59340 ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
59341 ** pages being balanced.  The current page, pPg, has pPg->nCell cells starting
59342 ** with apCell[iOld].  After balancing, this page should hold nNew cells
59343 ** starting at apCell[iNew].
59344 **
59345 ** This routine makes the necessary adjustments to pPg so that it contains
59346 ** the correct cells after being balanced.
59347 **
59348 ** The pPg->nFree field is invalid when this function returns. It is the
59349 ** responsibility of the caller to set it correctly.
59350 */
59351 static void editPage(
59352   MemPage *pPg,                   /* Edit this page */
59353   int iOld,                       /* Index of first cell currently on page */
59354   int iNew,                       /* Index of new first cell on page */
59355   int nNew,                       /* Final number of cells on page */
59356   u8 **apCell,                    /* Array of cells */
59357   u16 *szCell                     /* Array of cell sizes */
59358 ){
59359   u8 * const aData = pPg->aData;
59360   const int hdr = pPg->hdrOffset;
59361   u8 *pBegin = &pPg->aCellIdx[nNew * 2];
59362   int nCell = pPg->nCell;       /* Cells stored on pPg */
59363   u8 *pData;
59364   u8 *pCellptr;
59365   int i;
59366   int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
59367   int iNewEnd = iNew + nNew;
59368 
59369 #ifdef SQLITE_DEBUG
59370   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
59371   memcpy(pTmp, aData, pPg->pBt->usableSize);
59372 #endif
59373 
59374   /* Remove cells from the start and end of the page */
59375   if( iOld<iNew ){
59376     int nShift = pageFreeArray(
59377         pPg, iNew-iOld, &apCell[iOld], &szCell[iOld]
59378     );
59379     memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
59380     nCell -= nShift;
59381   }
59382   if( iNewEnd < iOldEnd ){
59383     nCell -= pageFreeArray(
59384         pPg, iOldEnd-iNewEnd, &apCell[iNewEnd], &szCell[iNewEnd]
59385     );
59386   }
59387 
59388   pData = &aData[get2byteNotZero(&aData[hdr+5])];
59389   if( pData<pBegin ) goto editpage_fail;
59390 
59391   /* Add cells to the start of the page */
59392   if( iNew<iOld ){
59393     int nAdd = MIN(nNew,iOld-iNew);
59394     assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
59395     pCellptr = pPg->aCellIdx;
59396     memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
59397     if( pageInsertArray(
59398           pPg, pBegin, &pData, pCellptr,
59399           nAdd, &apCell[iNew], &szCell[iNew]
59400     ) ) goto editpage_fail;
59401     nCell += nAdd;
59402   }
59403 
59404   /* Add any overflow cells */
59405   for(i=0; i<pPg->nOverflow; i++){
59406     int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
59407     if( iCell>=0 && iCell<nNew ){
59408       pCellptr = &pPg->aCellIdx[iCell * 2];
59409       memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
59410       nCell++;
59411       if( pageInsertArray(
59412             pPg, pBegin, &pData, pCellptr,
59413             1, &apCell[iCell + iNew], &szCell[iCell + iNew]
59414       ) ) goto editpage_fail;
59415     }
59416   }
59417 
59418   /* Append cells to the end of the page */
59419   pCellptr = &pPg->aCellIdx[nCell*2];
59420   if( pageInsertArray(
59421         pPg, pBegin, &pData, pCellptr,
59422         nNew-nCell, &apCell[iNew+nCell], &szCell[iNew+nCell]
59423   ) ) goto editpage_fail;
59424 
59425   pPg->nCell = nNew;
59426   pPg->nOverflow = 0;
59427 
59428   put2byte(&aData[hdr+3], pPg->nCell);
59429   put2byte(&aData[hdr+5], pData - aData);
59430 
59431 #ifdef SQLITE_DEBUG
59432   for(i=0; i<nNew && !CORRUPT_DB; i++){
59433     u8 *pCell = apCell[i+iNew];
59434     int iOff = get2byte(&pPg->aCellIdx[i*2]);
59435     if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){
59436       pCell = &pTmp[pCell - aData];
59437     }
59438     assert( 0==memcmp(pCell, &aData[iOff], szCell[i+iNew]) );
59439   }
59440 #endif
59441 
59442   return;
59443  editpage_fail:
59444   /* Unable to edit this page. Rebuild it from scratch instead. */
59445   rebuildPage(pPg, nNew, &apCell[iNew], &szCell[iNew]);
59446 }
59447 
59448 /*
59449 ** The following parameters determine how many adjacent pages get involved
59450 ** in a balancing operation.  NN is the number of neighbors on either side
59451 ** of the page that participate in the balancing operation.  NB is the
59452 ** total number of pages that participate, including the target page and
59453 ** NN neighbors on either side.
59454 **
59455 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
59456 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
59457 ** in exchange for a larger degradation in INSERT and UPDATE performance.
59458 ** The value of NN appears to give the best results overall.
59459 */
59460 #define NN 1             /* Number of neighbors on either side of pPage */
59461 #define NB (NN*2+1)      /* Total pages involved in the balance */
59462 
59463 
59464 #ifndef SQLITE_OMIT_QUICKBALANCE
59465 /*
59466 ** This version of balance() handles the common special case where
59467 ** a new entry is being inserted on the extreme right-end of the
59468 ** tree, in other words, when the new entry will become the largest
59469 ** entry in the tree.
59470 **
59471 ** Instead of trying to balance the 3 right-most leaf pages, just add
59472 ** a new page to the right-hand side and put the one new entry in
59473 ** that page.  This leaves the right side of the tree somewhat
59474 ** unbalanced.  But odds are that we will be inserting new entries
59475 ** at the end soon afterwards so the nearly empty page will quickly
59476 ** fill up.  On average.
59477 **
59478 ** pPage is the leaf page which is the right-most page in the tree.
59479 ** pParent is its parent.  pPage must have a single overflow entry
59480 ** which is also the right-most entry on the page.
59481 **
59482 ** The pSpace buffer is used to store a temporary copy of the divider
59483 ** cell that will be inserted into pParent. Such a cell consists of a 4
59484 ** byte page number followed by a variable length integer. In other
59485 ** words, at most 13 bytes. Hence the pSpace buffer must be at
59486 ** least 13 bytes in size.
59487 */
59488 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
59489   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
59490   MemPage *pNew;                       /* Newly allocated page */
59491   int rc;                              /* Return Code */
59492   Pgno pgnoNew;                        /* Page number of pNew */
59493 
59494   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59495   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
59496   assert( pPage->nOverflow==1 );
59497 
59498   /* This error condition is now caught prior to reaching this function */
59499   if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
59500 
59501   /* Allocate a new page. This page will become the right-sibling of
59502   ** pPage. Make the parent page writable, so that the new divider cell
59503   ** may be inserted. If both these operations are successful, proceed.
59504   */
59505   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
59506 
59507   if( rc==SQLITE_OK ){
59508 
59509     u8 *pOut = &pSpace[4];
59510     u8 *pCell = pPage->apOvfl[0];
59511     u16 szCell = cellSizePtr(pPage, pCell);
59512     u8 *pStop;
59513 
59514     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
59515     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
59516     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
59517     rebuildPage(pNew, 1, &pCell, &szCell);
59518     pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
59519 
59520     /* If this is an auto-vacuum database, update the pointer map
59521     ** with entries for the new page, and any pointer from the
59522     ** cell on the page to an overflow page. If either of these
59523     ** operations fails, the return code is set, but the contents
59524     ** of the parent page are still manipulated by thh code below.
59525     ** That is Ok, at this point the parent page is guaranteed to
59526     ** be marked as dirty. Returning an error code will cause a
59527     ** rollback, undoing any changes made to the parent page.
59528     */
59529     if( ISAUTOVACUUM ){
59530       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
59531       if( szCell>pNew->minLocal ){
59532         ptrmapPutOvflPtr(pNew, pCell, &rc);
59533       }
59534     }
59535 
59536     /* Create a divider cell to insert into pParent. The divider cell
59537     ** consists of a 4-byte page number (the page number of pPage) and
59538     ** a variable length key value (which must be the same value as the
59539     ** largest key on pPage).
59540     **
59541     ** To find the largest key value on pPage, first find the right-most
59542     ** cell on pPage. The first two fields of this cell are the
59543     ** record-length (a variable length integer at most 32-bits in size)
59544     ** and the key value (a variable length integer, may have any value).
59545     ** The first of the while(...) loops below skips over the record-length
59546     ** field. The second while(...) loop copies the key value from the
59547     ** cell on pPage into the pSpace buffer.
59548     */
59549     pCell = findCell(pPage, pPage->nCell-1);
59550     pStop = &pCell[9];
59551     while( (*(pCell++)&0x80) && pCell<pStop );
59552     pStop = &pCell[9];
59553     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
59554 
59555     /* Insert the new divider cell into pParent. */
59556     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
59557                0, pPage->pgno, &rc);
59558 
59559     /* Set the right-child pointer of pParent to point to the new page. */
59560     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
59561 
59562     /* Release the reference to the new page. */
59563     releasePage(pNew);
59564   }
59565 
59566   return rc;
59567 }
59568 #endif /* SQLITE_OMIT_QUICKBALANCE */
59569 
59570 #if 0
59571 /*
59572 ** This function does not contribute anything to the operation of SQLite.
59573 ** it is sometimes activated temporarily while debugging code responsible
59574 ** for setting pointer-map entries.
59575 */
59576 static int ptrmapCheckPages(MemPage **apPage, int nPage){
59577   int i, j;
59578   for(i=0; i<nPage; i++){
59579     Pgno n;
59580     u8 e;
59581     MemPage *pPage = apPage[i];
59582     BtShared *pBt = pPage->pBt;
59583     assert( pPage->isInit );
59584 
59585     for(j=0; j<pPage->nCell; j++){
59586       CellInfo info;
59587       u8 *z;
59588 
59589       z = findCell(pPage, j);
59590       btreeParseCellPtr(pPage, z, &info);
59591       if( info.iOverflow ){
59592         Pgno ovfl = get4byte(&z[info.iOverflow]);
59593         ptrmapGet(pBt, ovfl, &e, &n);
59594         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
59595       }
59596       if( !pPage->leaf ){
59597         Pgno child = get4byte(z);
59598         ptrmapGet(pBt, child, &e, &n);
59599         assert( n==pPage->pgno && e==PTRMAP_BTREE );
59600       }
59601     }
59602     if( !pPage->leaf ){
59603       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
59604       ptrmapGet(pBt, child, &e, &n);
59605       assert( n==pPage->pgno && e==PTRMAP_BTREE );
59606     }
59607   }
59608   return 1;
59609 }
59610 #endif
59611 
59612 /*
59613 ** This function is used to copy the contents of the b-tree node stored
59614 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
59615 ** the pointer-map entries for each child page are updated so that the
59616 ** parent page stored in the pointer map is page pTo. If pFrom contained
59617 ** any cells with overflow page pointers, then the corresponding pointer
59618 ** map entries are also updated so that the parent page is page pTo.
59619 **
59620 ** If pFrom is currently carrying any overflow cells (entries in the
59621 ** MemPage.apOvfl[] array), they are not copied to pTo.
59622 **
59623 ** Before returning, page pTo is reinitialized using btreeInitPage().
59624 **
59625 ** The performance of this function is not critical. It is only used by
59626 ** the balance_shallower() and balance_deeper() procedures, neither of
59627 ** which are called often under normal circumstances.
59628 */
59629 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
59630   if( (*pRC)==SQLITE_OK ){
59631     BtShared * const pBt = pFrom->pBt;
59632     u8 * const aFrom = pFrom->aData;
59633     u8 * const aTo = pTo->aData;
59634     int const iFromHdr = pFrom->hdrOffset;
59635     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
59636     int rc;
59637     int iData;
59638 
59639 
59640     assert( pFrom->isInit );
59641     assert( pFrom->nFree>=iToHdr );
59642     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
59643 
59644     /* Copy the b-tree node content from page pFrom to page pTo. */
59645     iData = get2byte(&aFrom[iFromHdr+5]);
59646     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
59647     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
59648 
59649     /* Reinitialize page pTo so that the contents of the MemPage structure
59650     ** match the new data. The initialization of pTo can actually fail under
59651     ** fairly obscure circumstances, even though it is a copy of initialized
59652     ** page pFrom.
59653     */
59654     pTo->isInit = 0;
59655     rc = btreeInitPage(pTo);
59656     if( rc!=SQLITE_OK ){
59657       *pRC = rc;
59658       return;
59659     }
59660 
59661     /* If this is an auto-vacuum database, update the pointer-map entries
59662     ** for any b-tree or overflow pages that pTo now contains the pointers to.
59663     */
59664     if( ISAUTOVACUUM ){
59665       *pRC = setChildPtrmaps(pTo);
59666     }
59667   }
59668 }
59669 
59670 /*
59671 ** This routine redistributes cells on the iParentIdx'th child of pParent
59672 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
59673 ** same amount of free space. Usually a single sibling on either side of the
59674 ** page are used in the balancing, though both siblings might come from one
59675 ** side if the page is the first or last child of its parent. If the page
59676 ** has fewer than 2 siblings (something which can only happen if the page
59677 ** is a root page or a child of a root page) then all available siblings
59678 ** participate in the balancing.
59679 **
59680 ** The number of siblings of the page might be increased or decreased by
59681 ** one or two in an effort to keep pages nearly full but not over full.
59682 **
59683 ** Note that when this routine is called, some of the cells on the page
59684 ** might not actually be stored in MemPage.aData[]. This can happen
59685 ** if the page is overfull. This routine ensures that all cells allocated
59686 ** to the page and its siblings fit into MemPage.aData[] before returning.
59687 **
59688 ** In the course of balancing the page and its siblings, cells may be
59689 ** inserted into or removed from the parent page (pParent). Doing so
59690 ** may cause the parent page to become overfull or underfull. If this
59691 ** happens, it is the responsibility of the caller to invoke the correct
59692 ** balancing routine to fix this problem (see the balance() routine).
59693 **
59694 ** If this routine fails for any reason, it might leave the database
59695 ** in a corrupted state. So if this routine fails, the database should
59696 ** be rolled back.
59697 **
59698 ** The third argument to this function, aOvflSpace, is a pointer to a
59699 ** buffer big enough to hold one page. If while inserting cells into the parent
59700 ** page (pParent) the parent page becomes overfull, this buffer is
59701 ** used to store the parent's overflow cells. Because this function inserts
59702 ** a maximum of four divider cells into the parent page, and the maximum
59703 ** size of a cell stored within an internal node is always less than 1/4
59704 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
59705 ** enough for all overflow cells.
59706 **
59707 ** If aOvflSpace is set to a null pointer, this function returns
59708 ** SQLITE_NOMEM.
59709 */
59710 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
59711 #pragma optimize("", off)
59712 #endif
59713 static int balance_nonroot(
59714   MemPage *pParent,               /* Parent page of siblings being balanced */
59715   int iParentIdx,                 /* Index of "the page" in pParent */
59716   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
59717   int isRoot,                     /* True if pParent is a root-page */
59718   int bBulk                       /* True if this call is part of a bulk load */
59719 ){
59720   BtShared *pBt;               /* The whole database */
59721   int nCell = 0;               /* Number of cells in apCell[] */
59722   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
59723   int nNew = 0;                /* Number of pages in apNew[] */
59724   int nOld;                    /* Number of pages in apOld[] */
59725   int i, j, k;                 /* Loop counters */
59726   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
59727   int rc = SQLITE_OK;          /* The return code */
59728   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
59729   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
59730   int usableSpace;             /* Bytes in pPage beyond the header */
59731   int pageFlags;               /* Value of pPage->aData[0] */
59732   int subtotal;                /* Subtotal of bytes in cells on one page */
59733   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
59734   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
59735   int szScratch;               /* Size of scratch memory requested */
59736   MemPage *apOld[NB];          /* pPage and up to two siblings */
59737   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
59738   u8 *pRight;                  /* Location in parent of right-sibling pointer */
59739   u8 *apDiv[NB-1];             /* Divider cells in pParent */
59740   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
59741   int cntOld[NB+2];            /* Old index in aCell[] after i-th page */
59742   int szNew[NB+2];             /* Combined size of cells placed on i-th page */
59743   u8 **apCell = 0;             /* All cells begin balanced */
59744   u16 *szCell;                 /* Local size of all cells in apCell[] */
59745   u8 *aSpace1;                 /* Space for copies of dividers cells */
59746   Pgno pgno;                   /* Temp var to store a page number in */
59747   u8 abDone[NB+2];             /* True after i'th new page is populated */
59748   Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
59749   Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
59750   u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
59751 
59752   memset(abDone, 0, sizeof(abDone));
59753   pBt = pParent->pBt;
59754   assert( sqlite3_mutex_held(pBt->mutex) );
59755   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
59756 
59757 #if 0
59758   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
59759 #endif
59760 
59761   /* At this point pParent may have at most one overflow cell. And if
59762   ** this overflow cell is present, it must be the cell with
59763   ** index iParentIdx. This scenario comes about when this function
59764   ** is called (indirectly) from sqlite3BtreeDelete().
59765   */
59766   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
59767   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
59768 
59769   if( !aOvflSpace ){
59770     return SQLITE_NOMEM;
59771   }
59772 
59773   /* Find the sibling pages to balance. Also locate the cells in pParent
59774   ** that divide the siblings. An attempt is made to find NN siblings on
59775   ** either side of pPage. More siblings are taken from one side, however,
59776   ** if there are fewer than NN siblings on the other side. If pParent
59777   ** has NB or fewer children then all children of pParent are taken.
59778   **
59779   ** This loop also drops the divider cells from the parent page. This
59780   ** way, the remainder of the function does not have to deal with any
59781   ** overflow cells in the parent page, since if any existed they will
59782   ** have already been removed.
59783   */
59784   i = pParent->nOverflow + pParent->nCell;
59785   if( i<2 ){
59786     nxDiv = 0;
59787   }else{
59788     assert( bBulk==0 || bBulk==1 );
59789     if( iParentIdx==0 ){
59790       nxDiv = 0;
59791     }else if( iParentIdx==i ){
59792       nxDiv = i-2+bBulk;
59793     }else{
59794       nxDiv = iParentIdx-1;
59795     }
59796     i = 2-bBulk;
59797   }
59798   nOld = i+1;
59799   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
59800     pRight = &pParent->aData[pParent->hdrOffset+8];
59801   }else{
59802     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
59803   }
59804   pgno = get4byte(pRight);
59805   while( 1 ){
59806     rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
59807     if( rc ){
59808       memset(apOld, 0, (i+1)*sizeof(MemPage*));
59809       goto balance_cleanup;
59810     }
59811     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
59812     if( (i--)==0 ) break;
59813 
59814     if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
59815       apDiv[i] = pParent->apOvfl[0];
59816       pgno = get4byte(apDiv[i]);
59817       szNew[i] = cellSizePtr(pParent, apDiv[i]);
59818       pParent->nOverflow = 0;
59819     }else{
59820       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
59821       pgno = get4byte(apDiv[i]);
59822       szNew[i] = cellSizePtr(pParent, apDiv[i]);
59823 
59824       /* Drop the cell from the parent page. apDiv[i] still points to
59825       ** the cell within the parent, even though it has been dropped.
59826       ** This is safe because dropping a cell only overwrites the first
59827       ** four bytes of it, and this function does not need the first
59828       ** four bytes of the divider cell. So the pointer is safe to use
59829       ** later on.
59830       **
59831       ** But not if we are in secure-delete mode. In secure-delete mode,
59832       ** the dropCell() routine will overwrite the entire cell with zeroes.
59833       ** In this case, temporarily copy the cell into the aOvflSpace[]
59834       ** buffer. It will be copied out again as soon as the aSpace[] buffer
59835       ** is allocated.  */
59836       if( pBt->btsFlags & BTS_SECURE_DELETE ){
59837         int iOff;
59838 
59839         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
59840         if( (iOff+szNew[i])>(int)pBt->usableSize ){
59841           rc = SQLITE_CORRUPT_BKPT;
59842           memset(apOld, 0, (i+1)*sizeof(MemPage*));
59843           goto balance_cleanup;
59844         }else{
59845           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
59846           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
59847         }
59848       }
59849       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
59850     }
59851   }
59852 
59853   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
59854   ** alignment */
59855   nMaxCells = (nMaxCells + 3)&~3;
59856 
59857   /*
59858   ** Allocate space for memory structures
59859   */
59860   szScratch =
59861        nMaxCells*sizeof(u8*)                       /* apCell */
59862      + nMaxCells*sizeof(u16)                       /* szCell */
59863      + pBt->pageSize;                              /* aSpace1 */
59864 
59865   /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
59866   ** that is more than 6 times the database page size. */
59867   assert( szScratch<=6*(int)pBt->pageSize );
59868   apCell = sqlite3ScratchMalloc( szScratch );
59869   if( apCell==0 ){
59870     rc = SQLITE_NOMEM;
59871     goto balance_cleanup;
59872   }
59873   szCell = (u16*)&apCell[nMaxCells];
59874   aSpace1 = (u8*)&szCell[nMaxCells];
59875   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
59876 
59877   /*
59878   ** Load pointers to all cells on sibling pages and the divider cells
59879   ** into the local apCell[] array.  Make copies of the divider cells
59880   ** into space obtained from aSpace1[]. The divider cells have already
59881   ** been removed from pParent.
59882   **
59883   ** If the siblings are on leaf pages, then the child pointers of the
59884   ** divider cells are stripped from the cells before they are copied
59885   ** into aSpace1[].  In this way, all cells in apCell[] are without
59886   ** child pointers.  If siblings are not leaves, then all cell in
59887   ** apCell[] include child pointers.  Either way, all cells in apCell[]
59888   ** are alike.
59889   **
59890   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
59891   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
59892   */
59893   leafCorrection = apOld[0]->leaf*4;
59894   leafData = apOld[0]->intKeyLeaf;
59895   for(i=0; i<nOld; i++){
59896     int limit;
59897     MemPage *pOld = apOld[i];
59898 
59899     limit = pOld->nCell+pOld->nOverflow;
59900     if( pOld->nOverflow>0 ){
59901       for(j=0; j<limit; j++){
59902         assert( nCell<nMaxCells );
59903         apCell[nCell] = findOverflowCell(pOld, j);
59904         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
59905         nCell++;
59906       }
59907     }else{
59908       u8 *aData = pOld->aData;
59909       u16 maskPage = pOld->maskPage;
59910       u16 cellOffset = pOld->cellOffset;
59911       for(j=0; j<limit; j++){
59912         assert( nCell<nMaxCells );
59913         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
59914         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
59915         nCell++;
59916       }
59917     }
59918     cntOld[i] = nCell;
59919     if( i<nOld-1 && !leafData){
59920       u16 sz = (u16)szNew[i];
59921       u8 *pTemp;
59922       assert( nCell<nMaxCells );
59923       szCell[nCell] = sz;
59924       pTemp = &aSpace1[iSpace1];
59925       iSpace1 += sz;
59926       assert( sz<=pBt->maxLocal+23 );
59927       assert( iSpace1 <= (int)pBt->pageSize );
59928       memcpy(pTemp, apDiv[i], sz);
59929       apCell[nCell] = pTemp+leafCorrection;
59930       assert( leafCorrection==0 || leafCorrection==4 );
59931       szCell[nCell] = szCell[nCell] - leafCorrection;
59932       if( !pOld->leaf ){
59933         assert( leafCorrection==0 );
59934         assert( pOld->hdrOffset==0 );
59935         /* The right pointer of the child page pOld becomes the left
59936         ** pointer of the divider cell */
59937         memcpy(apCell[nCell], &pOld->aData[8], 4);
59938       }else{
59939         assert( leafCorrection==4 );
59940         if( szCell[nCell]<4 ){
59941           /* Do not allow any cells smaller than 4 bytes. If a smaller cell
59942           ** does exist, pad it with 0x00 bytes. */
59943           assert( szCell[nCell]==3 );
59944           assert( apCell[nCell]==&aSpace1[iSpace1-3] );
59945           aSpace1[iSpace1++] = 0x00;
59946           szCell[nCell] = 4;
59947         }
59948       }
59949       nCell++;
59950     }
59951   }
59952 
59953   /*
59954   ** Figure out the number of pages needed to hold all nCell cells.
59955   ** Store this number in "k".  Also compute szNew[] which is the total
59956   ** size of all cells on the i-th page and cntNew[] which is the index
59957   ** in apCell[] of the cell that divides page i from page i+1.
59958   ** cntNew[k] should equal nCell.
59959   **
59960   ** Values computed by this block:
59961   **
59962   **           k: The total number of sibling pages
59963   **    szNew[i]: Spaced used on the i-th sibling page.
59964   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
59965   **              the right of the i-th sibling page.
59966   ** usableSpace: Number of bytes of space available on each sibling.
59967   **
59968   */
59969   usableSpace = pBt->usableSize - 12 + leafCorrection;
59970   for(subtotal=k=i=0; i<nCell; i++){
59971     assert( i<nMaxCells );
59972     subtotal += szCell[i] + 2;
59973     if( subtotal > usableSpace ){
59974       szNew[k] = subtotal - szCell[i] - 2;
59975       cntNew[k] = i;
59976       if( leafData ){ i--; }
59977       subtotal = 0;
59978       k++;
59979       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
59980     }
59981   }
59982   szNew[k] = subtotal;
59983   cntNew[k] = nCell;
59984   k++;
59985 
59986   /*
59987   ** The packing computed by the previous block is biased toward the siblings
59988   ** on the left side (siblings with smaller keys). The left siblings are
59989   ** always nearly full, while the right-most sibling might be nearly empty.
59990   ** The next block of code attempts to adjust the packing of siblings to
59991   ** get a better balance.
59992   **
59993   ** This adjustment is more than an optimization.  The packing above might
59994   ** be so out of balance as to be illegal.  For example, the right-most
59995   ** sibling might be completely empty.  This adjustment is not optional.
59996   */
59997   for(i=k-1; i>0; i--){
59998     int szRight = szNew[i];  /* Size of sibling on the right */
59999     int szLeft = szNew[i-1]; /* Size of sibling on the left */
60000     int r;              /* Index of right-most cell in left sibling */
60001     int d;              /* Index of first cell to the left of right sibling */
60002 
60003     r = cntNew[i-1] - 1;
60004     d = r + 1 - leafData;
60005     assert( d<nMaxCells );
60006     assert( r<nMaxCells );
60007     while( szRight==0
60008        || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
60009     ){
60010       szRight += szCell[d] + 2;
60011       szLeft -= szCell[r] + 2;
60012       cntNew[i-1]--;
60013       r = cntNew[i-1] - 1;
60014       d = r + 1 - leafData;
60015     }
60016     szNew[i] = szRight;
60017     szNew[i-1] = szLeft;
60018   }
60019 
60020   /* Sanity check:  For a non-corrupt database file one of the follwing
60021   ** must be true:
60022   **    (1) We found one or more cells (cntNew[0])>0), or
60023   **    (2) pPage is a virtual root page.  A virtual root page is when
60024   **        the real root page is page 1 and we are the only child of
60025   **        that page.
60026   */
60027   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
60028   TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
60029     apOld[0]->pgno, apOld[0]->nCell,
60030     nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
60031     nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
60032   ));
60033 
60034   /*
60035   ** Allocate k new pages.  Reuse old pages where possible.
60036   */
60037   if( apOld[0]->pgno<=1 ){
60038     rc = SQLITE_CORRUPT_BKPT;
60039     goto balance_cleanup;
60040   }
60041   pageFlags = apOld[0]->aData[0];
60042   for(i=0; i<k; i++){
60043     MemPage *pNew;
60044     if( i<nOld ){
60045       pNew = apNew[i] = apOld[i];
60046       apOld[i] = 0;
60047       rc = sqlite3PagerWrite(pNew->pDbPage);
60048       nNew++;
60049       if( rc ) goto balance_cleanup;
60050     }else{
60051       assert( i>0 );
60052       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
60053       if( rc ) goto balance_cleanup;
60054       zeroPage(pNew, pageFlags);
60055       apNew[i] = pNew;
60056       nNew++;
60057       cntOld[i] = nCell;
60058 
60059       /* Set the pointer-map entry for the new sibling page. */
60060       if( ISAUTOVACUUM ){
60061         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
60062         if( rc!=SQLITE_OK ){
60063           goto balance_cleanup;
60064         }
60065       }
60066     }
60067   }
60068 
60069   /*
60070   ** Reassign page numbers so that the new pages are in ascending order.
60071   ** This helps to keep entries in the disk file in order so that a scan
60072   ** of the table is closer to a linear scan through the file. That in turn
60073   ** helps the operating system to deliver pages from the disk more rapidly.
60074   **
60075   ** An O(n^2) insertion sort algorithm is used, but since n is never more
60076   ** than (NB+2) (a small constant), that should not be a problem.
60077   **
60078   ** When NB==3, this one optimization makes the database about 25% faster
60079   ** for large insertions and deletions.
60080   */
60081   for(i=0; i<nNew; i++){
60082     aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
60083     aPgFlags[i] = apNew[i]->pDbPage->flags;
60084     for(j=0; j<i; j++){
60085       if( aPgno[j]==aPgno[i] ){
60086         /* This branch is taken if the set of sibling pages somehow contains
60087         ** duplicate entries. This can happen if the database is corrupt.
60088         ** It would be simpler to detect this as part of the loop below, but
60089         ** we do the detection here in order to avoid populating the pager
60090         ** cache with two separate objects associated with the same
60091         ** page number.  */
60092         assert( CORRUPT_DB );
60093         rc = SQLITE_CORRUPT_BKPT;
60094         goto balance_cleanup;
60095       }
60096     }
60097   }
60098   for(i=0; i<nNew; i++){
60099     int iBest = 0;                /* aPgno[] index of page number to use */
60100     for(j=1; j<nNew; j++){
60101       if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
60102     }
60103     pgno = aPgOrder[iBest];
60104     aPgOrder[iBest] = 0xffffffff;
60105     if( iBest!=i ){
60106       if( iBest>i ){
60107         sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
60108       }
60109       sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
60110       apNew[i]->pgno = pgno;
60111     }
60112   }
60113 
60114   TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
60115          "%d(%d nc=%d) %d(%d nc=%d)\n",
60116     apNew[0]->pgno, szNew[0], cntNew[0],
60117     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
60118     nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
60119     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
60120     nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
60121     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
60122     nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
60123     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
60124     nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
60125   ));
60126 
60127   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
60128   put4byte(pRight, apNew[nNew-1]->pgno);
60129 
60130   /* If the sibling pages are not leaves, ensure that the right-child pointer
60131   ** of the right-most new sibling page is set to the value that was
60132   ** originally in the same field of the right-most old sibling page. */
60133   if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
60134     MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
60135     memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
60136   }
60137 
60138   /* Make any required updates to pointer map entries associated with
60139   ** cells stored on sibling pages following the balance operation. Pointer
60140   ** map entries associated with divider cells are set by the insertCell()
60141   ** routine. The associated pointer map entries are:
60142   **
60143   **   a) if the cell contains a reference to an overflow chain, the
60144   **      entry associated with the first page in the overflow chain, and
60145   **
60146   **   b) if the sibling pages are not leaves, the child page associated
60147   **      with the cell.
60148   **
60149   ** If the sibling pages are not leaves, then the pointer map entry
60150   ** associated with the right-child of each sibling may also need to be
60151   ** updated. This happens below, after the sibling pages have been
60152   ** populated, not here.
60153   */
60154   if( ISAUTOVACUUM ){
60155     MemPage *pNew = apNew[0];
60156     u8 *aOld = pNew->aData;
60157     int cntOldNext = pNew->nCell + pNew->nOverflow;
60158     int usableSize = pBt->usableSize;
60159     int iNew = 0;
60160     int iOld = 0;
60161 
60162     for(i=0; i<nCell; i++){
60163       u8 *pCell = apCell[i];
60164       if( i==cntOldNext ){
60165         MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
60166         cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
60167         aOld = pOld->aData;
60168       }
60169       if( i==cntNew[iNew] ){
60170         pNew = apNew[++iNew];
60171         if( !leafData ) continue;
60172       }
60173 
60174       /* Cell pCell is destined for new sibling page pNew. Originally, it
60175       ** was either part of sibling page iOld (possibly an overflow cell),
60176       ** or else the divider cell to the left of sibling page iOld. So,
60177       ** if sibling page iOld had the same page number as pNew, and if
60178       ** pCell really was a part of sibling page iOld (not a divider or
60179       ** overflow cell), we can skip updating the pointer map entries.  */
60180       if( iOld>=nNew
60181        || pNew->pgno!=aPgno[iOld]
60182        || pCell<aOld
60183        || pCell>=&aOld[usableSize]
60184       ){
60185         if( !leafCorrection ){
60186           ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
60187         }
60188         if( szCell[i]>pNew->minLocal ){
60189           ptrmapPutOvflPtr(pNew, pCell, &rc);
60190         }
60191       }
60192     }
60193   }
60194 
60195   /* Insert new divider cells into pParent. */
60196   for(i=0; i<nNew-1; i++){
60197     u8 *pCell;
60198     u8 *pTemp;
60199     int sz;
60200     MemPage *pNew = apNew[i];
60201     j = cntNew[i];
60202 
60203     assert( j<nMaxCells );
60204     pCell = apCell[j];
60205     sz = szCell[j] + leafCorrection;
60206     pTemp = &aOvflSpace[iOvflSpace];
60207     if( !pNew->leaf ){
60208       memcpy(&pNew->aData[8], pCell, 4);
60209     }else if( leafData ){
60210       /* If the tree is a leaf-data tree, and the siblings are leaves,
60211       ** then there is no divider cell in apCell[]. Instead, the divider
60212       ** cell consists of the integer key for the right-most cell of
60213       ** the sibling-page assembled above only.
60214       */
60215       CellInfo info;
60216       j--;
60217       btreeParseCellPtr(pNew, apCell[j], &info);
60218       pCell = pTemp;
60219       sz = 4 + putVarint(&pCell[4], info.nKey);
60220       pTemp = 0;
60221     }else{
60222       pCell -= 4;
60223       /* Obscure case for non-leaf-data trees: If the cell at pCell was
60224       ** previously stored on a leaf node, and its reported size was 4
60225       ** bytes, then it may actually be smaller than this
60226       ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
60227       ** any cell). But it is important to pass the correct size to
60228       ** insertCell(), so reparse the cell now.
60229       **
60230       ** Note that this can never happen in an SQLite data file, as all
60231       ** cells are at least 4 bytes. It only happens in b-trees used
60232       ** to evaluate "IN (SELECT ...)" and similar clauses.
60233       */
60234       if( szCell[j]==4 ){
60235         assert(leafCorrection==4);
60236         sz = cellSizePtr(pParent, pCell);
60237       }
60238     }
60239     iOvflSpace += sz;
60240     assert( sz<=pBt->maxLocal+23 );
60241     assert( iOvflSpace <= (int)pBt->pageSize );
60242     insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
60243     if( rc!=SQLITE_OK ) goto balance_cleanup;
60244     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
60245   }
60246 
60247   /* Now update the actual sibling pages. The order in which they are updated
60248   ** is important, as this code needs to avoid disrupting any page from which
60249   ** cells may still to be read. In practice, this means:
60250   **
60251   **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
60252   **      then it is not safe to update page apNew[iPg] until after
60253   **      the left-hand sibling apNew[iPg-1] has been updated.
60254   **
60255   **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
60256   **      then it is not safe to update page apNew[iPg] until after
60257   **      the right-hand sibling apNew[iPg+1] has been updated.
60258   **
60259   ** If neither of the above apply, the page is safe to update.
60260   **
60261   ** The iPg value in the following loop starts at nNew-1 goes down
60262   ** to 0, then back up to nNew-1 again, thus making two passes over
60263   ** the pages.  On the initial downward pass, only condition (1) above
60264   ** needs to be tested because (2) will always be true from the previous
60265   ** step.  On the upward pass, both conditions are always true, so the
60266   ** upwards pass simply processes pages that were missed on the downward
60267   ** pass.
60268   */
60269   for(i=1-nNew; i<nNew; i++){
60270     int iPg = i<0 ? -i : i;
60271     assert( iPg>=0 && iPg<nNew );
60272     if( abDone[iPg] ) continue;         /* Skip pages already processed */
60273     if( i>=0                            /* On the upwards pass, or... */
60274      || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
60275     ){
60276       int iNew;
60277       int iOld;
60278       int nNewCell;
60279 
60280       /* Verify condition (1):  If cells are moving left, update iPg
60281       ** only after iPg-1 has already been updated. */
60282       assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
60283 
60284       /* Verify condition (2):  If cells are moving right, update iPg
60285       ** only after iPg+1 has already been updated. */
60286       assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
60287 
60288       if( iPg==0 ){
60289         iNew = iOld = 0;
60290         nNewCell = cntNew[0];
60291       }else{
60292         iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : nCell;
60293         iNew = cntNew[iPg-1] + !leafData;
60294         nNewCell = cntNew[iPg] - iNew;
60295       }
60296 
60297       editPage(apNew[iPg], iOld, iNew, nNewCell, apCell, szCell);
60298       abDone[iPg]++;
60299       apNew[iPg]->nFree = usableSpace-szNew[iPg];
60300       assert( apNew[iPg]->nOverflow==0 );
60301       assert( apNew[iPg]->nCell==nNewCell );
60302     }
60303   }
60304 
60305   /* All pages have been processed exactly once */
60306   assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
60307 
60308   assert( nOld>0 );
60309   assert( nNew>0 );
60310 
60311   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
60312     /* The root page of the b-tree now contains no cells. The only sibling
60313     ** page is the right-child of the parent. Copy the contents of the
60314     ** child page into the parent, decreasing the overall height of the
60315     ** b-tree structure by one. This is described as the "balance-shallower"
60316     ** sub-algorithm in some documentation.
60317     **
60318     ** If this is an auto-vacuum database, the call to copyNodeContent()
60319     ** sets all pointer-map entries corresponding to database image pages
60320     ** for which the pointer is stored within the content being copied.
60321     **
60322     ** It is critical that the child page be defragmented before being
60323     ** copied into the parent, because if the parent is page 1 then it will
60324     ** by smaller than the child due to the database header, and so all the
60325     ** free space needs to be up front.
60326     */
60327     assert( nNew==1 );
60328     rc = defragmentPage(apNew[0]);
60329     testcase( rc!=SQLITE_OK );
60330     assert( apNew[0]->nFree ==
60331         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
60332       || rc!=SQLITE_OK
60333     );
60334     copyNodeContent(apNew[0], pParent, &rc);
60335     freePage(apNew[0], &rc);
60336   }else if( ISAUTOVACUUM && !leafCorrection ){
60337     /* Fix the pointer map entries associated with the right-child of each
60338     ** sibling page. All other pointer map entries have already been taken
60339     ** care of.  */
60340     for(i=0; i<nNew; i++){
60341       u32 key = get4byte(&apNew[i]->aData[8]);
60342       ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
60343     }
60344   }
60345 
60346   assert( pParent->isInit );
60347   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
60348           nOld, nNew, nCell));
60349 
60350   /* Free any old pages that were not reused as new pages.
60351   */
60352   for(i=nNew; i<nOld; i++){
60353     freePage(apOld[i], &rc);
60354   }
60355 
60356 #if 0
60357   if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
60358     /* The ptrmapCheckPages() contains assert() statements that verify that
60359     ** all pointer map pages are set correctly. This is helpful while
60360     ** debugging. This is usually disabled because a corrupt database may
60361     ** cause an assert() statement to fail.  */
60362     ptrmapCheckPages(apNew, nNew);
60363     ptrmapCheckPages(&pParent, 1);
60364   }
60365 #endif
60366 
60367   /*
60368   ** Cleanup before returning.
60369   */
60370 balance_cleanup:
60371   sqlite3ScratchFree(apCell);
60372   for(i=0; i<nOld; i++){
60373     releasePage(apOld[i]);
60374   }
60375   for(i=0; i<nNew; i++){
60376     releasePage(apNew[i]);
60377   }
60378 
60379   return rc;
60380 }
60381 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
60382 #pragma optimize("", on)
60383 #endif
60384 
60385 
60386 /*
60387 ** This function is called when the root page of a b-tree structure is
60388 ** overfull (has one or more overflow pages).
60389 **
60390 ** A new child page is allocated and the contents of the current root
60391 ** page, including overflow cells, are copied into the child. The root
60392 ** page is then overwritten to make it an empty page with the right-child
60393 ** pointer pointing to the new page.
60394 **
60395 ** Before returning, all pointer-map entries corresponding to pages
60396 ** that the new child-page now contains pointers to are updated. The
60397 ** entry corresponding to the new right-child pointer of the root
60398 ** page is also updated.
60399 **
60400 ** If successful, *ppChild is set to contain a reference to the child
60401 ** page and SQLITE_OK is returned. In this case the caller is required
60402 ** to call releasePage() on *ppChild exactly once. If an error occurs,
60403 ** an error code is returned and *ppChild is set to 0.
60404 */
60405 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
60406   int rc;                        /* Return value from subprocedures */
60407   MemPage *pChild = 0;           /* Pointer to a new child page */
60408   Pgno pgnoChild = 0;            /* Page number of the new child page */
60409   BtShared *pBt = pRoot->pBt;    /* The BTree */
60410 
60411   assert( pRoot->nOverflow>0 );
60412   assert( sqlite3_mutex_held(pBt->mutex) );
60413 
60414   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
60415   ** page that will become the new right-child of pPage. Copy the contents
60416   ** of the node stored on pRoot into the new child page.
60417   */
60418   rc = sqlite3PagerWrite(pRoot->pDbPage);
60419   if( rc==SQLITE_OK ){
60420     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
60421     copyNodeContent(pRoot, pChild, &rc);
60422     if( ISAUTOVACUUM ){
60423       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
60424     }
60425   }
60426   if( rc ){
60427     *ppChild = 0;
60428     releasePage(pChild);
60429     return rc;
60430   }
60431   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
60432   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
60433   assert( pChild->nCell==pRoot->nCell );
60434 
60435   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
60436 
60437   /* Copy the overflow cells from pRoot to pChild */
60438   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
60439          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
60440   memcpy(pChild->apOvfl, pRoot->apOvfl,
60441          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
60442   pChild->nOverflow = pRoot->nOverflow;
60443 
60444   /* Zero the contents of pRoot. Then install pChild as the right-child. */
60445   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
60446   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
60447 
60448   *ppChild = pChild;
60449   return SQLITE_OK;
60450 }
60451 
60452 /*
60453 ** The page that pCur currently points to has just been modified in
60454 ** some way. This function figures out if this modification means the
60455 ** tree needs to be balanced, and if so calls the appropriate balancing
60456 ** routine. Balancing routines are:
60457 **
60458 **   balance_quick()
60459 **   balance_deeper()
60460 **   balance_nonroot()
60461 */
60462 static int balance(BtCursor *pCur){
60463   int rc = SQLITE_OK;
60464   const int nMin = pCur->pBt->usableSize * 2 / 3;
60465   u8 aBalanceQuickSpace[13];
60466   u8 *pFree = 0;
60467 
60468   TESTONLY( int balance_quick_called = 0 );
60469   TESTONLY( int balance_deeper_called = 0 );
60470 
60471   do {
60472     int iPage = pCur->iPage;
60473     MemPage *pPage = pCur->apPage[iPage];
60474 
60475     if( iPage==0 ){
60476       if( pPage->nOverflow ){
60477         /* The root page of the b-tree is overfull. In this case call the
60478         ** balance_deeper() function to create a new child for the root-page
60479         ** and copy the current contents of the root-page to it. The
60480         ** next iteration of the do-loop will balance the child page.
60481         */
60482         assert( (balance_deeper_called++)==0 );
60483         rc = balance_deeper(pPage, &pCur->apPage[1]);
60484         if( rc==SQLITE_OK ){
60485           pCur->iPage = 1;
60486           pCur->aiIdx[0] = 0;
60487           pCur->aiIdx[1] = 0;
60488           assert( pCur->apPage[1]->nOverflow );
60489         }
60490       }else{
60491         break;
60492       }
60493     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
60494       break;
60495     }else{
60496       MemPage * const pParent = pCur->apPage[iPage-1];
60497       int const iIdx = pCur->aiIdx[iPage-1];
60498 
60499       rc = sqlite3PagerWrite(pParent->pDbPage);
60500       if( rc==SQLITE_OK ){
60501 #ifndef SQLITE_OMIT_QUICKBALANCE
60502         if( pPage->intKeyLeaf
60503          && pPage->nOverflow==1
60504          && pPage->aiOvfl[0]==pPage->nCell
60505          && pParent->pgno!=1
60506          && pParent->nCell==iIdx
60507         ){
60508           /* Call balance_quick() to create a new sibling of pPage on which
60509           ** to store the overflow cell. balance_quick() inserts a new cell
60510           ** into pParent, which may cause pParent overflow. If this
60511           ** happens, the next iteration of the do-loop will balance pParent
60512           ** use either balance_nonroot() or balance_deeper(). Until this
60513           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
60514           ** buffer.
60515           **
60516           ** The purpose of the following assert() is to check that only a
60517           ** single call to balance_quick() is made for each call to this
60518           ** function. If this were not verified, a subtle bug involving reuse
60519           ** of the aBalanceQuickSpace[] might sneak in.
60520           */
60521           assert( (balance_quick_called++)==0 );
60522           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
60523         }else
60524 #endif
60525         {
60526           /* In this case, call balance_nonroot() to redistribute cells
60527           ** between pPage and up to 2 of its sibling pages. This involves
60528           ** modifying the contents of pParent, which may cause pParent to
60529           ** become overfull or underfull. The next iteration of the do-loop
60530           ** will balance the parent page to correct this.
60531           **
60532           ** If the parent page becomes overfull, the overflow cell or cells
60533           ** are stored in the pSpace buffer allocated immediately below.
60534           ** A subsequent iteration of the do-loop will deal with this by
60535           ** calling balance_nonroot() (balance_deeper() may be called first,
60536           ** but it doesn't deal with overflow cells - just moves them to a
60537           ** different page). Once this subsequent call to balance_nonroot()
60538           ** has completed, it is safe to release the pSpace buffer used by
60539           ** the previous call, as the overflow cell data will have been
60540           ** copied either into the body of a database page or into the new
60541           ** pSpace buffer passed to the latter call to balance_nonroot().
60542           */
60543           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
60544           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
60545                                pCur->hints&BTREE_BULKLOAD);
60546           if( pFree ){
60547             /* If pFree is not NULL, it points to the pSpace buffer used
60548             ** by a previous call to balance_nonroot(). Its contents are
60549             ** now stored either on real database pages or within the
60550             ** new pSpace buffer, so it may be safely freed here. */
60551             sqlite3PageFree(pFree);
60552           }
60553 
60554           /* The pSpace buffer will be freed after the next call to
60555           ** balance_nonroot(), or just before this function returns, whichever
60556           ** comes first. */
60557           pFree = pSpace;
60558         }
60559       }
60560 
60561       pPage->nOverflow = 0;
60562 
60563       /* The next iteration of the do-loop balances the parent page. */
60564       releasePage(pPage);
60565       pCur->iPage--;
60566       assert( pCur->iPage>=0 );
60567     }
60568   }while( rc==SQLITE_OK );
60569 
60570   if( pFree ){
60571     sqlite3PageFree(pFree);
60572   }
60573   return rc;
60574 }
60575 
60576 
60577 /*
60578 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
60579 ** and the data is given by (pData,nData).  The cursor is used only to
60580 ** define what table the record should be inserted into.  The cursor
60581 ** is left pointing at a random location.
60582 **
60583 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
60584 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
60585 **
60586 ** If the seekResult parameter is non-zero, then a successful call to
60587 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
60588 ** been performed. seekResult is the search result returned (a negative
60589 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
60590 ** a positive value if pCur points at an entry that is larger than
60591 ** (pKey, nKey)).
60592 **
60593 ** If the seekResult parameter is non-zero, then the caller guarantees that
60594 ** cursor pCur is pointing at the existing copy of a row that is to be
60595 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
60596 ** point to any entry or to no entry at all and so this function has to seek
60597 ** the cursor before the new key can be inserted.
60598 */
60599 SQLITE_PRIVATE int sqlite3BtreeInsert(
60600   BtCursor *pCur,                /* Insert data into the table of this cursor */
60601   const void *pKey, i64 nKey,    /* The key of the new record */
60602   const void *pData, int nData,  /* The data of the new record */
60603   int nZero,                     /* Number of extra 0 bytes to append to data */
60604   int appendBias,                /* True if this is likely an append */
60605   int seekResult                 /* Result of prior MovetoUnpacked() call */
60606 ){
60607   int rc;
60608   int loc = seekResult;          /* -1: before desired location  +1: after */
60609   int szNew = 0;
60610   int idx;
60611   MemPage *pPage;
60612   Btree *p = pCur->pBtree;
60613   BtShared *pBt = p->pBt;
60614   unsigned char *oldCell;
60615   unsigned char *newCell = 0;
60616 
60617   if( pCur->eState==CURSOR_FAULT ){
60618     assert( pCur->skipNext!=SQLITE_OK );
60619     return pCur->skipNext;
60620   }
60621 
60622   assert( cursorHoldsMutex(pCur) );
60623   assert( (pCur->curFlags & BTCF_WriteFlag)!=0
60624               && pBt->inTransaction==TRANS_WRITE
60625               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
60626   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
60627 
60628   /* Assert that the caller has been consistent. If this cursor was opened
60629   ** expecting an index b-tree, then the caller should be inserting blob
60630   ** keys with no associated data. If the cursor was opened expecting an
60631   ** intkey table, the caller should be inserting integer keys with a
60632   ** blob of associated data.  */
60633   assert( (pKey==0)==(pCur->pKeyInfo==0) );
60634 
60635   /* Save the positions of any other cursors open on this table.
60636   **
60637   ** In some cases, the call to btreeMoveto() below is a no-op. For
60638   ** example, when inserting data into a table with auto-generated integer
60639   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
60640   ** integer key to use. It then calls this function to actually insert the
60641   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
60642   ** that the cursor is already where it needs to be and returns without
60643   ** doing any work. To avoid thwarting these optimizations, it is important
60644   ** not to clear the cursor here.
60645   */
60646   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
60647   if( rc ) return rc;
60648 
60649   if( pCur->pKeyInfo==0 ){
60650     /* If this is an insert into a table b-tree, invalidate any incrblob
60651     ** cursors open on the row being replaced */
60652     invalidateIncrblobCursors(p, nKey, 0);
60653 
60654     /* If the cursor is currently on the last row and we are appending a
60655     ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
60656     ** call */
60657     if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
60658       && pCur->info.nKey==nKey-1 ){
60659       loc = -1;
60660     }
60661   }
60662 
60663   if( !loc ){
60664     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
60665     if( rc ) return rc;
60666   }
60667   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
60668 
60669   pPage = pCur->apPage[pCur->iPage];
60670   assert( pPage->intKey || nKey>=0 );
60671   assert( pPage->leaf || !pPage->intKey );
60672 
60673   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
60674           pCur->pgnoRoot, nKey, nData, pPage->pgno,
60675           loc==0 ? "overwrite" : "new entry"));
60676   assert( pPage->isInit );
60677   newCell = pBt->pTmpSpace;
60678   assert( newCell!=0 );
60679   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
60680   if( rc ) goto end_insert;
60681   assert( szNew==cellSizePtr(pPage, newCell) );
60682   assert( szNew <= MX_CELL_SIZE(pBt) );
60683   idx = pCur->aiIdx[pCur->iPage];
60684   if( loc==0 ){
60685     u16 szOld;
60686     assert( idx<pPage->nCell );
60687     rc = sqlite3PagerWrite(pPage->pDbPage);
60688     if( rc ){
60689       goto end_insert;
60690     }
60691     oldCell = findCell(pPage, idx);
60692     if( !pPage->leaf ){
60693       memcpy(newCell, oldCell, 4);
60694     }
60695     rc = clearCell(pPage, oldCell, &szOld);
60696     dropCell(pPage, idx, szOld, &rc);
60697     if( rc ) goto end_insert;
60698   }else if( loc<0 && pPage->nCell>0 ){
60699     assert( pPage->leaf );
60700     idx = ++pCur->aiIdx[pCur->iPage];
60701   }else{
60702     assert( pPage->leaf );
60703   }
60704   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
60705   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
60706 
60707   /* If no error has occurred and pPage has an overflow cell, call balance()
60708   ** to redistribute the cells within the tree. Since balance() may move
60709   ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
60710   ** variables.
60711   **
60712   ** Previous versions of SQLite called moveToRoot() to move the cursor
60713   ** back to the root page as balance() used to invalidate the contents
60714   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
60715   ** set the cursor state to "invalid". This makes common insert operations
60716   ** slightly faster.
60717   **
60718   ** There is a subtle but important optimization here too. When inserting
60719   ** multiple records into an intkey b-tree using a single cursor (as can
60720   ** happen while processing an "INSERT INTO ... SELECT" statement), it
60721   ** is advantageous to leave the cursor pointing to the last entry in
60722   ** the b-tree if possible. If the cursor is left pointing to the last
60723   ** entry in the table, and the next row inserted has an integer key
60724   ** larger than the largest existing key, it is possible to insert the
60725   ** row without seeking the cursor. This can be a big performance boost.
60726   */
60727   pCur->info.nSize = 0;
60728   if( rc==SQLITE_OK && pPage->nOverflow ){
60729     pCur->curFlags &= ~(BTCF_ValidNKey);
60730     rc = balance(pCur);
60731 
60732     /* Must make sure nOverflow is reset to zero even if the balance()
60733     ** fails. Internal data structure corruption will result otherwise.
60734     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
60735     ** from trying to save the current position of the cursor.  */
60736     pCur->apPage[pCur->iPage]->nOverflow = 0;
60737     pCur->eState = CURSOR_INVALID;
60738   }
60739   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
60740 
60741 end_insert:
60742   return rc;
60743 }
60744 
60745 /*
60746 ** Delete the entry that the cursor is pointing to.  The cursor
60747 ** is left pointing at an arbitrary location.
60748 */
60749 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
60750   Btree *p = pCur->pBtree;
60751   BtShared *pBt = p->pBt;
60752   int rc;                              /* Return code */
60753   MemPage *pPage;                      /* Page to delete cell from */
60754   unsigned char *pCell;                /* Pointer to cell to delete */
60755   int iCellIdx;                        /* Index of cell to delete */
60756   int iCellDepth;                      /* Depth of node containing pCell */
60757   u16 szCell;                          /* Size of the cell being deleted */
60758 
60759   assert( cursorHoldsMutex(pCur) );
60760   assert( pBt->inTransaction==TRANS_WRITE );
60761   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
60762   assert( pCur->curFlags & BTCF_WriteFlag );
60763   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
60764   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
60765 
60766   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
60767    || NEVER(pCur->eState!=CURSOR_VALID)
60768   ){
60769     return SQLITE_ERROR;  /* Something has gone awry. */
60770   }
60771 
60772   iCellDepth = pCur->iPage;
60773   iCellIdx = pCur->aiIdx[iCellDepth];
60774   pPage = pCur->apPage[iCellDepth];
60775   pCell = findCell(pPage, iCellIdx);
60776 
60777   /* If the page containing the entry to delete is not a leaf page, move
60778   ** the cursor to the largest entry in the tree that is smaller than
60779   ** the entry being deleted. This cell will replace the cell being deleted
60780   ** from the internal node. The 'previous' entry is used for this instead
60781   ** of the 'next' entry, as the previous entry is always a part of the
60782   ** sub-tree headed by the child page of the cell being deleted. This makes
60783   ** balancing the tree following the delete operation easier.  */
60784   if( !pPage->leaf ){
60785     int notUsed = 0;
60786     rc = sqlite3BtreePrevious(pCur, &notUsed);
60787     if( rc ) return rc;
60788   }
60789 
60790   /* Save the positions of any other cursors open on this table before
60791   ** making any modifications. Make the page containing the entry to be
60792   ** deleted writable. Then free any overflow pages associated with the
60793   ** entry and finally remove the cell itself from within the page.
60794   */
60795   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
60796   if( rc ) return rc;
60797 
60798   /* If this is a delete operation to remove a row from a table b-tree,
60799   ** invalidate any incrblob cursors open on the row being deleted.  */
60800   if( pCur->pKeyInfo==0 ){
60801     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
60802   }
60803 
60804   rc = sqlite3PagerWrite(pPage->pDbPage);
60805   if( rc ) return rc;
60806   rc = clearCell(pPage, pCell, &szCell);
60807   dropCell(pPage, iCellIdx, szCell, &rc);
60808   if( rc ) return rc;
60809 
60810   /* If the cell deleted was not located on a leaf page, then the cursor
60811   ** is currently pointing to the largest entry in the sub-tree headed
60812   ** by the child-page of the cell that was just deleted from an internal
60813   ** node. The cell from the leaf node needs to be moved to the internal
60814   ** node to replace the deleted cell.  */
60815   if( !pPage->leaf ){
60816     MemPage *pLeaf = pCur->apPage[pCur->iPage];
60817     int nCell;
60818     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
60819     unsigned char *pTmp;
60820 
60821     pCell = findCell(pLeaf, pLeaf->nCell-1);
60822     nCell = cellSizePtr(pLeaf, pCell);
60823     assert( MX_CELL_SIZE(pBt) >= nCell );
60824     pTmp = pBt->pTmpSpace;
60825     assert( pTmp!=0 );
60826     rc = sqlite3PagerWrite(pLeaf->pDbPage);
60827     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
60828     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
60829     if( rc ) return rc;
60830   }
60831 
60832   /* Balance the tree. If the entry deleted was located on a leaf page,
60833   ** then the cursor still points to that page. In this case the first
60834   ** call to balance() repairs the tree, and the if(...) condition is
60835   ** never true.
60836   **
60837   ** Otherwise, if the entry deleted was on an internal node page, then
60838   ** pCur is pointing to the leaf page from which a cell was removed to
60839   ** replace the cell deleted from the internal node. This is slightly
60840   ** tricky as the leaf node may be underfull, and the internal node may
60841   ** be either under or overfull. In this case run the balancing algorithm
60842   ** on the leaf node first. If the balance proceeds far enough up the
60843   ** tree that we can be sure that any problem in the internal node has
60844   ** been corrected, so be it. Otherwise, after balancing the leaf node,
60845   ** walk the cursor up the tree to the internal node and balance it as
60846   ** well.  */
60847   rc = balance(pCur);
60848   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
60849     while( pCur->iPage>iCellDepth ){
60850       releasePage(pCur->apPage[pCur->iPage--]);
60851     }
60852     rc = balance(pCur);
60853   }
60854 
60855   if( rc==SQLITE_OK ){
60856     moveToRoot(pCur);
60857   }
60858   return rc;
60859 }
60860 
60861 /*
60862 ** Create a new BTree table.  Write into *piTable the page
60863 ** number for the root page of the new table.
60864 **
60865 ** The type of type is determined by the flags parameter.  Only the
60866 ** following values of flags are currently in use.  Other values for
60867 ** flags might not work:
60868 **
60869 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
60870 **     BTREE_ZERODATA                  Used for SQL indices
60871 */
60872 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
60873   BtShared *pBt = p->pBt;
60874   MemPage *pRoot;
60875   Pgno pgnoRoot;
60876   int rc;
60877   int ptfFlags;          /* Page-type flage for the root page of new table */
60878 
60879   assert( sqlite3BtreeHoldsMutex(p) );
60880   assert( pBt->inTransaction==TRANS_WRITE );
60881   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
60882 
60883 #ifdef SQLITE_OMIT_AUTOVACUUM
60884   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
60885   if( rc ){
60886     return rc;
60887   }
60888 #else
60889   if( pBt->autoVacuum ){
60890     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
60891     MemPage *pPageMove; /* The page to move to. */
60892 
60893     /* Creating a new table may probably require moving an existing database
60894     ** to make room for the new tables root page. In case this page turns
60895     ** out to be an overflow page, delete all overflow page-map caches
60896     ** held by open cursors.
60897     */
60898     invalidateAllOverflowCache(pBt);
60899 
60900     /* Read the value of meta[3] from the database to determine where the
60901     ** root page of the new table should go. meta[3] is the largest root-page
60902     ** created so far, so the new root-page is (meta[3]+1).
60903     */
60904     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
60905     pgnoRoot++;
60906 
60907     /* The new root-page may not be allocated on a pointer-map page, or the
60908     ** PENDING_BYTE page.
60909     */
60910     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
60911         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
60912       pgnoRoot++;
60913     }
60914     assert( pgnoRoot>=3 );
60915 
60916     /* Allocate a page. The page that currently resides at pgnoRoot will
60917     ** be moved to the allocated page (unless the allocated page happens
60918     ** to reside at pgnoRoot).
60919     */
60920     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
60921     if( rc!=SQLITE_OK ){
60922       return rc;
60923     }
60924 
60925     if( pgnoMove!=pgnoRoot ){
60926       /* pgnoRoot is the page that will be used for the root-page of
60927       ** the new table (assuming an error did not occur). But we were
60928       ** allocated pgnoMove. If required (i.e. if it was not allocated
60929       ** by extending the file), the current page at position pgnoMove
60930       ** is already journaled.
60931       */
60932       u8 eType = 0;
60933       Pgno iPtrPage = 0;
60934 
60935       /* Save the positions of any open cursors. This is required in
60936       ** case they are holding a reference to an xFetch reference
60937       ** corresponding to page pgnoRoot.  */
60938       rc = saveAllCursors(pBt, 0, 0);
60939       releasePage(pPageMove);
60940       if( rc!=SQLITE_OK ){
60941         return rc;
60942       }
60943 
60944       /* Move the page currently at pgnoRoot to pgnoMove. */
60945       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
60946       if( rc!=SQLITE_OK ){
60947         return rc;
60948       }
60949       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
60950       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
60951         rc = SQLITE_CORRUPT_BKPT;
60952       }
60953       if( rc!=SQLITE_OK ){
60954         releasePage(pRoot);
60955         return rc;
60956       }
60957       assert( eType!=PTRMAP_ROOTPAGE );
60958       assert( eType!=PTRMAP_FREEPAGE );
60959       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
60960       releasePage(pRoot);
60961 
60962       /* Obtain the page at pgnoRoot */
60963       if( rc!=SQLITE_OK ){
60964         return rc;
60965       }
60966       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
60967       if( rc!=SQLITE_OK ){
60968         return rc;
60969       }
60970       rc = sqlite3PagerWrite(pRoot->pDbPage);
60971       if( rc!=SQLITE_OK ){
60972         releasePage(pRoot);
60973         return rc;
60974       }
60975     }else{
60976       pRoot = pPageMove;
60977     }
60978 
60979     /* Update the pointer-map and meta-data with the new root-page number. */
60980     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
60981     if( rc ){
60982       releasePage(pRoot);
60983       return rc;
60984     }
60985 
60986     /* When the new root page was allocated, page 1 was made writable in
60987     ** order either to increase the database filesize, or to decrement the
60988     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
60989     */
60990     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
60991     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
60992     if( NEVER(rc) ){
60993       releasePage(pRoot);
60994       return rc;
60995     }
60996 
60997   }else{
60998     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
60999     if( rc ) return rc;
61000   }
61001 #endif
61002   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
61003   if( createTabFlags & BTREE_INTKEY ){
61004     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
61005   }else{
61006     ptfFlags = PTF_ZERODATA | PTF_LEAF;
61007   }
61008   zeroPage(pRoot, ptfFlags);
61009   sqlite3PagerUnref(pRoot->pDbPage);
61010   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
61011   *piTable = (int)pgnoRoot;
61012   return SQLITE_OK;
61013 }
61014 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
61015   int rc;
61016   sqlite3BtreeEnter(p);
61017   rc = btreeCreateTable(p, piTable, flags);
61018   sqlite3BtreeLeave(p);
61019   return rc;
61020 }
61021 
61022 /*
61023 ** Erase the given database page and all its children.  Return
61024 ** the page to the freelist.
61025 */
61026 static int clearDatabasePage(
61027   BtShared *pBt,           /* The BTree that contains the table */
61028   Pgno pgno,               /* Page number to clear */
61029   int freePageFlag,        /* Deallocate page if true */
61030   int *pnChange            /* Add number of Cells freed to this counter */
61031 ){
61032   MemPage *pPage;
61033   int rc;
61034   unsigned char *pCell;
61035   int i;
61036   int hdr;
61037   u16 szCell;
61038 
61039   assert( sqlite3_mutex_held(pBt->mutex) );
61040   if( pgno>btreePagecount(pBt) ){
61041     return SQLITE_CORRUPT_BKPT;
61042   }
61043   rc = getAndInitPage(pBt, pgno, &pPage, 0);
61044   if( rc ) return rc;
61045   if( pPage->bBusy ){
61046     rc = SQLITE_CORRUPT_BKPT;
61047     goto cleardatabasepage_out;
61048   }
61049   pPage->bBusy = 1;
61050   hdr = pPage->hdrOffset;
61051   for(i=0; i<pPage->nCell; i++){
61052     pCell = findCell(pPage, i);
61053     if( !pPage->leaf ){
61054       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
61055       if( rc ) goto cleardatabasepage_out;
61056     }
61057     rc = clearCell(pPage, pCell, &szCell);
61058     if( rc ) goto cleardatabasepage_out;
61059   }
61060   if( !pPage->leaf ){
61061     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
61062     if( rc ) goto cleardatabasepage_out;
61063   }else if( pnChange ){
61064     assert( pPage->intKey );
61065     *pnChange += pPage->nCell;
61066   }
61067   if( freePageFlag ){
61068     freePage(pPage, &rc);
61069   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
61070     zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
61071   }
61072 
61073 cleardatabasepage_out:
61074   pPage->bBusy = 0;
61075   releasePage(pPage);
61076   return rc;
61077 }
61078 
61079 /*
61080 ** Delete all information from a single table in the database.  iTable is
61081 ** the page number of the root of the table.  After this routine returns,
61082 ** the root page is empty, but still exists.
61083 **
61084 ** This routine will fail with SQLITE_LOCKED if there are any open
61085 ** read cursors on the table.  Open write cursors are moved to the
61086 ** root of the table.
61087 **
61088 ** If pnChange is not NULL, then table iTable must be an intkey table. The
61089 ** integer value pointed to by pnChange is incremented by the number of
61090 ** entries in the table.
61091 */
61092 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
61093   int rc;
61094   BtShared *pBt = p->pBt;
61095   sqlite3BtreeEnter(p);
61096   assert( p->inTrans==TRANS_WRITE );
61097 
61098   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
61099 
61100   if( SQLITE_OK==rc ){
61101     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
61102     ** is the root of a table b-tree - if it is not, the following call is
61103     ** a no-op).  */
61104     invalidateIncrblobCursors(p, 0, 1);
61105     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
61106   }
61107   sqlite3BtreeLeave(p);
61108   return rc;
61109 }
61110 
61111 /*
61112 ** Delete all information from the single table that pCur is open on.
61113 **
61114 ** This routine only work for pCur on an ephemeral table.
61115 */
61116 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
61117   return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
61118 }
61119 
61120 /*
61121 ** Erase all information in a table and add the root of the table to
61122 ** the freelist.  Except, the root of the principle table (the one on
61123 ** page 1) is never added to the freelist.
61124 **
61125 ** This routine will fail with SQLITE_LOCKED if there are any open
61126 ** cursors on the table.
61127 **
61128 ** If AUTOVACUUM is enabled and the page at iTable is not the last
61129 ** root page in the database file, then the last root page
61130 ** in the database file is moved into the slot formerly occupied by
61131 ** iTable and that last slot formerly occupied by the last root page
61132 ** is added to the freelist instead of iTable.  In this say, all
61133 ** root pages are kept at the beginning of the database file, which
61134 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
61135 ** page number that used to be the last root page in the file before
61136 ** the move.  If no page gets moved, *piMoved is set to 0.
61137 ** The last root page is recorded in meta[3] and the value of
61138 ** meta[3] is updated by this procedure.
61139 */
61140 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
61141   int rc;
61142   MemPage *pPage = 0;
61143   BtShared *pBt = p->pBt;
61144 
61145   assert( sqlite3BtreeHoldsMutex(p) );
61146   assert( p->inTrans==TRANS_WRITE );
61147 
61148   /* It is illegal to drop a table if any cursors are open on the
61149   ** database. This is because in auto-vacuum mode the backend may
61150   ** need to move another root-page to fill a gap left by the deleted
61151   ** root page. If an open cursor was using this page a problem would
61152   ** occur.
61153   **
61154   ** This error is caught long before control reaches this point.
61155   */
61156   if( NEVER(pBt->pCursor) ){
61157     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
61158     return SQLITE_LOCKED_SHAREDCACHE;
61159   }
61160 
61161   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
61162   if( rc ) return rc;
61163   rc = sqlite3BtreeClearTable(p, iTable, 0);
61164   if( rc ){
61165     releasePage(pPage);
61166     return rc;
61167   }
61168 
61169   *piMoved = 0;
61170 
61171   if( iTable>1 ){
61172 #ifdef SQLITE_OMIT_AUTOVACUUM
61173     freePage(pPage, &rc);
61174     releasePage(pPage);
61175 #else
61176     if( pBt->autoVacuum ){
61177       Pgno maxRootPgno;
61178       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
61179 
61180       if( iTable==maxRootPgno ){
61181         /* If the table being dropped is the table with the largest root-page
61182         ** number in the database, put the root page on the free list.
61183         */
61184         freePage(pPage, &rc);
61185         releasePage(pPage);
61186         if( rc!=SQLITE_OK ){
61187           return rc;
61188         }
61189       }else{
61190         /* The table being dropped does not have the largest root-page
61191         ** number in the database. So move the page that does into the
61192         ** gap left by the deleted root-page.
61193         */
61194         MemPage *pMove;
61195         releasePage(pPage);
61196         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
61197         if( rc!=SQLITE_OK ){
61198           return rc;
61199         }
61200         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
61201         releasePage(pMove);
61202         if( rc!=SQLITE_OK ){
61203           return rc;
61204         }
61205         pMove = 0;
61206         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
61207         freePage(pMove, &rc);
61208         releasePage(pMove);
61209         if( rc!=SQLITE_OK ){
61210           return rc;
61211         }
61212         *piMoved = maxRootPgno;
61213       }
61214 
61215       /* Set the new 'max-root-page' value in the database header. This
61216       ** is the old value less one, less one more if that happens to
61217       ** be a root-page number, less one again if that is the
61218       ** PENDING_BYTE_PAGE.
61219       */
61220       maxRootPgno--;
61221       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
61222              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
61223         maxRootPgno--;
61224       }
61225       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
61226 
61227       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
61228     }else{
61229       freePage(pPage, &rc);
61230       releasePage(pPage);
61231     }
61232 #endif
61233   }else{
61234     /* If sqlite3BtreeDropTable was called on page 1.
61235     ** This really never should happen except in a corrupt
61236     ** database.
61237     */
61238     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
61239     releasePage(pPage);
61240   }
61241   return rc;
61242 }
61243 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
61244   int rc;
61245   sqlite3BtreeEnter(p);
61246   rc = btreeDropTable(p, iTable, piMoved);
61247   sqlite3BtreeLeave(p);
61248   return rc;
61249 }
61250 
61251 
61252 /*
61253 ** This function may only be called if the b-tree connection already
61254 ** has a read or write transaction open on the database.
61255 **
61256 ** Read the meta-information out of a database file.  Meta[0]
61257 ** is the number of free pages currently in the database.  Meta[1]
61258 ** through meta[15] are available for use by higher layers.  Meta[0]
61259 ** is read-only, the others are read/write.
61260 **
61261 ** The schema layer numbers meta values differently.  At the schema
61262 ** layer (and the SetCookie and ReadCookie opcodes) the number of
61263 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
61264 **
61265 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
61266 ** of reading the value out of the header, it instead loads the "DataVersion"
61267 ** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
61268 ** database file.  It is a number computed by the pager.  But its access
61269 ** pattern is the same as header meta values, and so it is convenient to
61270 ** read it from this routine.
61271 */
61272 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
61273   BtShared *pBt = p->pBt;
61274 
61275   sqlite3BtreeEnter(p);
61276   assert( p->inTrans>TRANS_NONE );
61277   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
61278   assert( pBt->pPage1 );
61279   assert( idx>=0 && idx<=15 );
61280 
61281   if( idx==BTREE_DATA_VERSION ){
61282     *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
61283   }else{
61284     *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
61285   }
61286 
61287   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
61288   ** database, mark the database as read-only.  */
61289 #ifdef SQLITE_OMIT_AUTOVACUUM
61290   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
61291     pBt->btsFlags |= BTS_READ_ONLY;
61292   }
61293 #endif
61294 
61295   sqlite3BtreeLeave(p);
61296 }
61297 
61298 /*
61299 ** Write meta-information back into the database.  Meta[0] is
61300 ** read-only and may not be written.
61301 */
61302 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
61303   BtShared *pBt = p->pBt;
61304   unsigned char *pP1;
61305   int rc;
61306   assert( idx>=1 && idx<=15 );
61307   sqlite3BtreeEnter(p);
61308   assert( p->inTrans==TRANS_WRITE );
61309   assert( pBt->pPage1!=0 );
61310   pP1 = pBt->pPage1->aData;
61311   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61312   if( rc==SQLITE_OK ){
61313     put4byte(&pP1[36 + idx*4], iMeta);
61314 #ifndef SQLITE_OMIT_AUTOVACUUM
61315     if( idx==BTREE_INCR_VACUUM ){
61316       assert( pBt->autoVacuum || iMeta==0 );
61317       assert( iMeta==0 || iMeta==1 );
61318       pBt->incrVacuum = (u8)iMeta;
61319     }
61320 #endif
61321   }
61322   sqlite3BtreeLeave(p);
61323   return rc;
61324 }
61325 
61326 #ifndef SQLITE_OMIT_BTREECOUNT
61327 /*
61328 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
61329 ** number of entries in the b-tree and write the result to *pnEntry.
61330 **
61331 ** SQLITE_OK is returned if the operation is successfully executed.
61332 ** Otherwise, if an error is encountered (i.e. an IO error or database
61333 ** corruption) an SQLite error code is returned.
61334 */
61335 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
61336   i64 nEntry = 0;                      /* Value to return in *pnEntry */
61337   int rc;                              /* Return code */
61338 
61339   if( pCur->pgnoRoot==0 ){
61340     *pnEntry = 0;
61341     return SQLITE_OK;
61342   }
61343   rc = moveToRoot(pCur);
61344 
61345   /* Unless an error occurs, the following loop runs one iteration for each
61346   ** page in the B-Tree structure (not including overflow pages).
61347   */
61348   while( rc==SQLITE_OK ){
61349     int iIdx;                          /* Index of child node in parent */
61350     MemPage *pPage;                    /* Current page of the b-tree */
61351 
61352     /* If this is a leaf page or the tree is not an int-key tree, then
61353     ** this page contains countable entries. Increment the entry counter
61354     ** accordingly.
61355     */
61356     pPage = pCur->apPage[pCur->iPage];
61357     if( pPage->leaf || !pPage->intKey ){
61358       nEntry += pPage->nCell;
61359     }
61360 
61361     /* pPage is a leaf node. This loop navigates the cursor so that it
61362     ** points to the first interior cell that it points to the parent of
61363     ** the next page in the tree that has not yet been visited. The
61364     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
61365     ** of the page, or to the number of cells in the page if the next page
61366     ** to visit is the right-child of its parent.
61367     **
61368     ** If all pages in the tree have been visited, return SQLITE_OK to the
61369     ** caller.
61370     */
61371     if( pPage->leaf ){
61372       do {
61373         if( pCur->iPage==0 ){
61374           /* All pages of the b-tree have been visited. Return successfully. */
61375           *pnEntry = nEntry;
61376           return moveToRoot(pCur);
61377         }
61378         moveToParent(pCur);
61379       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
61380 
61381       pCur->aiIdx[pCur->iPage]++;
61382       pPage = pCur->apPage[pCur->iPage];
61383     }
61384 
61385     /* Descend to the child node of the cell that the cursor currently
61386     ** points at. This is the right-child if (iIdx==pPage->nCell).
61387     */
61388     iIdx = pCur->aiIdx[pCur->iPage];
61389     if( iIdx==pPage->nCell ){
61390       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
61391     }else{
61392       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
61393     }
61394   }
61395 
61396   /* An error has occurred. Return an error code. */
61397   return rc;
61398 }
61399 #endif
61400 
61401 /*
61402 ** Return the pager associated with a BTree.  This routine is used for
61403 ** testing and debugging only.
61404 */
61405 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
61406   return p->pBt->pPager;
61407 }
61408 
61409 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
61410 /*
61411 ** Append a message to the error message string.
61412 */
61413 static void checkAppendMsg(
61414   IntegrityCk *pCheck,
61415   const char *zFormat,
61416   ...
61417 ){
61418   va_list ap;
61419   char zBuf[200];
61420   if( !pCheck->mxErr ) return;
61421   pCheck->mxErr--;
61422   pCheck->nErr++;
61423   va_start(ap, zFormat);
61424   if( pCheck->errMsg.nChar ){
61425     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
61426   }
61427   if( pCheck->zPfx ){
61428     sqlite3_snprintf(sizeof(zBuf), zBuf, pCheck->zPfx, pCheck->v1, pCheck->v2);
61429     sqlite3StrAccumAppendAll(&pCheck->errMsg, zBuf);
61430   }
61431   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
61432   va_end(ap);
61433   if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
61434     pCheck->mallocFailed = 1;
61435   }
61436 }
61437 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
61438 
61439 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
61440 
61441 /*
61442 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
61443 ** corresponds to page iPg is already set.
61444 */
61445 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
61446   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
61447   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
61448 }
61449 
61450 /*
61451 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
61452 */
61453 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
61454   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
61455   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
61456 }
61457 
61458 
61459 /*
61460 ** Add 1 to the reference count for page iPage.  If this is the second
61461 ** reference to the page, add an error message to pCheck->zErrMsg.
61462 ** Return 1 if there are 2 or more references to the page and 0 if
61463 ** if this is the first reference to the page.
61464 **
61465 ** Also check that the page number is in bounds.
61466 */
61467 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
61468   if( iPage==0 ) return 1;
61469   if( iPage>pCheck->nPage ){
61470     checkAppendMsg(pCheck, "invalid page number %d", iPage);
61471     return 1;
61472   }
61473   if( getPageReferenced(pCheck, iPage) ){
61474     checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
61475     return 1;
61476   }
61477   setPageReferenced(pCheck, iPage);
61478   return 0;
61479 }
61480 
61481 #ifndef SQLITE_OMIT_AUTOVACUUM
61482 /*
61483 ** Check that the entry in the pointer-map for page iChild maps to
61484 ** page iParent, pointer type ptrType. If not, append an error message
61485 ** to pCheck.
61486 */
61487 static void checkPtrmap(
61488   IntegrityCk *pCheck,   /* Integrity check context */
61489   Pgno iChild,           /* Child page number */
61490   u8 eType,              /* Expected pointer map type */
61491   Pgno iParent           /* Expected pointer map parent page number */
61492 ){
61493   int rc;
61494   u8 ePtrmapType;
61495   Pgno iPtrmapParent;
61496 
61497   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
61498   if( rc!=SQLITE_OK ){
61499     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
61500     checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
61501     return;
61502   }
61503 
61504   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
61505     checkAppendMsg(pCheck,
61506       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
61507       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
61508   }
61509 }
61510 #endif
61511 
61512 /*
61513 ** Check the integrity of the freelist or of an overflow page list.
61514 ** Verify that the number of pages on the list is N.
61515 */
61516 static void checkList(
61517   IntegrityCk *pCheck,  /* Integrity checking context */
61518   int isFreeList,       /* True for a freelist.  False for overflow page list */
61519   int iPage,            /* Page number for first page in the list */
61520   int N                 /* Expected number of pages in the list */
61521 ){
61522   int i;
61523   int expected = N;
61524   int iFirst = iPage;
61525   while( N-- > 0 && pCheck->mxErr ){
61526     DbPage *pOvflPage;
61527     unsigned char *pOvflData;
61528     if( iPage<1 ){
61529       checkAppendMsg(pCheck,
61530          "%d of %d pages missing from overflow list starting at %d",
61531           N+1, expected, iFirst);
61532       break;
61533     }
61534     if( checkRef(pCheck, iPage) ) break;
61535     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
61536       checkAppendMsg(pCheck, "failed to get page %d", iPage);
61537       break;
61538     }
61539     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
61540     if( isFreeList ){
61541       int n = get4byte(&pOvflData[4]);
61542 #ifndef SQLITE_OMIT_AUTOVACUUM
61543       if( pCheck->pBt->autoVacuum ){
61544         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
61545       }
61546 #endif
61547       if( n>(int)pCheck->pBt->usableSize/4-2 ){
61548         checkAppendMsg(pCheck,
61549            "freelist leaf count too big on page %d", iPage);
61550         N--;
61551       }else{
61552         for(i=0; i<n; i++){
61553           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
61554 #ifndef SQLITE_OMIT_AUTOVACUUM
61555           if( pCheck->pBt->autoVacuum ){
61556             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
61557           }
61558 #endif
61559           checkRef(pCheck, iFreePage);
61560         }
61561         N -= n;
61562       }
61563     }
61564 #ifndef SQLITE_OMIT_AUTOVACUUM
61565     else{
61566       /* If this database supports auto-vacuum and iPage is not the last
61567       ** page in this overflow list, check that the pointer-map entry for
61568       ** the following page matches iPage.
61569       */
61570       if( pCheck->pBt->autoVacuum && N>0 ){
61571         i = get4byte(pOvflData);
61572         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
61573       }
61574     }
61575 #endif
61576     iPage = get4byte(pOvflData);
61577     sqlite3PagerUnref(pOvflPage);
61578   }
61579 }
61580 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
61581 
61582 /*
61583 ** An implementation of a min-heap.
61584 **
61585 ** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
61586 ** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
61587 ** and aHeap[N*2+1].
61588 **
61589 ** The heap property is this:  Every node is less than or equal to both
61590 ** of its daughter nodes.  A consequence of the heap property is that the
61591 ** root node aHeap[1] is always the minimum value currently in the heap.
61592 **
61593 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
61594 ** the heap, preserving the heap property.  The btreeHeapPull() routine
61595 ** removes the root element from the heap (the minimum value in the heap)
61596 ** and then moves other nodes around as necessary to preserve the heap
61597 ** property.
61598 **
61599 ** This heap is used for cell overlap and coverage testing.  Each u32
61600 ** entry represents the span of a cell or freeblock on a btree page.
61601 ** The upper 16 bits are the index of the first byte of a range and the
61602 ** lower 16 bits are the index of the last byte of that range.
61603 */
61604 static void btreeHeapInsert(u32 *aHeap, u32 x){
61605   u32 j, i = ++aHeap[0];
61606   aHeap[i] = x;
61607   while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
61608     x = aHeap[j];
61609     aHeap[j] = aHeap[i];
61610     aHeap[i] = x;
61611     i = j;
61612   }
61613 }
61614 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
61615   u32 j, i, x;
61616   if( (x = aHeap[0])==0 ) return 0;
61617   *pOut = aHeap[1];
61618   aHeap[1] = aHeap[x];
61619   aHeap[x] = 0xffffffff;
61620   aHeap[0]--;
61621   i = 1;
61622   while( (j = i*2)<=aHeap[0] ){
61623     if( aHeap[j]>aHeap[j+1] ) j++;
61624     if( aHeap[i]<aHeap[j] ) break;
61625     x = aHeap[i];
61626     aHeap[i] = aHeap[j];
61627     aHeap[j] = x;
61628     i = j;
61629   }
61630   return 1;
61631 }
61632 
61633 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
61634 /*
61635 ** Do various sanity checks on a single page of a tree.  Return
61636 ** the tree depth.  Root pages return 0.  Parents of root pages
61637 ** return 1, and so forth.
61638 **
61639 ** These checks are done:
61640 **
61641 **      1.  Make sure that cells and freeblocks do not overlap
61642 **          but combine to completely cover the page.
61643 **  NO  2.  Make sure cell keys are in order.
61644 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
61645 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
61646 **      5.  Check the integrity of overflow pages.
61647 **      6.  Recursively call checkTreePage on all children.
61648 **      7.  Verify that the depth of all children is the same.
61649 **      8.  Make sure this page is at least 33% full or else it is
61650 **          the root of the tree.
61651 */
61652 static int checkTreePage(
61653   IntegrityCk *pCheck,  /* Context for the sanity check */
61654   int iPage,            /* Page number of the page to check */
61655   i64 *pnParentMinKey,
61656   i64 *pnParentMaxKey
61657 ){
61658   MemPage *pPage;
61659   int i, rc, depth, d2, pgno, cnt;
61660   int hdr, cellStart;
61661   int nCell;
61662   u8 *data;
61663   BtShared *pBt;
61664   int usableSize;
61665   u32 *heap = 0;
61666   u32 x, prev = 0;
61667   i64 nMinKey = 0;
61668   i64 nMaxKey = 0;
61669   const char *saved_zPfx = pCheck->zPfx;
61670   int saved_v1 = pCheck->v1;
61671   int saved_v2 = pCheck->v2;
61672 
61673   /* Check that the page exists
61674   */
61675   pBt = pCheck->pBt;
61676   usableSize = pBt->usableSize;
61677   if( iPage==0 ) return 0;
61678   if( checkRef(pCheck, iPage) ) return 0;
61679   pCheck->zPfx = "Page %d: ";
61680   pCheck->v1 = iPage;
61681   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
61682     checkAppendMsg(pCheck,
61683        "unable to get the page. error code=%d", rc);
61684     depth = -1;
61685     goto end_of_check;
61686   }
61687 
61688   /* Clear MemPage.isInit to make sure the corruption detection code in
61689   ** btreeInitPage() is executed.  */
61690   pPage->isInit = 0;
61691   if( (rc = btreeInitPage(pPage))!=0 ){
61692     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
61693     checkAppendMsg(pCheck,
61694                    "btreeInitPage() returns error code %d", rc);
61695     releasePage(pPage);
61696     depth = -1;
61697     goto end_of_check;
61698   }
61699 
61700   /* Check out all the cells.
61701   */
61702   depth = 0;
61703   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
61704     u8 *pCell;
61705     u32 sz;
61706     CellInfo info;
61707 
61708     /* Check payload overflow pages
61709     */
61710     pCheck->zPfx = "On tree page %d cell %d: ";
61711     pCheck->v1 = iPage;
61712     pCheck->v2 = i;
61713     pCell = findCell(pPage,i);
61714     btreeParseCellPtr(pPage, pCell, &info);
61715     sz = info.nPayload;
61716     /* For intKey pages, check that the keys are in order.
61717     */
61718     if( pPage->intKey ){
61719       if( i==0 ){
61720         nMinKey = nMaxKey = info.nKey;
61721       }else if( info.nKey <= nMaxKey ){
61722         checkAppendMsg(pCheck,
61723            "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
61724       }
61725       nMaxKey = info.nKey;
61726     }
61727     if( (sz>info.nLocal)
61728      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
61729     ){
61730       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
61731       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
61732 #ifndef SQLITE_OMIT_AUTOVACUUM
61733       if( pBt->autoVacuum ){
61734         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
61735       }
61736 #endif
61737       checkList(pCheck, 0, pgnoOvfl, nPage);
61738     }
61739 
61740     /* Check sanity of left child page.
61741     */
61742     if( !pPage->leaf ){
61743       pgno = get4byte(pCell);
61744 #ifndef SQLITE_OMIT_AUTOVACUUM
61745       if( pBt->autoVacuum ){
61746         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
61747       }
61748 #endif
61749       d2 = checkTreePage(pCheck, pgno, &nMinKey, i==0?NULL:&nMaxKey);
61750       if( i>0 && d2!=depth ){
61751         checkAppendMsg(pCheck, "Child page depth differs");
61752       }
61753       depth = d2;
61754     }
61755   }
61756 
61757   if( !pPage->leaf ){
61758     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
61759     pCheck->zPfx = "On page %d at right child: ";
61760     pCheck->v1 = iPage;
61761 #ifndef SQLITE_OMIT_AUTOVACUUM
61762     if( pBt->autoVacuum ){
61763       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
61764     }
61765 #endif
61766     checkTreePage(pCheck, pgno, NULL, !pPage->nCell?NULL:&nMaxKey);
61767   }
61768 
61769   /* For intKey leaf pages, check that the min/max keys are in order
61770   ** with any left/parent/right pages.
61771   */
61772   pCheck->zPfx = "Page %d: ";
61773   pCheck->v1 = iPage;
61774   if( pPage->leaf && pPage->intKey ){
61775     /* if we are a left child page */
61776     if( pnParentMinKey ){
61777       /* if we are the left most child page */
61778       if( !pnParentMaxKey ){
61779         if( nMaxKey > *pnParentMinKey ){
61780           checkAppendMsg(pCheck,
61781               "Rowid %lld out of order (max larger than parent min of %lld)",
61782               nMaxKey, *pnParentMinKey);
61783         }
61784       }else{
61785         if( nMinKey <= *pnParentMinKey ){
61786           checkAppendMsg(pCheck,
61787               "Rowid %lld out of order (min less than parent min of %lld)",
61788               nMinKey, *pnParentMinKey);
61789         }
61790         if( nMaxKey > *pnParentMaxKey ){
61791           checkAppendMsg(pCheck,
61792               "Rowid %lld out of order (max larger than parent max of %lld)",
61793               nMaxKey, *pnParentMaxKey);
61794         }
61795         *pnParentMinKey = nMaxKey;
61796       }
61797     /* else if we're a right child page */
61798     } else if( pnParentMaxKey ){
61799       if( nMinKey <= *pnParentMaxKey ){
61800         checkAppendMsg(pCheck,
61801             "Rowid %lld out of order (min less than parent max of %lld)",
61802             nMinKey, *pnParentMaxKey);
61803       }
61804     }
61805   }
61806 
61807   /* Check for complete coverage of the page
61808   */
61809   data = pPage->aData;
61810   hdr = pPage->hdrOffset;
61811   heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
61812   pCheck->zPfx = 0;
61813   if( heap==0 ){
61814     pCheck->mallocFailed = 1;
61815   }else{
61816     int contentOffset = get2byteNotZero(&data[hdr+5]);
61817     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
61818     heap[0] = 0;
61819     btreeHeapInsert(heap, contentOffset-1);
61820     /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
61821     ** number of cells on the page. */
61822     nCell = get2byte(&data[hdr+3]);
61823     /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
61824     ** immediately follows the b-tree page header. */
61825     cellStart = hdr + 12 - 4*pPage->leaf;
61826     /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
61827     ** integer offsets to the cell contents. */
61828     for(i=0; i<nCell; i++){
61829       int pc = get2byte(&data[cellStart+i*2]);
61830       u32 size = 65536;
61831       if( pc<=usableSize-4 ){
61832         size = cellSizePtr(pPage, &data[pc]);
61833       }
61834       if( (int)(pc+size-1)>=usableSize ){
61835         pCheck->zPfx = 0;
61836         checkAppendMsg(pCheck,
61837             "Corruption detected in cell %d on page %d",i,iPage);
61838       }else{
61839         btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
61840       }
61841     }
61842     /* EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
61843     ** is the offset of the first freeblock, or zero if there are no
61844     ** freeblocks on the page. */
61845     i = get2byte(&data[hdr+1]);
61846     while( i>0 ){
61847       int size, j;
61848       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
61849       size = get2byte(&data[i+2]);
61850       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
61851       btreeHeapInsert(heap, (i<<16)|(i+size-1));
61852       /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
61853       ** big-endian integer which is the offset in the b-tree page of the next
61854       ** freeblock in the chain, or zero if the freeblock is the last on the
61855       ** chain. */
61856       j = get2byte(&data[i]);
61857       /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
61858       ** increasing offset. */
61859       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
61860       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
61861       i = j;
61862     }
61863     cnt = 0;
61864     assert( heap[0]>0 );
61865     assert( (heap[1]>>16)==0 );
61866     btreeHeapPull(heap,&prev);
61867     while( btreeHeapPull(heap,&x) ){
61868       if( (prev&0xffff)+1>(x>>16) ){
61869         checkAppendMsg(pCheck,
61870           "Multiple uses for byte %u of page %d", x>>16, iPage);
61871         break;
61872       }else{
61873         cnt += (x>>16) - (prev&0xffff) - 1;
61874         prev = x;
61875       }
61876     }
61877     cnt += usableSize - (prev&0xffff) - 1;
61878     /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
61879     ** is stored in the fifth field of the b-tree page header.
61880     ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
61881     ** number of fragmented free bytes within the cell content area.
61882     */
61883     if( heap[0]==0 && cnt!=data[hdr+7] ){
61884       checkAppendMsg(pCheck,
61885           "Fragmentation of %d bytes reported as %d on page %d",
61886           cnt, data[hdr+7], iPage);
61887     }
61888   }
61889   sqlite3PageFree(heap);
61890   releasePage(pPage);
61891 
61892 end_of_check:
61893   pCheck->zPfx = saved_zPfx;
61894   pCheck->v1 = saved_v1;
61895   pCheck->v2 = saved_v2;
61896   return depth+1;
61897 }
61898 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
61899 
61900 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
61901 /*
61902 ** This routine does a complete check of the given BTree file.  aRoot[] is
61903 ** an array of pages numbers were each page number is the root page of
61904 ** a table.  nRoot is the number of entries in aRoot.
61905 **
61906 ** A read-only or read-write transaction must be opened before calling
61907 ** this function.
61908 **
61909 ** Write the number of error seen in *pnErr.  Except for some memory
61910 ** allocation errors,  an error message held in memory obtained from
61911 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
61912 ** returned.  If a memory allocation error occurs, NULL is returned.
61913 */
61914 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
61915   Btree *p,     /* The btree to be checked */
61916   int *aRoot,   /* An array of root pages numbers for individual trees */
61917   int nRoot,    /* Number of entries in aRoot[] */
61918   int mxErr,    /* Stop reporting errors after this many */
61919   int *pnErr    /* Write number of errors seen to this variable */
61920 ){
61921   Pgno i;
61922   int nRef;
61923   IntegrityCk sCheck;
61924   BtShared *pBt = p->pBt;
61925   char zErr[100];
61926 
61927   sqlite3BtreeEnter(p);
61928   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
61929   nRef = sqlite3PagerRefcount(pBt->pPager);
61930   sCheck.pBt = pBt;
61931   sCheck.pPager = pBt->pPager;
61932   sCheck.nPage = btreePagecount(sCheck.pBt);
61933   sCheck.mxErr = mxErr;
61934   sCheck.nErr = 0;
61935   sCheck.mallocFailed = 0;
61936   sCheck.zPfx = 0;
61937   sCheck.v1 = 0;
61938   sCheck.v2 = 0;
61939   *pnErr = 0;
61940   if( sCheck.nPage==0 ){
61941     sqlite3BtreeLeave(p);
61942     return 0;
61943   }
61944 
61945   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
61946   if( !sCheck.aPgRef ){
61947     *pnErr = 1;
61948     sqlite3BtreeLeave(p);
61949     return 0;
61950   }
61951   i = PENDING_BYTE_PAGE(pBt);
61952   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
61953   sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
61954 
61955   /* Check the integrity of the freelist
61956   */
61957   sCheck.zPfx = "Main freelist: ";
61958   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
61959             get4byte(&pBt->pPage1->aData[36]));
61960   sCheck.zPfx = 0;
61961 
61962   /* Check all the tables.
61963   */
61964   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
61965     if( aRoot[i]==0 ) continue;
61966 #ifndef SQLITE_OMIT_AUTOVACUUM
61967     if( pBt->autoVacuum && aRoot[i]>1 ){
61968       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
61969     }
61970 #endif
61971     sCheck.zPfx = "List of tree roots: ";
61972     checkTreePage(&sCheck, aRoot[i], NULL, NULL);
61973     sCheck.zPfx = 0;
61974   }
61975 
61976   /* Make sure every page in the file is referenced
61977   */
61978   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
61979 #ifdef SQLITE_OMIT_AUTOVACUUM
61980     if( getPageReferenced(&sCheck, i)==0 ){
61981       checkAppendMsg(&sCheck, "Page %d is never used", i);
61982     }
61983 #else
61984     /* If the database supports auto-vacuum, make sure no tables contain
61985     ** references to pointer-map pages.
61986     */
61987     if( getPageReferenced(&sCheck, i)==0 &&
61988        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
61989       checkAppendMsg(&sCheck, "Page %d is never used", i);
61990     }
61991     if( getPageReferenced(&sCheck, i)!=0 &&
61992        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
61993       checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
61994     }
61995 #endif
61996   }
61997 
61998   /* Make sure this analysis did not leave any unref() pages.
61999   ** This is an internal consistency check; an integrity check
62000   ** of the integrity check.
62001   */
62002   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
62003     checkAppendMsg(&sCheck,
62004       "Outstanding page count goes from %d to %d during this analysis",
62005       nRef, sqlite3PagerRefcount(pBt->pPager)
62006     );
62007   }
62008 
62009   /* Clean  up and report errors.
62010   */
62011   sqlite3BtreeLeave(p);
62012   sqlite3_free(sCheck.aPgRef);
62013   if( sCheck.mallocFailed ){
62014     sqlite3StrAccumReset(&sCheck.errMsg);
62015     *pnErr = sCheck.nErr+1;
62016     return 0;
62017   }
62018   *pnErr = sCheck.nErr;
62019   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
62020   return sqlite3StrAccumFinish(&sCheck.errMsg);
62021 }
62022 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
62023 
62024 /*
62025 ** Return the full pathname of the underlying database file.  Return
62026 ** an empty string if the database is in-memory or a TEMP database.
62027 **
62028 ** The pager filename is invariant as long as the pager is
62029 ** open so it is safe to access without the BtShared mutex.
62030 */
62031 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
62032   assert( p->pBt->pPager!=0 );
62033   return sqlite3PagerFilename(p->pBt->pPager, 1);
62034 }
62035 
62036 /*
62037 ** Return the pathname of the journal file for this database. The return
62038 ** value of this routine is the same regardless of whether the journal file
62039 ** has been created or not.
62040 **
62041 ** The pager journal filename is invariant as long as the pager is
62042 ** open so it is safe to access without the BtShared mutex.
62043 */
62044 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
62045   assert( p->pBt->pPager!=0 );
62046   return sqlite3PagerJournalname(p->pBt->pPager);
62047 }
62048 
62049 /*
62050 ** Return non-zero if a transaction is active.
62051 */
62052 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
62053   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
62054   return (p && (p->inTrans==TRANS_WRITE));
62055 }
62056 
62057 #ifndef SQLITE_OMIT_WAL
62058 /*
62059 ** Run a checkpoint on the Btree passed as the first argument.
62060 **
62061 ** Return SQLITE_LOCKED if this or any other connection has an open
62062 ** transaction on the shared-cache the argument Btree is connected to.
62063 **
62064 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
62065 */
62066 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
62067   int rc = SQLITE_OK;
62068   if( p ){
62069     BtShared *pBt = p->pBt;
62070     sqlite3BtreeEnter(p);
62071     if( pBt->inTransaction!=TRANS_NONE ){
62072       rc = SQLITE_LOCKED;
62073     }else{
62074       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
62075     }
62076     sqlite3BtreeLeave(p);
62077   }
62078   return rc;
62079 }
62080 #endif
62081 
62082 /*
62083 ** Return non-zero if a read (or write) transaction is active.
62084 */
62085 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
62086   assert( p );
62087   assert( sqlite3_mutex_held(p->db->mutex) );
62088   return p->inTrans!=TRANS_NONE;
62089 }
62090 
62091 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
62092   assert( p );
62093   assert( sqlite3_mutex_held(p->db->mutex) );
62094   return p->nBackup!=0;
62095 }
62096 
62097 /*
62098 ** This function returns a pointer to a blob of memory associated with
62099 ** a single shared-btree. The memory is used by client code for its own
62100 ** purposes (for example, to store a high-level schema associated with
62101 ** the shared-btree). The btree layer manages reference counting issues.
62102 **
62103 ** The first time this is called on a shared-btree, nBytes bytes of memory
62104 ** are allocated, zeroed, and returned to the caller. For each subsequent
62105 ** call the nBytes parameter is ignored and a pointer to the same blob
62106 ** of memory returned.
62107 **
62108 ** If the nBytes parameter is 0 and the blob of memory has not yet been
62109 ** allocated, a null pointer is returned. If the blob has already been
62110 ** allocated, it is returned as normal.
62111 **
62112 ** Just before the shared-btree is closed, the function passed as the
62113 ** xFree argument when the memory allocation was made is invoked on the
62114 ** blob of allocated memory. The xFree function should not call sqlite3_free()
62115 ** on the memory, the btree layer does that.
62116 */
62117 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
62118   BtShared *pBt = p->pBt;
62119   sqlite3BtreeEnter(p);
62120   if( !pBt->pSchema && nBytes ){
62121     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
62122     pBt->xFreeSchema = xFree;
62123   }
62124   sqlite3BtreeLeave(p);
62125   return pBt->pSchema;
62126 }
62127 
62128 /*
62129 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
62130 ** btree as the argument handle holds an exclusive lock on the
62131 ** sqlite_master table. Otherwise SQLITE_OK.
62132 */
62133 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
62134   int rc;
62135   assert( sqlite3_mutex_held(p->db->mutex) );
62136   sqlite3BtreeEnter(p);
62137   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
62138   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
62139   sqlite3BtreeLeave(p);
62140   return rc;
62141 }
62142 
62143 
62144 #ifndef SQLITE_OMIT_SHARED_CACHE
62145 /*
62146 ** Obtain a lock on the table whose root page is iTab.  The
62147 ** lock is a write lock if isWritelock is true or a read lock
62148 ** if it is false.
62149 */
62150 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
62151   int rc = SQLITE_OK;
62152   assert( p->inTrans!=TRANS_NONE );
62153   if( p->sharable ){
62154     u8 lockType = READ_LOCK + isWriteLock;
62155     assert( READ_LOCK+1==WRITE_LOCK );
62156     assert( isWriteLock==0 || isWriteLock==1 );
62157 
62158     sqlite3BtreeEnter(p);
62159     rc = querySharedCacheTableLock(p, iTab, lockType);
62160     if( rc==SQLITE_OK ){
62161       rc = setSharedCacheTableLock(p, iTab, lockType);
62162     }
62163     sqlite3BtreeLeave(p);
62164   }
62165   return rc;
62166 }
62167 #endif
62168 
62169 #ifndef SQLITE_OMIT_INCRBLOB
62170 /*
62171 ** Argument pCsr must be a cursor opened for writing on an
62172 ** INTKEY table currently pointing at a valid table entry.
62173 ** This function modifies the data stored as part of that entry.
62174 **
62175 ** Only the data content may only be modified, it is not possible to
62176 ** change the length of the data stored. If this function is called with
62177 ** parameters that attempt to write past the end of the existing data,
62178 ** no modifications are made and SQLITE_CORRUPT is returned.
62179 */
62180 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
62181   int rc;
62182   assert( cursorHoldsMutex(pCsr) );
62183   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
62184   assert( pCsr->curFlags & BTCF_Incrblob );
62185 
62186   rc = restoreCursorPosition(pCsr);
62187   if( rc!=SQLITE_OK ){
62188     return rc;
62189   }
62190   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
62191   if( pCsr->eState!=CURSOR_VALID ){
62192     return SQLITE_ABORT;
62193   }
62194 
62195   /* Save the positions of all other cursors open on this table. This is
62196   ** required in case any of them are holding references to an xFetch
62197   ** version of the b-tree page modified by the accessPayload call below.
62198   **
62199   ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
62200   ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
62201   ** saveAllCursors can only return SQLITE_OK.
62202   */
62203   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
62204   assert( rc==SQLITE_OK );
62205 
62206   /* Check some assumptions:
62207   **   (a) the cursor is open for writing,
62208   **   (b) there is a read/write transaction open,
62209   **   (c) the connection holds a write-lock on the table (if required),
62210   **   (d) there are no conflicting read-locks, and
62211   **   (e) the cursor points at a valid row of an intKey table.
62212   */
62213   if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
62214     return SQLITE_READONLY;
62215   }
62216   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
62217               && pCsr->pBt->inTransaction==TRANS_WRITE );
62218   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
62219   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
62220   assert( pCsr->apPage[pCsr->iPage]->intKey );
62221 
62222   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
62223 }
62224 
62225 /*
62226 ** Mark this cursor as an incremental blob cursor.
62227 */
62228 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
62229   pCur->curFlags |= BTCF_Incrblob;
62230 }
62231 #endif
62232 
62233 /*
62234 ** Set both the "read version" (single byte at byte offset 18) and
62235 ** "write version" (single byte at byte offset 19) fields in the database
62236 ** header to iVersion.
62237 */
62238 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
62239   BtShared *pBt = pBtree->pBt;
62240   int rc;                         /* Return code */
62241 
62242   assert( iVersion==1 || iVersion==2 );
62243 
62244   /* If setting the version fields to 1, do not automatically open the
62245   ** WAL connection, even if the version fields are currently set to 2.
62246   */
62247   pBt->btsFlags &= ~BTS_NO_WAL;
62248   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
62249 
62250   rc = sqlite3BtreeBeginTrans(pBtree, 0);
62251   if( rc==SQLITE_OK ){
62252     u8 *aData = pBt->pPage1->aData;
62253     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
62254       rc = sqlite3BtreeBeginTrans(pBtree, 2);
62255       if( rc==SQLITE_OK ){
62256         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
62257         if( rc==SQLITE_OK ){
62258           aData[18] = (u8)iVersion;
62259           aData[19] = (u8)iVersion;
62260         }
62261       }
62262     }
62263   }
62264 
62265   pBt->btsFlags &= ~BTS_NO_WAL;
62266   return rc;
62267 }
62268 
62269 /*
62270 ** set the mask of hint flags for cursor pCsr.
62271 */
62272 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
62273   assert( mask==BTREE_BULKLOAD || mask==BTREE_SEEK_EQ || mask==0 );
62274   pCsr->hints = mask;
62275 }
62276 
62277 #ifdef SQLITE_DEBUG
62278 /*
62279 ** Return true if the cursor has a hint specified.  This routine is
62280 ** only used from within assert() statements
62281 */
62282 SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
62283   return (pCsr->hints & mask)!=0;
62284 }
62285 #endif
62286 
62287 /*
62288 ** Return true if the given Btree is read-only.
62289 */
62290 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
62291   return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
62292 }
62293 
62294 /*
62295 ** Return the size of the header added to each page by this module.
62296 */
62297 SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
62298 
62299 /************** End of btree.c ***********************************************/
62300 /************** Begin file backup.c ******************************************/
62301 /*
62302 ** 2009 January 28
62303 **
62304 ** The author disclaims copyright to this source code.  In place of
62305 ** a legal notice, here is a blessing:
62306 **
62307 **    May you do good and not evil.
62308 **    May you find forgiveness for yourself and forgive others.
62309 **    May you share freely, never taking more than you give.
62310 **
62311 *************************************************************************
62312 ** This file contains the implementation of the sqlite3_backup_XXX()
62313 ** API functions and the related features.
62314 */
62315 
62316 /*
62317 ** Structure allocated for each backup operation.
62318 */
62319 struct sqlite3_backup {
62320   sqlite3* pDestDb;        /* Destination database handle */
62321   Btree *pDest;            /* Destination b-tree file */
62322   u32 iDestSchema;         /* Original schema cookie in destination */
62323   int bDestLocked;         /* True once a write-transaction is open on pDest */
62324 
62325   Pgno iNext;              /* Page number of the next source page to copy */
62326   sqlite3* pSrcDb;         /* Source database handle */
62327   Btree *pSrc;             /* Source b-tree file */
62328 
62329   int rc;                  /* Backup process error code */
62330 
62331   /* These two variables are set by every call to backup_step(). They are
62332   ** read by calls to backup_remaining() and backup_pagecount().
62333   */
62334   Pgno nRemaining;         /* Number of pages left to copy */
62335   Pgno nPagecount;         /* Total number of pages to copy */
62336 
62337   int isAttached;          /* True once backup has been registered with pager */
62338   sqlite3_backup *pNext;   /* Next backup associated with source pager */
62339 };
62340 
62341 /*
62342 ** THREAD SAFETY NOTES:
62343 **
62344 **   Once it has been created using backup_init(), a single sqlite3_backup
62345 **   structure may be accessed via two groups of thread-safe entry points:
62346 **
62347 **     * Via the sqlite3_backup_XXX() API function backup_step() and
62348 **       backup_finish(). Both these functions obtain the source database
62349 **       handle mutex and the mutex associated with the source BtShared
62350 **       structure, in that order.
62351 **
62352 **     * Via the BackupUpdate() and BackupRestart() functions, which are
62353 **       invoked by the pager layer to report various state changes in
62354 **       the page cache associated with the source database. The mutex
62355 **       associated with the source database BtShared structure will always
62356 **       be held when either of these functions are invoked.
62357 **
62358 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
62359 **   backup_pagecount() are not thread-safe functions. If they are called
62360 **   while some other thread is calling backup_step() or backup_finish(),
62361 **   the values returned may be invalid. There is no way for a call to
62362 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
62363 **   or backup_pagecount().
62364 **
62365 **   Depending on the SQLite configuration, the database handles and/or
62366 **   the Btree objects may have their own mutexes that require locking.
62367 **   Non-sharable Btrees (in-memory databases for example), do not have
62368 **   associated mutexes.
62369 */
62370 
62371 /*
62372 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
62373 ** in connection handle pDb. If such a database cannot be found, return
62374 ** a NULL pointer and write an error message to pErrorDb.
62375 **
62376 ** If the "temp" database is requested, it may need to be opened by this
62377 ** function. If an error occurs while doing so, return 0 and write an
62378 ** error message to pErrorDb.
62379 */
62380 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
62381   int i = sqlite3FindDbName(pDb, zDb);
62382 
62383   if( i==1 ){
62384     Parse *pParse;
62385     int rc = 0;
62386     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
62387     if( pParse==0 ){
62388       sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
62389       rc = SQLITE_NOMEM;
62390     }else{
62391       pParse->db = pDb;
62392       if( sqlite3OpenTempDatabase(pParse) ){
62393         sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
62394         rc = SQLITE_ERROR;
62395       }
62396       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
62397       sqlite3ParserReset(pParse);
62398       sqlite3StackFree(pErrorDb, pParse);
62399     }
62400     if( rc ){
62401       return 0;
62402     }
62403   }
62404 
62405   if( i<0 ){
62406     sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
62407     return 0;
62408   }
62409 
62410   return pDb->aDb[i].pBt;
62411 }
62412 
62413 /*
62414 ** Attempt to set the page size of the destination to match the page size
62415 ** of the source.
62416 */
62417 static int setDestPgsz(sqlite3_backup *p){
62418   int rc;
62419   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
62420   return rc;
62421 }
62422 
62423 /*
62424 ** Check that there is no open read-transaction on the b-tree passed as the
62425 ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
62426 ** is an open read-transaction, return SQLITE_ERROR and leave an error
62427 ** message in database handle db.
62428 */
62429 static int checkReadTransaction(sqlite3 *db, Btree *p){
62430   if( sqlite3BtreeIsInReadTrans(p) ){
62431     sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
62432     return SQLITE_ERROR;
62433   }
62434   return SQLITE_OK;
62435 }
62436 
62437 /*
62438 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
62439 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
62440 ** a pointer to the new sqlite3_backup object.
62441 **
62442 ** If an error occurs, NULL is returned and an error code and error message
62443 ** stored in database handle pDestDb.
62444 */
62445 SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
62446   sqlite3* pDestDb,                     /* Database to write to */
62447   const char *zDestDb,                  /* Name of database within pDestDb */
62448   sqlite3* pSrcDb,                      /* Database connection to read from */
62449   const char *zSrcDb                    /* Name of database within pSrcDb */
62450 ){
62451   sqlite3_backup *p;                    /* Value to return */
62452 
62453 #ifdef SQLITE_ENABLE_API_ARMOR
62454   if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
62455     (void)SQLITE_MISUSE_BKPT;
62456     return 0;
62457   }
62458 #endif
62459 
62460   /* Lock the source database handle. The destination database
62461   ** handle is not locked in this routine, but it is locked in
62462   ** sqlite3_backup_step(). The user is required to ensure that no
62463   ** other thread accesses the destination handle for the duration
62464   ** of the backup operation.  Any attempt to use the destination
62465   ** database connection while a backup is in progress may cause
62466   ** a malfunction or a deadlock.
62467   */
62468   sqlite3_mutex_enter(pSrcDb->mutex);
62469   sqlite3_mutex_enter(pDestDb->mutex);
62470 
62471   if( pSrcDb==pDestDb ){
62472     sqlite3ErrorWithMsg(
62473         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
62474     );
62475     p = 0;
62476   }else {
62477     /* Allocate space for a new sqlite3_backup object...
62478     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
62479     ** call to sqlite3_backup_init() and is destroyed by a call to
62480     ** sqlite3_backup_finish(). */
62481     p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
62482     if( !p ){
62483       sqlite3Error(pDestDb, SQLITE_NOMEM);
62484     }
62485   }
62486 
62487   /* If the allocation succeeded, populate the new object. */
62488   if( p ){
62489     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
62490     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
62491     p->pDestDb = pDestDb;
62492     p->pSrcDb = pSrcDb;
62493     p->iNext = 1;
62494     p->isAttached = 0;
62495 
62496     if( 0==p->pSrc || 0==p->pDest
62497      || setDestPgsz(p)==SQLITE_NOMEM
62498      || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
62499      ){
62500       /* One (or both) of the named databases did not exist or an OOM
62501       ** error was hit. Or there is a transaction open on the destination
62502       ** database. The error has already been written into the pDestDb
62503       ** handle. All that is left to do here is free the sqlite3_backup
62504       ** structure.  */
62505       sqlite3_free(p);
62506       p = 0;
62507     }
62508   }
62509   if( p ){
62510     p->pSrc->nBackup++;
62511   }
62512 
62513   sqlite3_mutex_leave(pDestDb->mutex);
62514   sqlite3_mutex_leave(pSrcDb->mutex);
62515   return p;
62516 }
62517 
62518 /*
62519 ** Argument rc is an SQLite error code. Return true if this error is
62520 ** considered fatal if encountered during a backup operation. All errors
62521 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
62522 */
62523 static int isFatalError(int rc){
62524   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
62525 }
62526 
62527 /*
62528 ** Parameter zSrcData points to a buffer containing the data for
62529 ** page iSrcPg from the source database. Copy this data into the
62530 ** destination database.
62531 */
62532 static int backupOnePage(
62533   sqlite3_backup *p,              /* Backup handle */
62534   Pgno iSrcPg,                    /* Source database page to backup */
62535   const u8 *zSrcData,             /* Source database page data */
62536   int bUpdate                     /* True for an update, false otherwise */
62537 ){
62538   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
62539   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
62540   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
62541   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
62542   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
62543 #ifdef SQLITE_HAS_CODEC
62544   /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
62545   ** guaranteed that the shared-mutex is held by this thread, handle
62546   ** p->pSrc may not actually be the owner.  */
62547   int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
62548   int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
62549 #endif
62550   int rc = SQLITE_OK;
62551   i64 iOff;
62552 
62553   assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
62554   assert( p->bDestLocked );
62555   assert( !isFatalError(p->rc) );
62556   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
62557   assert( zSrcData );
62558 
62559   /* Catch the case where the destination is an in-memory database and the
62560   ** page sizes of the source and destination differ.
62561   */
62562   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
62563     rc = SQLITE_READONLY;
62564   }
62565 
62566 #ifdef SQLITE_HAS_CODEC
62567   /* Backup is not possible if the page size of the destination is changing
62568   ** and a codec is in use.
62569   */
62570   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
62571     rc = SQLITE_READONLY;
62572   }
62573 
62574   /* Backup is not possible if the number of bytes of reserve space differ
62575   ** between source and destination.  If there is a difference, try to
62576   ** fix the destination to agree with the source.  If that is not possible,
62577   ** then the backup cannot proceed.
62578   */
62579   if( nSrcReserve!=nDestReserve ){
62580     u32 newPgsz = nSrcPgsz;
62581     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
62582     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
62583   }
62584 #endif
62585 
62586   /* This loop runs once for each destination page spanned by the source
62587   ** page. For each iteration, variable iOff is set to the byte offset
62588   ** of the destination page.
62589   */
62590   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
62591     DbPage *pDestPg = 0;
62592     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
62593     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
62594     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
62595      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
62596     ){
62597       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
62598       u8 *zDestData = sqlite3PagerGetData(pDestPg);
62599       u8 *zOut = &zDestData[iOff%nDestPgsz];
62600 
62601       /* Copy the data from the source page into the destination page.
62602       ** Then clear the Btree layer MemPage.isInit flag. Both this module
62603       ** and the pager code use this trick (clearing the first byte
62604       ** of the page 'extra' space to invalidate the Btree layers
62605       ** cached parse of the page). MemPage.isInit is marked
62606       ** "MUST BE FIRST" for this purpose.
62607       */
62608       memcpy(zOut, zIn, nCopy);
62609       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
62610       if( iOff==0 && bUpdate==0 ){
62611         sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
62612       }
62613     }
62614     sqlite3PagerUnref(pDestPg);
62615   }
62616 
62617   return rc;
62618 }
62619 
62620 /*
62621 ** If pFile is currently larger than iSize bytes, then truncate it to
62622 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
62623 ** this function is a no-op.
62624 **
62625 ** Return SQLITE_OK if everything is successful, or an SQLite error
62626 ** code if an error occurs.
62627 */
62628 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
62629   i64 iCurrent;
62630   int rc = sqlite3OsFileSize(pFile, &iCurrent);
62631   if( rc==SQLITE_OK && iCurrent>iSize ){
62632     rc = sqlite3OsTruncate(pFile, iSize);
62633   }
62634   return rc;
62635 }
62636 
62637 /*
62638 ** Register this backup object with the associated source pager for
62639 ** callbacks when pages are changed or the cache invalidated.
62640 */
62641 static void attachBackupObject(sqlite3_backup *p){
62642   sqlite3_backup **pp;
62643   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
62644   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
62645   p->pNext = *pp;
62646   *pp = p;
62647   p->isAttached = 1;
62648 }
62649 
62650 /*
62651 ** Copy nPage pages from the source b-tree to the destination.
62652 */
62653 SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage){
62654   int rc;
62655   int destMode;       /* Destination journal mode */
62656   int pgszSrc = 0;    /* Source page size */
62657   int pgszDest = 0;   /* Destination page size */
62658 
62659 #ifdef SQLITE_ENABLE_API_ARMOR
62660   if( p==0 ) return SQLITE_MISUSE_BKPT;
62661 #endif
62662   sqlite3_mutex_enter(p->pSrcDb->mutex);
62663   sqlite3BtreeEnter(p->pSrc);
62664   if( p->pDestDb ){
62665     sqlite3_mutex_enter(p->pDestDb->mutex);
62666   }
62667 
62668   rc = p->rc;
62669   if( !isFatalError(rc) ){
62670     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
62671     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
62672     int ii;                            /* Iterator variable */
62673     int nSrcPage = -1;                 /* Size of source db in pages */
62674     int bCloseTrans = 0;               /* True if src db requires unlocking */
62675 
62676     /* If the source pager is currently in a write-transaction, return
62677     ** SQLITE_BUSY immediately.
62678     */
62679     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
62680       rc = SQLITE_BUSY;
62681     }else{
62682       rc = SQLITE_OK;
62683     }
62684 
62685     /* Lock the destination database, if it is not locked already. */
62686     if( SQLITE_OK==rc && p->bDestLocked==0
62687      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
62688     ){
62689       p->bDestLocked = 1;
62690       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
62691     }
62692 
62693     /* If there is no open read-transaction on the source database, open
62694     ** one now. If a transaction is opened here, then it will be closed
62695     ** before this function exits.
62696     */
62697     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
62698       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
62699       bCloseTrans = 1;
62700     }
62701 
62702     /* Do not allow backup if the destination database is in WAL mode
62703     ** and the page sizes are different between source and destination */
62704     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
62705     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
62706     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
62707     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
62708       rc = SQLITE_READONLY;
62709     }
62710 
62711     /* Now that there is a read-lock on the source database, query the
62712     ** source pager for the number of pages in the database.
62713     */
62714     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
62715     assert( nSrcPage>=0 );
62716     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
62717       const Pgno iSrcPg = p->iNext;                 /* Source page number */
62718       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
62719         DbPage *pSrcPg;                             /* Source page object */
62720         rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
62721                                  PAGER_GET_READONLY);
62722         if( rc==SQLITE_OK ){
62723           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
62724           sqlite3PagerUnref(pSrcPg);
62725         }
62726       }
62727       p->iNext++;
62728     }
62729     if( rc==SQLITE_OK ){
62730       p->nPagecount = nSrcPage;
62731       p->nRemaining = nSrcPage+1-p->iNext;
62732       if( p->iNext>(Pgno)nSrcPage ){
62733         rc = SQLITE_DONE;
62734       }else if( !p->isAttached ){
62735         attachBackupObject(p);
62736       }
62737     }
62738 
62739     /* Update the schema version field in the destination database. This
62740     ** is to make sure that the schema-version really does change in
62741     ** the case where the source and destination databases have the
62742     ** same schema version.
62743     */
62744     if( rc==SQLITE_DONE ){
62745       if( nSrcPage==0 ){
62746         rc = sqlite3BtreeNewDb(p->pDest);
62747         nSrcPage = 1;
62748       }
62749       if( rc==SQLITE_OK || rc==SQLITE_DONE ){
62750         rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
62751       }
62752       if( rc==SQLITE_OK ){
62753         if( p->pDestDb ){
62754           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
62755         }
62756         if( destMode==PAGER_JOURNALMODE_WAL ){
62757           rc = sqlite3BtreeSetVersion(p->pDest, 2);
62758         }
62759       }
62760       if( rc==SQLITE_OK ){
62761         int nDestTruncate;
62762         /* Set nDestTruncate to the final number of pages in the destination
62763         ** database. The complication here is that the destination page
62764         ** size may be different to the source page size.
62765         **
62766         ** If the source page size is smaller than the destination page size,
62767         ** round up. In this case the call to sqlite3OsTruncate() below will
62768         ** fix the size of the file. However it is important to call
62769         ** sqlite3PagerTruncateImage() here so that any pages in the
62770         ** destination file that lie beyond the nDestTruncate page mark are
62771         ** journalled by PagerCommitPhaseOne() before they are destroyed
62772         ** by the file truncation.
62773         */
62774         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
62775         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
62776         if( pgszSrc<pgszDest ){
62777           int ratio = pgszDest/pgszSrc;
62778           nDestTruncate = (nSrcPage+ratio-1)/ratio;
62779           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
62780             nDestTruncate--;
62781           }
62782         }else{
62783           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
62784         }
62785         assert( nDestTruncate>0 );
62786 
62787         if( pgszSrc<pgszDest ){
62788           /* If the source page-size is smaller than the destination page-size,
62789           ** two extra things may need to happen:
62790           **
62791           **   * The destination may need to be truncated, and
62792           **
62793           **   * Data stored on the pages immediately following the
62794           **     pending-byte page in the source database may need to be
62795           **     copied into the destination database.
62796           */
62797           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
62798           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
62799           Pgno iPg;
62800           int nDstPage;
62801           i64 iOff;
62802           i64 iEnd;
62803 
62804           assert( pFile );
62805           assert( nDestTruncate==0
62806               || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
62807                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
62808              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
62809           ));
62810 
62811           /* This block ensures that all data required to recreate the original
62812           ** database has been stored in the journal for pDestPager and the
62813           ** journal synced to disk. So at this point we may safely modify
62814           ** the database file in any way, knowing that if a power failure
62815           ** occurs, the original database will be reconstructed from the
62816           ** journal file.  */
62817           sqlite3PagerPagecount(pDestPager, &nDstPage);
62818           for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
62819             if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
62820               DbPage *pPg;
62821               rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
62822               if( rc==SQLITE_OK ){
62823                 rc = sqlite3PagerWrite(pPg);
62824                 sqlite3PagerUnref(pPg);
62825               }
62826             }
62827           }
62828           if( rc==SQLITE_OK ){
62829             rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
62830           }
62831 
62832           /* Write the extra pages and truncate the database file as required */
62833           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
62834           for(
62835             iOff=PENDING_BYTE+pgszSrc;
62836             rc==SQLITE_OK && iOff<iEnd;
62837             iOff+=pgszSrc
62838           ){
62839             PgHdr *pSrcPg = 0;
62840             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
62841             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
62842             if( rc==SQLITE_OK ){
62843               u8 *zData = sqlite3PagerGetData(pSrcPg);
62844               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
62845             }
62846             sqlite3PagerUnref(pSrcPg);
62847           }
62848           if( rc==SQLITE_OK ){
62849             rc = backupTruncateFile(pFile, iSize);
62850           }
62851 
62852           /* Sync the database file to disk. */
62853           if( rc==SQLITE_OK ){
62854             rc = sqlite3PagerSync(pDestPager, 0);
62855           }
62856         }else{
62857           sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
62858           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
62859         }
62860 
62861         /* Finish committing the transaction to the destination database. */
62862         if( SQLITE_OK==rc
62863          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
62864         ){
62865           rc = SQLITE_DONE;
62866         }
62867       }
62868     }
62869 
62870     /* If bCloseTrans is true, then this function opened a read transaction
62871     ** on the source database. Close the read transaction here. There is
62872     ** no need to check the return values of the btree methods here, as
62873     ** "committing" a read-only transaction cannot fail.
62874     */
62875     if( bCloseTrans ){
62876       TESTONLY( int rc2 );
62877       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
62878       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
62879       assert( rc2==SQLITE_OK );
62880     }
62881 
62882     if( rc==SQLITE_IOERR_NOMEM ){
62883       rc = SQLITE_NOMEM;
62884     }
62885     p->rc = rc;
62886   }
62887   if( p->pDestDb ){
62888     sqlite3_mutex_leave(p->pDestDb->mutex);
62889   }
62890   sqlite3BtreeLeave(p->pSrc);
62891   sqlite3_mutex_leave(p->pSrcDb->mutex);
62892   return rc;
62893 }
62894 
62895 /*
62896 ** Release all resources associated with an sqlite3_backup* handle.
62897 */
62898 SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p){
62899   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
62900   sqlite3 *pSrcDb;                     /* Source database connection */
62901   int rc;                              /* Value to return */
62902 
62903   /* Enter the mutexes */
62904   if( p==0 ) return SQLITE_OK;
62905   pSrcDb = p->pSrcDb;
62906   sqlite3_mutex_enter(pSrcDb->mutex);
62907   sqlite3BtreeEnter(p->pSrc);
62908   if( p->pDestDb ){
62909     sqlite3_mutex_enter(p->pDestDb->mutex);
62910   }
62911 
62912   /* Detach this backup from the source pager. */
62913   if( p->pDestDb ){
62914     p->pSrc->nBackup--;
62915   }
62916   if( p->isAttached ){
62917     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
62918     while( *pp!=p ){
62919       pp = &(*pp)->pNext;
62920     }
62921     *pp = p->pNext;
62922   }
62923 
62924   /* If a transaction is still open on the Btree, roll it back. */
62925   sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
62926 
62927   /* Set the error code of the destination database handle. */
62928   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
62929   if( p->pDestDb ){
62930     sqlite3Error(p->pDestDb, rc);
62931 
62932     /* Exit the mutexes and free the backup context structure. */
62933     sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
62934   }
62935   sqlite3BtreeLeave(p->pSrc);
62936   if( p->pDestDb ){
62937     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
62938     ** call to sqlite3_backup_init() and is destroyed by a call to
62939     ** sqlite3_backup_finish(). */
62940     sqlite3_free(p);
62941   }
62942   sqlite3LeaveMutexAndCloseZombie(pSrcDb);
62943   return rc;
62944 }
62945 
62946 /*
62947 ** Return the number of pages still to be backed up as of the most recent
62948 ** call to sqlite3_backup_step().
62949 */
62950 SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p){
62951 #ifdef SQLITE_ENABLE_API_ARMOR
62952   if( p==0 ){
62953     (void)SQLITE_MISUSE_BKPT;
62954     return 0;
62955   }
62956 #endif
62957   return p->nRemaining;
62958 }
62959 
62960 /*
62961 ** Return the total number of pages in the source database as of the most
62962 ** recent call to sqlite3_backup_step().
62963 */
62964 SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p){
62965 #ifdef SQLITE_ENABLE_API_ARMOR
62966   if( p==0 ){
62967     (void)SQLITE_MISUSE_BKPT;
62968     return 0;
62969   }
62970 #endif
62971   return p->nPagecount;
62972 }
62973 
62974 /*
62975 ** This function is called after the contents of page iPage of the
62976 ** source database have been modified. If page iPage has already been
62977 ** copied into the destination database, then the data written to the
62978 ** destination is now invalidated. The destination copy of iPage needs
62979 ** to be updated with the new data before the backup operation is
62980 ** complete.
62981 **
62982 ** It is assumed that the mutex associated with the BtShared object
62983 ** corresponding to the source database is held when this function is
62984 ** called.
62985 */
62986 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
62987   sqlite3_backup *p;                   /* Iterator variable */
62988   for(p=pBackup; p; p=p->pNext){
62989     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
62990     if( !isFatalError(p->rc) && iPage<p->iNext ){
62991       /* The backup process p has already copied page iPage. But now it
62992       ** has been modified by a transaction on the source pager. Copy
62993       ** the new data into the backup.
62994       */
62995       int rc;
62996       assert( p->pDestDb );
62997       sqlite3_mutex_enter(p->pDestDb->mutex);
62998       rc = backupOnePage(p, iPage, aData, 1);
62999       sqlite3_mutex_leave(p->pDestDb->mutex);
63000       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
63001       if( rc!=SQLITE_OK ){
63002         p->rc = rc;
63003       }
63004     }
63005   }
63006 }
63007 
63008 /*
63009 ** Restart the backup process. This is called when the pager layer
63010 ** detects that the database has been modified by an external database
63011 ** connection. In this case there is no way of knowing which of the
63012 ** pages that have been copied into the destination database are still
63013 ** valid and which are not, so the entire process needs to be restarted.
63014 **
63015 ** It is assumed that the mutex associated with the BtShared object
63016 ** corresponding to the source database is held when this function is
63017 ** called.
63018 */
63019 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
63020   sqlite3_backup *p;                   /* Iterator variable */
63021   for(p=pBackup; p; p=p->pNext){
63022     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
63023     p->iNext = 1;
63024   }
63025 }
63026 
63027 #ifndef SQLITE_OMIT_VACUUM
63028 /*
63029 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
63030 ** must be active for both files.
63031 **
63032 ** The size of file pTo may be reduced by this operation. If anything
63033 ** goes wrong, the transaction on pTo is rolled back. If successful, the
63034 ** transaction is committed before returning.
63035 */
63036 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
63037   int rc;
63038   sqlite3_file *pFd;              /* File descriptor for database pTo */
63039   sqlite3_backup b;
63040   sqlite3BtreeEnter(pTo);
63041   sqlite3BtreeEnter(pFrom);
63042 
63043   assert( sqlite3BtreeIsInTrans(pTo) );
63044   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
63045   if( pFd->pMethods ){
63046     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
63047     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
63048     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
63049     if( rc ) goto copy_finished;
63050   }
63051 
63052   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
63053   ** to 0. This is used by the implementations of sqlite3_backup_step()
63054   ** and sqlite3_backup_finish() to detect that they are being called
63055   ** from this function, not directly by the user.
63056   */
63057   memset(&b, 0, sizeof(b));
63058   b.pSrcDb = pFrom->db;
63059   b.pSrc = pFrom;
63060   b.pDest = pTo;
63061   b.iNext = 1;
63062 
63063   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
63064   ** file. By passing this as the number of pages to copy to
63065   ** sqlite3_backup_step(), we can guarantee that the copy finishes
63066   ** within a single call (unless an error occurs). The assert() statement
63067   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
63068   ** or an error code.
63069   */
63070   sqlite3_backup_step(&b, 0x7FFFFFFF);
63071   assert( b.rc!=SQLITE_OK );
63072   rc = sqlite3_backup_finish(&b);
63073   if( rc==SQLITE_OK ){
63074     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
63075   }else{
63076     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
63077   }
63078 
63079   assert( sqlite3BtreeIsInTrans(pTo)==0 );
63080 copy_finished:
63081   sqlite3BtreeLeave(pFrom);
63082   sqlite3BtreeLeave(pTo);
63083   return rc;
63084 }
63085 #endif /* SQLITE_OMIT_VACUUM */
63086 
63087 /************** End of backup.c **********************************************/
63088 /************** Begin file vdbemem.c *****************************************/
63089 /*
63090 ** 2004 May 26
63091 **
63092 ** The author disclaims copyright to this source code.  In place of
63093 ** a legal notice, here is a blessing:
63094 **
63095 **    May you do good and not evil.
63096 **    May you find forgiveness for yourself and forgive others.
63097 **    May you share freely, never taking more than you give.
63098 **
63099 *************************************************************************
63100 **
63101 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
63102 ** stores a single value in the VDBE.  Mem is an opaque structure visible
63103 ** only within the VDBE.  Interface routines refer to a Mem using the
63104 ** name sqlite_value
63105 */
63106 
63107 #ifdef SQLITE_DEBUG
63108 /*
63109 ** Check invariants on a Mem object.
63110 **
63111 ** This routine is intended for use inside of assert() statements, like
63112 ** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
63113 */
63114 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
63115   /* If MEM_Dyn is set then Mem.xDel!=0.
63116   ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
63117   */
63118   assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
63119 
63120   /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
63121   ** ensure that if Mem.szMalloc>0 then it is safe to do
63122   ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
63123   ** That saves a few cycles in inner loops. */
63124   assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
63125 
63126   /* Cannot be both MEM_Int and MEM_Real at the same time */
63127   assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
63128 
63129   /* The szMalloc field holds the correct memory allocation size */
63130   assert( p->szMalloc==0
63131        || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
63132 
63133   /* If p holds a string or blob, the Mem.z must point to exactly
63134   ** one of the following:
63135   **
63136   **   (1) Memory in Mem.zMalloc and managed by the Mem object
63137   **   (2) Memory to be freed using Mem.xDel
63138   **   (3) An ephemeral string or blob
63139   **   (4) A static string or blob
63140   */
63141   if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
63142     assert(
63143       ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
63144       ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
63145       ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
63146       ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
63147     );
63148   }
63149   return 1;
63150 }
63151 #endif
63152 
63153 
63154 /*
63155 ** If pMem is an object with a valid string representation, this routine
63156 ** ensures the internal encoding for the string representation is
63157 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
63158 **
63159 ** If pMem is not a string object, or the encoding of the string
63160 ** representation is already stored using the requested encoding, then this
63161 ** routine is a no-op.
63162 **
63163 ** SQLITE_OK is returned if the conversion is successful (or not required).
63164 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
63165 ** between formats.
63166 */
63167 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
63168 #ifndef SQLITE_OMIT_UTF16
63169   int rc;
63170 #endif
63171   assert( (pMem->flags&MEM_RowSet)==0 );
63172   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
63173            || desiredEnc==SQLITE_UTF16BE );
63174   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
63175     return SQLITE_OK;
63176   }
63177   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63178 #ifdef SQLITE_OMIT_UTF16
63179   return SQLITE_ERROR;
63180 #else
63181 
63182   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
63183   ** then the encoding of the value may not have changed.
63184   */
63185   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
63186   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
63187   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
63188   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
63189   return rc;
63190 #endif
63191 }
63192 
63193 /*
63194 ** Make sure pMem->z points to a writable allocation of at least
63195 ** min(n,32) bytes.
63196 **
63197 ** If the bPreserve argument is true, then copy of the content of
63198 ** pMem->z into the new allocation.  pMem must be either a string or
63199 ** blob if bPreserve is true.  If bPreserve is false, any prior content
63200 ** in pMem->z is discarded.
63201 */
63202 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
63203   assert( sqlite3VdbeCheckMemInvariants(pMem) );
63204   assert( (pMem->flags&MEM_RowSet)==0 );
63205 
63206   /* If the bPreserve flag is set to true, then the memory cell must already
63207   ** contain a valid string or blob value.  */
63208   assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
63209   testcase( bPreserve && pMem->z==0 );
63210 
63211   assert( pMem->szMalloc==0
63212        || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
63213   if( pMem->szMalloc<n ){
63214     if( n<32 ) n = 32;
63215     if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
63216       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
63217       bPreserve = 0;
63218     }else{
63219       if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
63220       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
63221     }
63222     if( pMem->zMalloc==0 ){
63223       sqlite3VdbeMemSetNull(pMem);
63224       pMem->z = 0;
63225       pMem->szMalloc = 0;
63226       return SQLITE_NOMEM;
63227     }else{
63228       pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
63229     }
63230   }
63231 
63232   if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
63233     memcpy(pMem->zMalloc, pMem->z, pMem->n);
63234   }
63235   if( (pMem->flags&MEM_Dyn)!=0 ){
63236     assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
63237     pMem->xDel((void *)(pMem->z));
63238   }
63239 
63240   pMem->z = pMem->zMalloc;
63241   pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
63242   return SQLITE_OK;
63243 }
63244 
63245 /*
63246 ** Change the pMem->zMalloc allocation to be at least szNew bytes.
63247 ** If pMem->zMalloc already meets or exceeds the requested size, this
63248 ** routine is a no-op.
63249 **
63250 ** Any prior string or blob content in the pMem object may be discarded.
63251 ** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
63252 ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
63253 ** values are preserved.
63254 **
63255 ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
63256 ** if unable to complete the resizing.
63257 */
63258 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
63259   assert( szNew>0 );
63260   assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
63261   if( pMem->szMalloc<szNew ){
63262     return sqlite3VdbeMemGrow(pMem, szNew, 0);
63263   }
63264   assert( (pMem->flags & MEM_Dyn)==0 );
63265   pMem->z = pMem->zMalloc;
63266   pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
63267   return SQLITE_OK;
63268 }
63269 
63270 /*
63271 ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
63272 ** MEM.zMalloc, where it can be safely written.
63273 **
63274 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
63275 */
63276 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
63277   int f;
63278   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63279   assert( (pMem->flags&MEM_RowSet)==0 );
63280   ExpandBlob(pMem);
63281   f = pMem->flags;
63282   if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
63283     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
63284       return SQLITE_NOMEM;
63285     }
63286     pMem->z[pMem->n] = 0;
63287     pMem->z[pMem->n+1] = 0;
63288     pMem->flags |= MEM_Term;
63289   }
63290   pMem->flags &= ~MEM_Ephem;
63291 #ifdef SQLITE_DEBUG
63292   pMem->pScopyFrom = 0;
63293 #endif
63294 
63295   return SQLITE_OK;
63296 }
63297 
63298 /*
63299 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
63300 ** blob stored in dynamically allocated space.
63301 */
63302 #ifndef SQLITE_OMIT_INCRBLOB
63303 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
63304   if( pMem->flags & MEM_Zero ){
63305     int nByte;
63306     assert( pMem->flags&MEM_Blob );
63307     assert( (pMem->flags&MEM_RowSet)==0 );
63308     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63309 
63310     /* Set nByte to the number of bytes required to store the expanded blob. */
63311     nByte = pMem->n + pMem->u.nZero;
63312     if( nByte<=0 ){
63313       nByte = 1;
63314     }
63315     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
63316       return SQLITE_NOMEM;
63317     }
63318 
63319     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
63320     pMem->n += pMem->u.nZero;
63321     pMem->flags &= ~(MEM_Zero|MEM_Term);
63322   }
63323   return SQLITE_OK;
63324 }
63325 #endif
63326 
63327 /*
63328 ** It is already known that pMem contains an unterminated string.
63329 ** Add the zero terminator.
63330 */
63331 static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
63332   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
63333     return SQLITE_NOMEM;
63334   }
63335   pMem->z[pMem->n] = 0;
63336   pMem->z[pMem->n+1] = 0;
63337   pMem->flags |= MEM_Term;
63338   return SQLITE_OK;
63339 }
63340 
63341 /*
63342 ** Make sure the given Mem is \u0000 terminated.
63343 */
63344 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
63345   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63346   testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
63347   testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
63348   if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
63349     return SQLITE_OK;   /* Nothing to do */
63350   }else{
63351     return vdbeMemAddTerminator(pMem);
63352   }
63353 }
63354 
63355 /*
63356 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
63357 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
63358 ** is a no-op.
63359 **
63360 ** Existing representations MEM_Int and MEM_Real are invalidated if
63361 ** bForce is true but are retained if bForce is false.
63362 **
63363 ** A MEM_Null value will never be passed to this function. This function is
63364 ** used for converting values to text for returning to the user (i.e. via
63365 ** sqlite3_value_text()), or for ensuring that values to be used as btree
63366 ** keys are strings. In the former case a NULL pointer is returned the
63367 ** user and the latter is an internal programming error.
63368 */
63369 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
63370   int fg = pMem->flags;
63371   const int nByte = 32;
63372 
63373   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63374   assert( !(fg&MEM_Zero) );
63375   assert( !(fg&(MEM_Str|MEM_Blob)) );
63376   assert( fg&(MEM_Int|MEM_Real) );
63377   assert( (pMem->flags&MEM_RowSet)==0 );
63378   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
63379 
63380 
63381   if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
63382     return SQLITE_NOMEM;
63383   }
63384 
63385   /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
63386   ** string representation of the value. Then, if the required encoding
63387   ** is UTF-16le or UTF-16be do a translation.
63388   **
63389   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
63390   */
63391   if( fg & MEM_Int ){
63392     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
63393   }else{
63394     assert( fg & MEM_Real );
63395     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
63396   }
63397   pMem->n = sqlite3Strlen30(pMem->z);
63398   pMem->enc = SQLITE_UTF8;
63399   pMem->flags |= MEM_Str|MEM_Term;
63400   if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
63401   sqlite3VdbeChangeEncoding(pMem, enc);
63402   return SQLITE_OK;
63403 }
63404 
63405 /*
63406 ** Memory cell pMem contains the context of an aggregate function.
63407 ** This routine calls the finalize method for that function.  The
63408 ** result of the aggregate is stored back into pMem.
63409 **
63410 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
63411 ** otherwise.
63412 */
63413 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
63414   int rc = SQLITE_OK;
63415   if( ALWAYS(pFunc && pFunc->xFinalize) ){
63416     sqlite3_context ctx;
63417     Mem t;
63418     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
63419     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63420     memset(&ctx, 0, sizeof(ctx));
63421     memset(&t, 0, sizeof(t));
63422     t.flags = MEM_Null;
63423     t.db = pMem->db;
63424     ctx.pOut = &t;
63425     ctx.pMem = pMem;
63426     ctx.pFunc = pFunc;
63427     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
63428     assert( (pMem->flags & MEM_Dyn)==0 );
63429     if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
63430     memcpy(pMem, &t, sizeof(t));
63431     rc = ctx.isError;
63432   }
63433   return rc;
63434 }
63435 
63436 /*
63437 ** If the memory cell contains a value that must be freed by
63438 ** invoking the external callback in Mem.xDel, then this routine
63439 ** will free that value.  It also sets Mem.flags to MEM_Null.
63440 **
63441 ** This is a helper routine for sqlite3VdbeMemSetNull() and
63442 ** for sqlite3VdbeMemRelease().  Use those other routines as the
63443 ** entry point for releasing Mem resources.
63444 */
63445 static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
63446   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
63447   assert( VdbeMemDynamic(p) );
63448   if( p->flags&MEM_Agg ){
63449     sqlite3VdbeMemFinalize(p, p->u.pDef);
63450     assert( (p->flags & MEM_Agg)==0 );
63451     testcase( p->flags & MEM_Dyn );
63452   }
63453   if( p->flags&MEM_Dyn ){
63454     assert( (p->flags&MEM_RowSet)==0 );
63455     assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
63456     p->xDel((void *)p->z);
63457   }else if( p->flags&MEM_RowSet ){
63458     sqlite3RowSetClear(p->u.pRowSet);
63459   }else if( p->flags&MEM_Frame ){
63460     VdbeFrame *pFrame = p->u.pFrame;
63461     pFrame->pParent = pFrame->v->pDelFrame;
63462     pFrame->v->pDelFrame = pFrame;
63463   }
63464   p->flags = MEM_Null;
63465 }
63466 
63467 /*
63468 ** Release memory held by the Mem p, both external memory cleared
63469 ** by p->xDel and memory in p->zMalloc.
63470 **
63471 ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
63472 ** the unusual case where there really is memory in p that needs
63473 ** to be freed.
63474 */
63475 static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
63476   if( VdbeMemDynamic(p) ){
63477     vdbeMemClearExternAndSetNull(p);
63478   }
63479   if( p->szMalloc ){
63480     sqlite3DbFree(p->db, p->zMalloc);
63481     p->szMalloc = 0;
63482   }
63483   p->z = 0;
63484 }
63485 
63486 /*
63487 ** Release any memory resources held by the Mem.  Both the memory that is
63488 ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
63489 **
63490 ** Use this routine prior to clean up prior to abandoning a Mem, or to
63491 ** reset a Mem back to its minimum memory utilization.
63492 **
63493 ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
63494 ** prior to inserting new content into the Mem.
63495 */
63496 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
63497   assert( sqlite3VdbeCheckMemInvariants(p) );
63498   if( VdbeMemDynamic(p) || p->szMalloc ){
63499     vdbeMemClear(p);
63500   }
63501 }
63502 
63503 /*
63504 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
63505 ** If the double is out of range of a 64-bit signed integer then
63506 ** return the closest available 64-bit signed integer.
63507 */
63508 static i64 doubleToInt64(double r){
63509 #ifdef SQLITE_OMIT_FLOATING_POINT
63510   /* When floating-point is omitted, double and int64 are the same thing */
63511   return r;
63512 #else
63513   /*
63514   ** Many compilers we encounter do not define constants for the
63515   ** minimum and maximum 64-bit integers, or they define them
63516   ** inconsistently.  And many do not understand the "LL" notation.
63517   ** So we define our own static constants here using nothing
63518   ** larger than a 32-bit integer constant.
63519   */
63520   static const i64 maxInt = LARGEST_INT64;
63521   static const i64 minInt = SMALLEST_INT64;
63522 
63523   if( r<=(double)minInt ){
63524     return minInt;
63525   }else if( r>=(double)maxInt ){
63526     return maxInt;
63527   }else{
63528     return (i64)r;
63529   }
63530 #endif
63531 }
63532 
63533 /*
63534 ** Return some kind of integer value which is the best we can do
63535 ** at representing the value that *pMem describes as an integer.
63536 ** If pMem is an integer, then the value is exact.  If pMem is
63537 ** a floating-point then the value returned is the integer part.
63538 ** If pMem is a string or blob, then we make an attempt to convert
63539 ** it into an integer and return that.  If pMem represents an
63540 ** an SQL-NULL value, return 0.
63541 **
63542 ** If pMem represents a string value, its encoding might be changed.
63543 */
63544 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
63545   int flags;
63546   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63547   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
63548   flags = pMem->flags;
63549   if( flags & MEM_Int ){
63550     return pMem->u.i;
63551   }else if( flags & MEM_Real ){
63552     return doubleToInt64(pMem->u.r);
63553   }else if( flags & (MEM_Str|MEM_Blob) ){
63554     i64 value = 0;
63555     assert( pMem->z || pMem->n==0 );
63556     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
63557     return value;
63558   }else{
63559     return 0;
63560   }
63561 }
63562 
63563 /*
63564 ** Return the best representation of pMem that we can get into a
63565 ** double.  If pMem is already a double or an integer, return its
63566 ** value.  If it is a string or blob, try to convert it to a double.
63567 ** If it is a NULL, return 0.0.
63568 */
63569 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
63570   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63571   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
63572   if( pMem->flags & MEM_Real ){
63573     return pMem->u.r;
63574   }else if( pMem->flags & MEM_Int ){
63575     return (double)pMem->u.i;
63576   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
63577     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
63578     double val = (double)0;
63579     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
63580     return val;
63581   }else{
63582     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
63583     return (double)0;
63584   }
63585 }
63586 
63587 /*
63588 ** The MEM structure is already a MEM_Real.  Try to also make it a
63589 ** MEM_Int if we can.
63590 */
63591 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
63592   i64 ix;
63593   assert( pMem->flags & MEM_Real );
63594   assert( (pMem->flags & MEM_RowSet)==0 );
63595   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63596   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
63597 
63598   ix = doubleToInt64(pMem->u.r);
63599 
63600   /* Only mark the value as an integer if
63601   **
63602   **    (1) the round-trip conversion real->int->real is a no-op, and
63603   **    (2) The integer is neither the largest nor the smallest
63604   **        possible integer (ticket #3922)
63605   **
63606   ** The second and third terms in the following conditional enforces
63607   ** the second condition under the assumption that addition overflow causes
63608   ** values to wrap around.
63609   */
63610   if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
63611     pMem->u.i = ix;
63612     MemSetTypeFlag(pMem, MEM_Int);
63613   }
63614 }
63615 
63616 /*
63617 ** Convert pMem to type integer.  Invalidate any prior representations.
63618 */
63619 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
63620   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63621   assert( (pMem->flags & MEM_RowSet)==0 );
63622   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
63623 
63624   pMem->u.i = sqlite3VdbeIntValue(pMem);
63625   MemSetTypeFlag(pMem, MEM_Int);
63626   return SQLITE_OK;
63627 }
63628 
63629 /*
63630 ** Convert pMem so that it is of type MEM_Real.
63631 ** Invalidate any prior representations.
63632 */
63633 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
63634   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63635   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
63636 
63637   pMem->u.r = sqlite3VdbeRealValue(pMem);
63638   MemSetTypeFlag(pMem, MEM_Real);
63639   return SQLITE_OK;
63640 }
63641 
63642 /*
63643 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
63644 ** Invalidate any prior representations.
63645 **
63646 ** Every effort is made to force the conversion, even if the input
63647 ** is a string that does not look completely like a number.  Convert
63648 ** as much of the string as we can and ignore the rest.
63649 */
63650 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
63651   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
63652     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
63653     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63654     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
63655       MemSetTypeFlag(pMem, MEM_Int);
63656     }else{
63657       pMem->u.r = sqlite3VdbeRealValue(pMem);
63658       MemSetTypeFlag(pMem, MEM_Real);
63659       sqlite3VdbeIntegerAffinity(pMem);
63660     }
63661   }
63662   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
63663   pMem->flags &= ~(MEM_Str|MEM_Blob);
63664   return SQLITE_OK;
63665 }
63666 
63667 /*
63668 ** Cast the datatype of the value in pMem according to the affinity
63669 ** "aff".  Casting is different from applying affinity in that a cast
63670 ** is forced.  In other words, the value is converted into the desired
63671 ** affinity even if that results in loss of data.  This routine is
63672 ** used (for example) to implement the SQL "cast()" operator.
63673 */
63674 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
63675   if( pMem->flags & MEM_Null ) return;
63676   switch( aff ){
63677     case SQLITE_AFF_NONE: {   /* Really a cast to BLOB */
63678       if( (pMem->flags & MEM_Blob)==0 ){
63679         sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
63680         assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
63681         MemSetTypeFlag(pMem, MEM_Blob);
63682       }else{
63683         pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
63684       }
63685       break;
63686     }
63687     case SQLITE_AFF_NUMERIC: {
63688       sqlite3VdbeMemNumerify(pMem);
63689       break;
63690     }
63691     case SQLITE_AFF_INTEGER: {
63692       sqlite3VdbeMemIntegerify(pMem);
63693       break;
63694     }
63695     case SQLITE_AFF_REAL: {
63696       sqlite3VdbeMemRealify(pMem);
63697       break;
63698     }
63699     default: {
63700       assert( aff==SQLITE_AFF_TEXT );
63701       assert( MEM_Str==(MEM_Blob>>3) );
63702       pMem->flags |= (pMem->flags&MEM_Blob)>>3;
63703       sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
63704       assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
63705       pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
63706       break;
63707     }
63708   }
63709 }
63710 
63711 /*
63712 ** Initialize bulk memory to be a consistent Mem object.
63713 **
63714 ** The minimum amount of initialization feasible is performed.
63715 */
63716 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
63717   assert( (flags & ~MEM_TypeMask)==0 );
63718   pMem->flags = flags;
63719   pMem->db = db;
63720   pMem->szMalloc = 0;
63721 }
63722 
63723 
63724 /*
63725 ** Delete any previous value and set the value stored in *pMem to NULL.
63726 **
63727 ** This routine calls the Mem.xDel destructor to dispose of values that
63728 ** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
63729 ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
63730 ** routine to invoke the destructor and deallocates Mem.zMalloc.
63731 **
63732 ** Use this routine to reset the Mem prior to insert a new value.
63733 **
63734 ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
63735 */
63736 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
63737   if( VdbeMemDynamic(pMem) ){
63738     vdbeMemClearExternAndSetNull(pMem);
63739   }else{
63740     pMem->flags = MEM_Null;
63741   }
63742 }
63743 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
63744   sqlite3VdbeMemSetNull((Mem*)p);
63745 }
63746 
63747 /*
63748 ** Delete any previous value and set the value to be a BLOB of length
63749 ** n containing all zeros.
63750 */
63751 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
63752   sqlite3VdbeMemRelease(pMem);
63753   pMem->flags = MEM_Blob|MEM_Zero;
63754   pMem->n = 0;
63755   if( n<0 ) n = 0;
63756   pMem->u.nZero = n;
63757   pMem->enc = SQLITE_UTF8;
63758   pMem->z = 0;
63759 }
63760 
63761 /*
63762 ** The pMem is known to contain content that needs to be destroyed prior
63763 ** to a value change.  So invoke the destructor, then set the value to
63764 ** a 64-bit integer.
63765 */
63766 static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
63767   sqlite3VdbeMemSetNull(pMem);
63768   pMem->u.i = val;
63769   pMem->flags = MEM_Int;
63770 }
63771 
63772 /*
63773 ** Delete any previous value and set the value stored in *pMem to val,
63774 ** manifest type INTEGER.
63775 */
63776 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
63777   if( VdbeMemDynamic(pMem) ){
63778     vdbeReleaseAndSetInt64(pMem, val);
63779   }else{
63780     pMem->u.i = val;
63781     pMem->flags = MEM_Int;
63782   }
63783 }
63784 
63785 #ifndef SQLITE_OMIT_FLOATING_POINT
63786 /*
63787 ** Delete any previous value and set the value stored in *pMem to val,
63788 ** manifest type REAL.
63789 */
63790 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
63791   sqlite3VdbeMemSetNull(pMem);
63792   if( !sqlite3IsNaN(val) ){
63793     pMem->u.r = val;
63794     pMem->flags = MEM_Real;
63795   }
63796 }
63797 #endif
63798 
63799 /*
63800 ** Delete any previous value and set the value of pMem to be an
63801 ** empty boolean index.
63802 */
63803 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
63804   sqlite3 *db = pMem->db;
63805   assert( db!=0 );
63806   assert( (pMem->flags & MEM_RowSet)==0 );
63807   sqlite3VdbeMemRelease(pMem);
63808   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
63809   if( db->mallocFailed ){
63810     pMem->flags = MEM_Null;
63811     pMem->szMalloc = 0;
63812   }else{
63813     assert( pMem->zMalloc );
63814     pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
63815     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
63816     assert( pMem->u.pRowSet!=0 );
63817     pMem->flags = MEM_RowSet;
63818   }
63819 }
63820 
63821 /*
63822 ** Return true if the Mem object contains a TEXT or BLOB that is
63823 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
63824 */
63825 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
63826   assert( p->db!=0 );
63827   if( p->flags & (MEM_Str|MEM_Blob) ){
63828     int n = p->n;
63829     if( p->flags & MEM_Zero ){
63830       n += p->u.nZero;
63831     }
63832     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
63833   }
63834   return 0;
63835 }
63836 
63837 #ifdef SQLITE_DEBUG
63838 /*
63839 ** This routine prepares a memory cell for modification by breaking
63840 ** its link to a shallow copy and by marking any current shallow
63841 ** copies of this cell as invalid.
63842 **
63843 ** This is used for testing and debugging only - to make sure shallow
63844 ** copies are not misused.
63845 */
63846 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
63847   int i;
63848   Mem *pX;
63849   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
63850     if( pX->pScopyFrom==pMem ){
63851       pX->flags |= MEM_Undefined;
63852       pX->pScopyFrom = 0;
63853     }
63854   }
63855   pMem->pScopyFrom = 0;
63856 }
63857 #endif /* SQLITE_DEBUG */
63858 
63859 /*
63860 ** Size of struct Mem not including the Mem.zMalloc member.
63861 */
63862 #define MEMCELLSIZE offsetof(Mem,zMalloc)
63863 
63864 /*
63865 ** Make an shallow copy of pFrom into pTo.  Prior contents of
63866 ** pTo are freed.  The pFrom->z field is not duplicated.  If
63867 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
63868 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
63869 */
63870 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
63871   assert( (pFrom->flags & MEM_RowSet)==0 );
63872   assert( pTo->db==pFrom->db );
63873   if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
63874   memcpy(pTo, pFrom, MEMCELLSIZE);
63875   if( (pFrom->flags&MEM_Static)==0 ){
63876     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
63877     assert( srcType==MEM_Ephem || srcType==MEM_Static );
63878     pTo->flags |= srcType;
63879   }
63880 }
63881 
63882 /*
63883 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
63884 ** freed before the copy is made.
63885 */
63886 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
63887   int rc = SQLITE_OK;
63888 
63889   assert( pTo->db==pFrom->db );
63890   assert( (pFrom->flags & MEM_RowSet)==0 );
63891   if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
63892   memcpy(pTo, pFrom, MEMCELLSIZE);
63893   pTo->flags &= ~MEM_Dyn;
63894   if( pTo->flags&(MEM_Str|MEM_Blob) ){
63895     if( 0==(pFrom->flags&MEM_Static) ){
63896       pTo->flags |= MEM_Ephem;
63897       rc = sqlite3VdbeMemMakeWriteable(pTo);
63898     }
63899   }
63900 
63901   return rc;
63902 }
63903 
63904 /*
63905 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
63906 ** freed. If pFrom contains ephemeral data, a copy is made.
63907 **
63908 ** pFrom contains an SQL NULL when this routine returns.
63909 */
63910 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
63911   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
63912   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
63913   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
63914 
63915   sqlite3VdbeMemRelease(pTo);
63916   memcpy(pTo, pFrom, sizeof(Mem));
63917   pFrom->flags = MEM_Null;
63918   pFrom->szMalloc = 0;
63919 }
63920 
63921 /*
63922 ** Change the value of a Mem to be a string or a BLOB.
63923 **
63924 ** The memory management strategy depends on the value of the xDel
63925 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
63926 ** string is copied into a (possibly existing) buffer managed by the
63927 ** Mem structure. Otherwise, any existing buffer is freed and the
63928 ** pointer copied.
63929 **
63930 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
63931 ** size limit) then no memory allocation occurs.  If the string can be
63932 ** stored without allocating memory, then it is.  If a memory allocation
63933 ** is required to store the string, then value of pMem is unchanged.  In
63934 ** either case, SQLITE_TOOBIG is returned.
63935 */
63936 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
63937   Mem *pMem,          /* Memory cell to set to string value */
63938   const char *z,      /* String pointer */
63939   int n,              /* Bytes in string, or negative */
63940   u8 enc,             /* Encoding of z.  0 for BLOBs */
63941   void (*xDel)(void*) /* Destructor function */
63942 ){
63943   int nByte = n;      /* New value for pMem->n */
63944   int iLimit;         /* Maximum allowed string or blob size */
63945   u16 flags = 0;      /* New value for pMem->flags */
63946 
63947   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63948   assert( (pMem->flags & MEM_RowSet)==0 );
63949 
63950   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
63951   if( !z ){
63952     sqlite3VdbeMemSetNull(pMem);
63953     return SQLITE_OK;
63954   }
63955 
63956   if( pMem->db ){
63957     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
63958   }else{
63959     iLimit = SQLITE_MAX_LENGTH;
63960   }
63961   flags = (enc==0?MEM_Blob:MEM_Str);
63962   if( nByte<0 ){
63963     assert( enc!=0 );
63964     if( enc==SQLITE_UTF8 ){
63965       nByte = sqlite3Strlen30(z);
63966       if( nByte>iLimit ) nByte = iLimit+1;
63967     }else{
63968       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
63969     }
63970     flags |= MEM_Term;
63971   }
63972 
63973   /* The following block sets the new values of Mem.z and Mem.xDel. It
63974   ** also sets a flag in local variable "flags" to indicate the memory
63975   ** management (one of MEM_Dyn or MEM_Static).
63976   */
63977   if( xDel==SQLITE_TRANSIENT ){
63978     int nAlloc = nByte;
63979     if( flags&MEM_Term ){
63980       nAlloc += (enc==SQLITE_UTF8?1:2);
63981     }
63982     if( nByte>iLimit ){
63983       return SQLITE_TOOBIG;
63984     }
63985     testcase( nAlloc==0 );
63986     testcase( nAlloc==31 );
63987     testcase( nAlloc==32 );
63988     if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
63989       return SQLITE_NOMEM;
63990     }
63991     memcpy(pMem->z, z, nAlloc);
63992   }else if( xDel==SQLITE_DYNAMIC ){
63993     sqlite3VdbeMemRelease(pMem);
63994     pMem->zMalloc = pMem->z = (char *)z;
63995     pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
63996   }else{
63997     sqlite3VdbeMemRelease(pMem);
63998     pMem->z = (char *)z;
63999     pMem->xDel = xDel;
64000     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
64001   }
64002 
64003   pMem->n = nByte;
64004   pMem->flags = flags;
64005   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
64006 
64007 #ifndef SQLITE_OMIT_UTF16
64008   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
64009     return SQLITE_NOMEM;
64010   }
64011 #endif
64012 
64013   if( nByte>iLimit ){
64014     return SQLITE_TOOBIG;
64015   }
64016 
64017   return SQLITE_OK;
64018 }
64019 
64020 /*
64021 ** Move data out of a btree key or data field and into a Mem structure.
64022 ** The data or key is taken from the entry that pCur is currently pointing
64023 ** to.  offset and amt determine what portion of the data or key to retrieve.
64024 ** key is true to get the key or false to get data.  The result is written
64025 ** into the pMem element.
64026 **
64027 ** The pMem object must have been initialized.  This routine will use
64028 ** pMem->zMalloc to hold the content from the btree, if possible.  New
64029 ** pMem->zMalloc space will be allocated if necessary.  The calling routine
64030 ** is responsible for making sure that the pMem object is eventually
64031 ** destroyed.
64032 **
64033 ** If this routine fails for any reason (malloc returns NULL or unable
64034 ** to read from the disk) then the pMem is left in an inconsistent state.
64035 */
64036 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
64037   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
64038   u32 offset,       /* Offset from the start of data to return bytes from. */
64039   u32 amt,          /* Number of bytes to return. */
64040   int key,          /* If true, retrieve from the btree key, not data. */
64041   Mem *pMem         /* OUT: Return data in this Mem structure. */
64042 ){
64043   char *zData;        /* Data from the btree layer */
64044   u32 available = 0;  /* Number of bytes available on the local btree page */
64045   int rc = SQLITE_OK; /* Return code */
64046 
64047   assert( sqlite3BtreeCursorIsValid(pCur) );
64048   assert( !VdbeMemDynamic(pMem) );
64049 
64050   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
64051   ** that both the BtShared and database handle mutexes are held. */
64052   assert( (pMem->flags & MEM_RowSet)==0 );
64053   if( key ){
64054     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
64055   }else{
64056     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
64057   }
64058   assert( zData!=0 );
64059 
64060   if( offset+amt<=available ){
64061     pMem->z = &zData[offset];
64062     pMem->flags = MEM_Blob|MEM_Ephem;
64063     pMem->n = (int)amt;
64064   }else{
64065     pMem->flags = MEM_Null;
64066     if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
64067       if( key ){
64068         rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
64069       }else{
64070         rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
64071       }
64072       if( rc==SQLITE_OK ){
64073         pMem->z[amt] = 0;
64074         pMem->z[amt+1] = 0;
64075         pMem->flags = MEM_Blob|MEM_Term;
64076         pMem->n = (int)amt;
64077       }else{
64078         sqlite3VdbeMemRelease(pMem);
64079       }
64080     }
64081   }
64082 
64083   return rc;
64084 }
64085 
64086 /*
64087 ** The pVal argument is known to be a value other than NULL.
64088 ** Convert it into a string with encoding enc and return a pointer
64089 ** to a zero-terminated version of that string.
64090 */
64091 static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
64092   assert( pVal!=0 );
64093   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
64094   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
64095   assert( (pVal->flags & MEM_RowSet)==0 );
64096   assert( (pVal->flags & (MEM_Null))==0 );
64097   if( pVal->flags & (MEM_Blob|MEM_Str) ){
64098     pVal->flags |= MEM_Str;
64099     if( pVal->flags & MEM_Zero ){
64100       sqlite3VdbeMemExpandBlob(pVal);
64101     }
64102     if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
64103       sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
64104     }
64105     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
64106       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
64107       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
64108         return 0;
64109       }
64110     }
64111     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
64112   }else{
64113     sqlite3VdbeMemStringify(pVal, enc, 0);
64114     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
64115   }
64116   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
64117               || pVal->db->mallocFailed );
64118   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
64119     return pVal->z;
64120   }else{
64121     return 0;
64122   }
64123 }
64124 
64125 /* This function is only available internally, it is not part of the
64126 ** external API. It works in a similar way to sqlite3_value_text(),
64127 ** except the data returned is in the encoding specified by the second
64128 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
64129 ** SQLITE_UTF8.
64130 **
64131 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
64132 ** If that is the case, then the result must be aligned on an even byte
64133 ** boundary.
64134 */
64135 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
64136   if( !pVal ) return 0;
64137   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
64138   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
64139   assert( (pVal->flags & MEM_RowSet)==0 );
64140   if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
64141     return pVal->z;
64142   }
64143   if( pVal->flags&MEM_Null ){
64144     return 0;
64145   }
64146   return valueToText(pVal, enc);
64147 }
64148 
64149 /*
64150 ** Create a new sqlite3_value object.
64151 */
64152 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
64153   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
64154   if( p ){
64155     p->flags = MEM_Null;
64156     p->db = db;
64157   }
64158   return p;
64159 }
64160 
64161 /*
64162 ** Context object passed by sqlite3Stat4ProbeSetValue() through to
64163 ** valueNew(). See comments above valueNew() for details.
64164 */
64165 struct ValueNewStat4Ctx {
64166   Parse *pParse;
64167   Index *pIdx;
64168   UnpackedRecord **ppRec;
64169   int iVal;
64170 };
64171 
64172 /*
64173 ** Allocate and return a pointer to a new sqlite3_value object. If
64174 ** the second argument to this function is NULL, the object is allocated
64175 ** by calling sqlite3ValueNew().
64176 **
64177 ** Otherwise, if the second argument is non-zero, then this function is
64178 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
64179 ** already been allocated, allocate the UnpackedRecord structure that
64180 ** that function will return to its caller here. Then return a pointer to
64181 ** an sqlite3_value within the UnpackedRecord.a[] array.
64182 */
64183 static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
64184 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
64185   if( p ){
64186     UnpackedRecord *pRec = p->ppRec[0];
64187 
64188     if( pRec==0 ){
64189       Index *pIdx = p->pIdx;      /* Index being probed */
64190       int nByte;                  /* Bytes of space to allocate */
64191       int i;                      /* Counter variable */
64192       int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
64193 
64194       nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
64195       pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
64196       if( pRec ){
64197         pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
64198         if( pRec->pKeyInfo ){
64199           assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
64200           assert( pRec->pKeyInfo->enc==ENC(db) );
64201           pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
64202           for(i=0; i<nCol; i++){
64203             pRec->aMem[i].flags = MEM_Null;
64204             pRec->aMem[i].db = db;
64205           }
64206         }else{
64207           sqlite3DbFree(db, pRec);
64208           pRec = 0;
64209         }
64210       }
64211       if( pRec==0 ) return 0;
64212       p->ppRec[0] = pRec;
64213     }
64214 
64215     pRec->nField = p->iVal+1;
64216     return &pRec->aMem[p->iVal];
64217   }
64218 #else
64219   UNUSED_PARAMETER(p);
64220 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
64221   return sqlite3ValueNew(db);
64222 }
64223 
64224 /*
64225 ** The expression object indicated by the second argument is guaranteed
64226 ** to be a scalar SQL function. If
64227 **
64228 **   * all function arguments are SQL literals,
64229 **   * the SQLITE_FUNC_CONSTANT function flag is set, and
64230 **   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
64231 **
64232 ** then this routine attempts to invoke the SQL function. Assuming no
64233 ** error occurs, output parameter (*ppVal) is set to point to a value
64234 ** object containing the result before returning SQLITE_OK.
64235 **
64236 ** Affinity aff is applied to the result of the function before returning.
64237 ** If the result is a text value, the sqlite3_value object uses encoding
64238 ** enc.
64239 **
64240 ** If the conditions above are not met, this function returns SQLITE_OK
64241 ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
64242 ** NULL and an SQLite error code returned.
64243 */
64244 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
64245 static int valueFromFunction(
64246   sqlite3 *db,                    /* The database connection */
64247   Expr *p,                        /* The expression to evaluate */
64248   u8 enc,                         /* Encoding to use */
64249   u8 aff,                         /* Affinity to use */
64250   sqlite3_value **ppVal,          /* Write the new value here */
64251   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
64252 ){
64253   sqlite3_context ctx;            /* Context object for function invocation */
64254   sqlite3_value **apVal = 0;      /* Function arguments */
64255   int nVal = 0;                   /* Size of apVal[] array */
64256   FuncDef *pFunc = 0;             /* Function definition */
64257   sqlite3_value *pVal = 0;        /* New value */
64258   int rc = SQLITE_OK;             /* Return code */
64259   int nName;                      /* Size of function name in bytes */
64260   ExprList *pList = 0;            /* Function arguments */
64261   int i;                          /* Iterator variable */
64262 
64263   assert( pCtx!=0 );
64264   assert( (p->flags & EP_TokenOnly)==0 );
64265   pList = p->x.pList;
64266   if( pList ) nVal = pList->nExpr;
64267   nName = sqlite3Strlen30(p->u.zToken);
64268   pFunc = sqlite3FindFunction(db, p->u.zToken, nName, nVal, enc, 0);
64269   assert( pFunc );
64270   if( (pFunc->funcFlags & SQLITE_FUNC_CONSTANT)==0
64271    || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
64272   ){
64273     return SQLITE_OK;
64274   }
64275 
64276   if( pList ){
64277     apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
64278     if( apVal==0 ){
64279       rc = SQLITE_NOMEM;
64280       goto value_from_function_out;
64281     }
64282     for(i=0; i<nVal; i++){
64283       rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
64284       if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
64285     }
64286   }
64287 
64288   pVal = valueNew(db, pCtx);
64289   if( pVal==0 ){
64290     rc = SQLITE_NOMEM;
64291     goto value_from_function_out;
64292   }
64293 
64294   assert( pCtx->pParse->rc==SQLITE_OK );
64295   memset(&ctx, 0, sizeof(ctx));
64296   ctx.pOut = pVal;
64297   ctx.pFunc = pFunc;
64298   pFunc->xFunc(&ctx, nVal, apVal);
64299   if( ctx.isError ){
64300     rc = ctx.isError;
64301     sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
64302   }else{
64303     sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
64304     assert( rc==SQLITE_OK );
64305     rc = sqlite3VdbeChangeEncoding(pVal, enc);
64306     if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
64307       rc = SQLITE_TOOBIG;
64308       pCtx->pParse->nErr++;
64309     }
64310   }
64311   pCtx->pParse->rc = rc;
64312 
64313  value_from_function_out:
64314   if( rc!=SQLITE_OK ){
64315     pVal = 0;
64316   }
64317   if( apVal ){
64318     for(i=0; i<nVal; i++){
64319       sqlite3ValueFree(apVal[i]);
64320     }
64321     sqlite3DbFree(db, apVal);
64322   }
64323 
64324   *ppVal = pVal;
64325   return rc;
64326 }
64327 #else
64328 # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
64329 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
64330 
64331 /*
64332 ** Extract a value from the supplied expression in the manner described
64333 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
64334 ** using valueNew().
64335 **
64336 ** If pCtx is NULL and an error occurs after the sqlite3_value object
64337 ** has been allocated, it is freed before returning. Or, if pCtx is not
64338 ** NULL, it is assumed that the caller will free any allocated object
64339 ** in all cases.
64340 */
64341 static int valueFromExpr(
64342   sqlite3 *db,                    /* The database connection */
64343   Expr *pExpr,                    /* The expression to evaluate */
64344   u8 enc,                         /* Encoding to use */
64345   u8 affinity,                    /* Affinity to use */
64346   sqlite3_value **ppVal,          /* Write the new value here */
64347   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
64348 ){
64349   int op;
64350   char *zVal = 0;
64351   sqlite3_value *pVal = 0;
64352   int negInt = 1;
64353   const char *zNeg = "";
64354   int rc = SQLITE_OK;
64355 
64356   if( !pExpr ){
64357     *ppVal = 0;
64358     return SQLITE_OK;
64359   }
64360   while( (op = pExpr->op)==TK_UPLUS ) pExpr = pExpr->pLeft;
64361   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
64362 
64363   /* Compressed expressions only appear when parsing the DEFAULT clause
64364   ** on a table column definition, and hence only when pCtx==0.  This
64365   ** check ensures that an EP_TokenOnly expression is never passed down
64366   ** into valueFromFunction(). */
64367   assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
64368 
64369   if( op==TK_CAST ){
64370     u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
64371     rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
64372     testcase( rc!=SQLITE_OK );
64373     if( *ppVal ){
64374       sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
64375       sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
64376     }
64377     return rc;
64378   }
64379 
64380   /* Handle negative integers in a single step.  This is needed in the
64381   ** case when the value is -9223372036854775808.
64382   */
64383   if( op==TK_UMINUS
64384    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
64385     pExpr = pExpr->pLeft;
64386     op = pExpr->op;
64387     negInt = -1;
64388     zNeg = "-";
64389   }
64390 
64391   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
64392     pVal = valueNew(db, pCtx);
64393     if( pVal==0 ) goto no_mem;
64394     if( ExprHasProperty(pExpr, EP_IntValue) ){
64395       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
64396     }else{
64397       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
64398       if( zVal==0 ) goto no_mem;
64399       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
64400     }
64401     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
64402       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
64403     }else{
64404       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
64405     }
64406     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
64407     if( enc!=SQLITE_UTF8 ){
64408       rc = sqlite3VdbeChangeEncoding(pVal, enc);
64409     }
64410   }else if( op==TK_UMINUS ) {
64411     /* This branch happens for multiple negative signs.  Ex: -(-5) */
64412     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
64413      && pVal!=0
64414     ){
64415       sqlite3VdbeMemNumerify(pVal);
64416       if( pVal->flags & MEM_Real ){
64417         pVal->u.r = -pVal->u.r;
64418       }else if( pVal->u.i==SMALLEST_INT64 ){
64419         pVal->u.r = -(double)SMALLEST_INT64;
64420         MemSetTypeFlag(pVal, MEM_Real);
64421       }else{
64422         pVal->u.i = -pVal->u.i;
64423       }
64424       sqlite3ValueApplyAffinity(pVal, affinity, enc);
64425     }
64426   }else if( op==TK_NULL ){
64427     pVal = valueNew(db, pCtx);
64428     if( pVal==0 ) goto no_mem;
64429   }
64430 #ifndef SQLITE_OMIT_BLOB_LITERAL
64431   else if( op==TK_BLOB ){
64432     int nVal;
64433     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
64434     assert( pExpr->u.zToken[1]=='\'' );
64435     pVal = valueNew(db, pCtx);
64436     if( !pVal ) goto no_mem;
64437     zVal = &pExpr->u.zToken[2];
64438     nVal = sqlite3Strlen30(zVal)-1;
64439     assert( zVal[nVal]=='\'' );
64440     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
64441                          0, SQLITE_DYNAMIC);
64442   }
64443 #endif
64444 
64445 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
64446   else if( op==TK_FUNCTION && pCtx!=0 ){
64447     rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
64448   }
64449 #endif
64450 
64451   *ppVal = pVal;
64452   return rc;
64453 
64454 no_mem:
64455   db->mallocFailed = 1;
64456   sqlite3DbFree(db, zVal);
64457   assert( *ppVal==0 );
64458 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
64459   if( pCtx==0 ) sqlite3ValueFree(pVal);
64460 #else
64461   assert( pCtx==0 ); sqlite3ValueFree(pVal);
64462 #endif
64463   return SQLITE_NOMEM;
64464 }
64465 
64466 /*
64467 ** Create a new sqlite3_value object, containing the value of pExpr.
64468 **
64469 ** This only works for very simple expressions that consist of one constant
64470 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
64471 ** be converted directly into a value, then the value is allocated and
64472 ** a pointer written to *ppVal. The caller is responsible for deallocating
64473 ** the value by passing it to sqlite3ValueFree() later on. If the expression
64474 ** cannot be converted to a value, then *ppVal is set to NULL.
64475 */
64476 SQLITE_PRIVATE int sqlite3ValueFromExpr(
64477   sqlite3 *db,              /* The database connection */
64478   Expr *pExpr,              /* The expression to evaluate */
64479   u8 enc,                   /* Encoding to use */
64480   u8 affinity,              /* Affinity to use */
64481   sqlite3_value **ppVal     /* Write the new value here */
64482 ){
64483   return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
64484 }
64485 
64486 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
64487 /*
64488 ** The implementation of the sqlite_record() function. This function accepts
64489 ** a single argument of any type. The return value is a formatted database
64490 ** record (a blob) containing the argument value.
64491 **
64492 ** This is used to convert the value stored in the 'sample' column of the
64493 ** sqlite_stat3 table to the record format SQLite uses internally.
64494 */
64495 static void recordFunc(
64496   sqlite3_context *context,
64497   int argc,
64498   sqlite3_value **argv
64499 ){
64500   const int file_format = 1;
64501   int iSerial;                    /* Serial type */
64502   int nSerial;                    /* Bytes of space for iSerial as varint */
64503   int nVal;                       /* Bytes of space required for argv[0] */
64504   int nRet;
64505   sqlite3 *db;
64506   u8 *aRet;
64507 
64508   UNUSED_PARAMETER( argc );
64509   iSerial = sqlite3VdbeSerialType(argv[0], file_format);
64510   nSerial = sqlite3VarintLen(iSerial);
64511   nVal = sqlite3VdbeSerialTypeLen(iSerial);
64512   db = sqlite3_context_db_handle(context);
64513 
64514   nRet = 1 + nSerial + nVal;
64515   aRet = sqlite3DbMallocRaw(db, nRet);
64516   if( aRet==0 ){
64517     sqlite3_result_error_nomem(context);
64518   }else{
64519     aRet[0] = nSerial+1;
64520     putVarint32(&aRet[1], iSerial);
64521     sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
64522     sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
64523     sqlite3DbFree(db, aRet);
64524   }
64525 }
64526 
64527 /*
64528 ** Register built-in functions used to help read ANALYZE data.
64529 */
64530 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
64531   static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
64532     FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
64533   };
64534   int i;
64535   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
64536   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
64537   for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
64538     sqlite3FuncDefInsert(pHash, &aFunc[i]);
64539   }
64540 }
64541 
64542 /*
64543 ** Attempt to extract a value from pExpr and use it to construct *ppVal.
64544 **
64545 ** If pAlloc is not NULL, then an UnpackedRecord object is created for
64546 ** pAlloc if one does not exist and the new value is added to the
64547 ** UnpackedRecord object.
64548 **
64549 ** A value is extracted in the following cases:
64550 **
64551 **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
64552 **
64553 **  * The expression is a bound variable, and this is a reprepare, or
64554 **
64555 **  * The expression is a literal value.
64556 **
64557 ** On success, *ppVal is made to point to the extracted value.  The caller
64558 ** is responsible for ensuring that the value is eventually freed.
64559 */
64560 static int stat4ValueFromExpr(
64561   Parse *pParse,                  /* Parse context */
64562   Expr *pExpr,                    /* The expression to extract a value from */
64563   u8 affinity,                    /* Affinity to use */
64564   struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
64565   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
64566 ){
64567   int rc = SQLITE_OK;
64568   sqlite3_value *pVal = 0;
64569   sqlite3 *db = pParse->db;
64570 
64571   /* Skip over any TK_COLLATE nodes */
64572   pExpr = sqlite3ExprSkipCollate(pExpr);
64573 
64574   if( !pExpr ){
64575     pVal = valueNew(db, pAlloc);
64576     if( pVal ){
64577       sqlite3VdbeMemSetNull((Mem*)pVal);
64578     }
64579   }else if( pExpr->op==TK_VARIABLE
64580         || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
64581   ){
64582     Vdbe *v;
64583     int iBindVar = pExpr->iColumn;
64584     sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
64585     if( (v = pParse->pReprepare)!=0 ){
64586       pVal = valueNew(db, pAlloc);
64587       if( pVal ){
64588         rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
64589         if( rc==SQLITE_OK ){
64590           sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
64591         }
64592         pVal->db = pParse->db;
64593       }
64594     }
64595   }else{
64596     rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
64597   }
64598 
64599   assert( pVal==0 || pVal->db==db );
64600   *ppVal = pVal;
64601   return rc;
64602 }
64603 
64604 /*
64605 ** This function is used to allocate and populate UnpackedRecord
64606 ** structures intended to be compared against sample index keys stored
64607 ** in the sqlite_stat4 table.
64608 **
64609 ** A single call to this function attempts to populates field iVal (leftmost
64610 ** is 0 etc.) of the unpacked record with a value extracted from expression
64611 ** pExpr. Extraction of values is possible if:
64612 **
64613 **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
64614 **
64615 **  * The expression is a bound variable, and this is a reprepare, or
64616 **
64617 **  * The sqlite3ValueFromExpr() function is able to extract a value
64618 **    from the expression (i.e. the expression is a literal value).
64619 **
64620 ** If a value can be extracted, the affinity passed as the 5th argument
64621 ** is applied to it before it is copied into the UnpackedRecord. Output
64622 ** parameter *pbOk is set to true if a value is extracted, or false
64623 ** otherwise.
64624 **
64625 ** When this function is called, *ppRec must either point to an object
64626 ** allocated by an earlier call to this function, or must be NULL. If it
64627 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
64628 ** is allocated (and *ppRec set to point to it) before returning.
64629 **
64630 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
64631 ** error if a value cannot be extracted from pExpr. If an error does
64632 ** occur, an SQLite error code is returned.
64633 */
64634 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
64635   Parse *pParse,                  /* Parse context */
64636   Index *pIdx,                    /* Index being probed */
64637   UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
64638   Expr *pExpr,                    /* The expression to extract a value from */
64639   u8 affinity,                    /* Affinity to use */
64640   int iVal,                       /* Array element to populate */
64641   int *pbOk                       /* OUT: True if value was extracted */
64642 ){
64643   int rc;
64644   sqlite3_value *pVal = 0;
64645   struct ValueNewStat4Ctx alloc;
64646 
64647   alloc.pParse = pParse;
64648   alloc.pIdx = pIdx;
64649   alloc.ppRec = ppRec;
64650   alloc.iVal = iVal;
64651 
64652   rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
64653   assert( pVal==0 || pVal->db==pParse->db );
64654   *pbOk = (pVal!=0);
64655   return rc;
64656 }
64657 
64658 /*
64659 ** Attempt to extract a value from expression pExpr using the methods
64660 ** as described for sqlite3Stat4ProbeSetValue() above.
64661 **
64662 ** If successful, set *ppVal to point to a new value object and return
64663 ** SQLITE_OK. If no value can be extracted, but no other error occurs
64664 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
64665 ** does occur, return an SQLite error code. The final value of *ppVal
64666 ** is undefined in this case.
64667 */
64668 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
64669   Parse *pParse,                  /* Parse context */
64670   Expr *pExpr,                    /* The expression to extract a value from */
64671   u8 affinity,                    /* Affinity to use */
64672   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
64673 ){
64674   return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
64675 }
64676 
64677 /*
64678 ** Extract the iCol-th column from the nRec-byte record in pRec.  Write
64679 ** the column value into *ppVal.  If *ppVal is initially NULL then a new
64680 ** sqlite3_value object is allocated.
64681 **
64682 ** If *ppVal is initially NULL then the caller is responsible for
64683 ** ensuring that the value written into *ppVal is eventually freed.
64684 */
64685 SQLITE_PRIVATE int sqlite3Stat4Column(
64686   sqlite3 *db,                    /* Database handle */
64687   const void *pRec,               /* Pointer to buffer containing record */
64688   int nRec,                       /* Size of buffer pRec in bytes */
64689   int iCol,                       /* Column to extract */
64690   sqlite3_value **ppVal           /* OUT: Extracted value */
64691 ){
64692   u32 t;                          /* a column type code */
64693   int nHdr;                       /* Size of the header in the record */
64694   int iHdr;                       /* Next unread header byte */
64695   int iField;                     /* Next unread data byte */
64696   int szField;                    /* Size of the current data field */
64697   int i;                          /* Column index */
64698   u8 *a = (u8*)pRec;              /* Typecast byte array */
64699   Mem *pMem = *ppVal;             /* Write result into this Mem object */
64700 
64701   assert( iCol>0 );
64702   iHdr = getVarint32(a, nHdr);
64703   if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
64704   iField = nHdr;
64705   for(i=0; i<=iCol; i++){
64706     iHdr += getVarint32(&a[iHdr], t);
64707     testcase( iHdr==nHdr );
64708     testcase( iHdr==nHdr+1 );
64709     if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
64710     szField = sqlite3VdbeSerialTypeLen(t);
64711     iField += szField;
64712   }
64713   testcase( iField==nRec );
64714   testcase( iField==nRec+1 );
64715   if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
64716   if( pMem==0 ){
64717     pMem = *ppVal = sqlite3ValueNew(db);
64718     if( pMem==0 ) return SQLITE_NOMEM;
64719   }
64720   sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
64721   pMem->enc = ENC(db);
64722   return SQLITE_OK;
64723 }
64724 
64725 /*
64726 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
64727 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
64728 ** the object.
64729 */
64730 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
64731   if( pRec ){
64732     int i;
64733     int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
64734     Mem *aMem = pRec->aMem;
64735     sqlite3 *db = aMem[0].db;
64736     for(i=0; i<nCol; i++){
64737       sqlite3VdbeMemRelease(&aMem[i]);
64738     }
64739     sqlite3KeyInfoUnref(pRec->pKeyInfo);
64740     sqlite3DbFree(db, pRec);
64741   }
64742 }
64743 #endif /* ifdef SQLITE_ENABLE_STAT4 */
64744 
64745 /*
64746 ** Change the string value of an sqlite3_value object
64747 */
64748 SQLITE_PRIVATE void sqlite3ValueSetStr(
64749   sqlite3_value *v,     /* Value to be set */
64750   int n,                /* Length of string z */
64751   const void *z,        /* Text of the new string */
64752   u8 enc,               /* Encoding to use */
64753   void (*xDel)(void*)   /* Destructor for the string */
64754 ){
64755   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
64756 }
64757 
64758 /*
64759 ** Free an sqlite3_value object
64760 */
64761 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
64762   if( !v ) return;
64763   sqlite3VdbeMemRelease((Mem *)v);
64764   sqlite3DbFree(((Mem*)v)->db, v);
64765 }
64766 
64767 /*
64768 ** Return the number of bytes in the sqlite3_value object assuming
64769 ** that it uses the encoding "enc"
64770 */
64771 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
64772   Mem *p = (Mem*)pVal;
64773   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
64774     if( p->flags & MEM_Zero ){
64775       return p->n + p->u.nZero;
64776     }else{
64777       return p->n;
64778     }
64779   }
64780   return 0;
64781 }
64782 
64783 /************** End of vdbemem.c *********************************************/
64784 /************** Begin file vdbeaux.c *****************************************/
64785 /*
64786 ** 2003 September 6
64787 **
64788 ** The author disclaims copyright to this source code.  In place of
64789 ** a legal notice, here is a blessing:
64790 **
64791 **    May you do good and not evil.
64792 **    May you find forgiveness for yourself and forgive others.
64793 **    May you share freely, never taking more than you give.
64794 **
64795 *************************************************************************
64796 ** This file contains code used for creating, destroying, and populating
64797 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
64798 */
64799 
64800 /*
64801 ** Create a new virtual database engine.
64802 */
64803 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
64804   sqlite3 *db = pParse->db;
64805   Vdbe *p;
64806   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
64807   if( p==0 ) return 0;
64808   p->db = db;
64809   if( db->pVdbe ){
64810     db->pVdbe->pPrev = p;
64811   }
64812   p->pNext = db->pVdbe;
64813   p->pPrev = 0;
64814   db->pVdbe = p;
64815   p->magic = VDBE_MAGIC_INIT;
64816   p->pParse = pParse;
64817   assert( pParse->aLabel==0 );
64818   assert( pParse->nLabel==0 );
64819   assert( pParse->nOpAlloc==0 );
64820   return p;
64821 }
64822 
64823 /*
64824 ** Remember the SQL string for a prepared statement.
64825 */
64826 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
64827   assert( isPrepareV2==1 || isPrepareV2==0 );
64828   if( p==0 ) return;
64829 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
64830   if( !isPrepareV2 ) return;
64831 #endif
64832   assert( p->zSql==0 );
64833   p->zSql = sqlite3DbStrNDup(p->db, z, n);
64834   p->isPrepareV2 = (u8)isPrepareV2;
64835 }
64836 
64837 /*
64838 ** Return the SQL associated with a prepared statement
64839 */
64840 SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt){
64841   Vdbe *p = (Vdbe *)pStmt;
64842   return (p && p->isPrepareV2) ? p->zSql : 0;
64843 }
64844 
64845 /*
64846 ** Swap all content between two VDBE structures.
64847 */
64848 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
64849   Vdbe tmp, *pTmp;
64850   char *zTmp;
64851   tmp = *pA;
64852   *pA = *pB;
64853   *pB = tmp;
64854   pTmp = pA->pNext;
64855   pA->pNext = pB->pNext;
64856   pB->pNext = pTmp;
64857   pTmp = pA->pPrev;
64858   pA->pPrev = pB->pPrev;
64859   pB->pPrev = pTmp;
64860   zTmp = pA->zSql;
64861   pA->zSql = pB->zSql;
64862   pB->zSql = zTmp;
64863   pB->isPrepareV2 = pA->isPrepareV2;
64864 }
64865 
64866 /*
64867 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
64868 ** than its current size. nOp is guaranteed to be less than or equal
64869 ** to 1024/sizeof(Op).
64870 **
64871 ** If an out-of-memory error occurs while resizing the array, return
64872 ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
64873 ** unchanged (this is so that any opcodes already allocated can be
64874 ** correctly deallocated along with the rest of the Vdbe).
64875 */
64876 static int growOpArray(Vdbe *v, int nOp){
64877   VdbeOp *pNew;
64878   Parse *p = v->pParse;
64879 
64880   /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
64881   ** more frequent reallocs and hence provide more opportunities for
64882   ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
64883   ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
64884   ** by the minimum* amount required until the size reaches 512.  Normal
64885   ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
64886   ** size of the op array or add 1KB of space, whichever is smaller. */
64887 #ifdef SQLITE_TEST_REALLOC_STRESS
64888   int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
64889 #else
64890   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
64891   UNUSED_PARAMETER(nOp);
64892 #endif
64893 
64894   assert( nOp<=(1024/sizeof(Op)) );
64895   assert( nNew>=(p->nOpAlloc+nOp) );
64896   pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
64897   if( pNew ){
64898     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
64899     v->aOp = pNew;
64900   }
64901   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
64902 }
64903 
64904 #ifdef SQLITE_DEBUG
64905 /* This routine is just a convenient place to set a breakpoint that will
64906 ** fire after each opcode is inserted and displayed using
64907 ** "PRAGMA vdbe_addoptrace=on".
64908 */
64909 static void test_addop_breakpoint(void){
64910   static int n = 0;
64911   n++;
64912 }
64913 #endif
64914 
64915 /*
64916 ** Add a new instruction to the list of instructions current in the
64917 ** VDBE.  Return the address of the new instruction.
64918 **
64919 ** Parameters:
64920 **
64921 **    p               Pointer to the VDBE
64922 **
64923 **    op              The opcode for this instruction
64924 **
64925 **    p1, p2, p3      Operands
64926 **
64927 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
64928 ** the sqlite3VdbeChangeP4() function to change the value of the P4
64929 ** operand.
64930 */
64931 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
64932   int i;
64933   VdbeOp *pOp;
64934 
64935   i = p->nOp;
64936   assert( p->magic==VDBE_MAGIC_INIT );
64937   assert( op>0 && op<0xff );
64938   if( p->pParse->nOpAlloc<=i ){
64939     if( growOpArray(p, 1) ){
64940       return 1;
64941     }
64942   }
64943   p->nOp++;
64944   pOp = &p->aOp[i];
64945   pOp->opcode = (u8)op;
64946   pOp->p5 = 0;
64947   pOp->p1 = p1;
64948   pOp->p2 = p2;
64949   pOp->p3 = p3;
64950   pOp->p4.p = 0;
64951   pOp->p4type = P4_NOTUSED;
64952 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
64953   pOp->zComment = 0;
64954 #endif
64955 #ifdef SQLITE_DEBUG
64956   if( p->db->flags & SQLITE_VdbeAddopTrace ){
64957     int jj, kk;
64958     Parse *pParse = p->pParse;
64959     for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
64960       struct yColCache *x = pParse->aColCache + jj;
64961       if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
64962       printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
64963       kk++;
64964     }
64965     if( kk ) printf("\n");
64966     sqlite3VdbePrintOp(0, i, &p->aOp[i]);
64967     test_addop_breakpoint();
64968   }
64969 #endif
64970 #ifdef VDBE_PROFILE
64971   pOp->cycles = 0;
64972   pOp->cnt = 0;
64973 #endif
64974 #ifdef SQLITE_VDBE_COVERAGE
64975   pOp->iSrcLine = 0;
64976 #endif
64977   return i;
64978 }
64979 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
64980   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
64981 }
64982 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
64983   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
64984 }
64985 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
64986   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
64987 }
64988 
64989 
64990 /*
64991 ** Add an opcode that includes the p4 value as a pointer.
64992 */
64993 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
64994   Vdbe *p,            /* Add the opcode to this VM */
64995   int op,             /* The new opcode */
64996   int p1,             /* The P1 operand */
64997   int p2,             /* The P2 operand */
64998   int p3,             /* The P3 operand */
64999   const char *zP4,    /* The P4 operand */
65000   int p4type          /* P4 operand type */
65001 ){
65002   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
65003   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
65004   return addr;
65005 }
65006 
65007 /*
65008 ** Add an OP_ParseSchema opcode.  This routine is broken out from
65009 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
65010 ** as having been used.
65011 **
65012 ** The zWhere string must have been obtained from sqlite3_malloc().
65013 ** This routine will take ownership of the allocated memory.
65014 */
65015 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
65016   int j;
65017   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
65018   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
65019   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
65020 }
65021 
65022 /*
65023 ** Add an opcode that includes the p4 value as an integer.
65024 */
65025 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
65026   Vdbe *p,            /* Add the opcode to this VM */
65027   int op,             /* The new opcode */
65028   int p1,             /* The P1 operand */
65029   int p2,             /* The P2 operand */
65030   int p3,             /* The P3 operand */
65031   int p4              /* The P4 operand as an integer */
65032 ){
65033   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
65034   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
65035   return addr;
65036 }
65037 
65038 /*
65039 ** Create a new symbolic label for an instruction that has yet to be
65040 ** coded.  The symbolic label is really just a negative number.  The
65041 ** label can be used as the P2 value of an operation.  Later, when
65042 ** the label is resolved to a specific address, the VDBE will scan
65043 ** through its operation list and change all values of P2 which match
65044 ** the label into the resolved address.
65045 **
65046 ** The VDBE knows that a P2 value is a label because labels are
65047 ** always negative and P2 values are suppose to be non-negative.
65048 ** Hence, a negative P2 value is a label that has yet to be resolved.
65049 **
65050 ** Zero is returned if a malloc() fails.
65051 */
65052 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
65053   Parse *p = v->pParse;
65054   int i = p->nLabel++;
65055   assert( v->magic==VDBE_MAGIC_INIT );
65056   if( (i & (i-1))==0 ){
65057     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
65058                                        (i*2+1)*sizeof(p->aLabel[0]));
65059   }
65060   if( p->aLabel ){
65061     p->aLabel[i] = -1;
65062   }
65063   return -1-i;
65064 }
65065 
65066 /*
65067 ** Resolve label "x" to be the address of the next instruction to
65068 ** be inserted.  The parameter "x" must have been obtained from
65069 ** a prior call to sqlite3VdbeMakeLabel().
65070 */
65071 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
65072   Parse *p = v->pParse;
65073   int j = -1-x;
65074   assert( v->magic==VDBE_MAGIC_INIT );
65075   assert( j<p->nLabel );
65076   if( ALWAYS(j>=0) && p->aLabel ){
65077     p->aLabel[j] = v->nOp;
65078   }
65079   p->iFixedOp = v->nOp - 1;
65080 }
65081 
65082 /*
65083 ** Mark the VDBE as one that can only be run one time.
65084 */
65085 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
65086   p->runOnlyOnce = 1;
65087 }
65088 
65089 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
65090 
65091 /*
65092 ** The following type and function are used to iterate through all opcodes
65093 ** in a Vdbe main program and each of the sub-programs (triggers) it may
65094 ** invoke directly or indirectly. It should be used as follows:
65095 **
65096 **   Op *pOp;
65097 **   VdbeOpIter sIter;
65098 **
65099 **   memset(&sIter, 0, sizeof(sIter));
65100 **   sIter.v = v;                            // v is of type Vdbe*
65101 **   while( (pOp = opIterNext(&sIter)) ){
65102 **     // Do something with pOp
65103 **   }
65104 **   sqlite3DbFree(v->db, sIter.apSub);
65105 **
65106 */
65107 typedef struct VdbeOpIter VdbeOpIter;
65108 struct VdbeOpIter {
65109   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
65110   SubProgram **apSub;        /* Array of subprograms */
65111   int nSub;                  /* Number of entries in apSub */
65112   int iAddr;                 /* Address of next instruction to return */
65113   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
65114 };
65115 static Op *opIterNext(VdbeOpIter *p){
65116   Vdbe *v = p->v;
65117   Op *pRet = 0;
65118   Op *aOp;
65119   int nOp;
65120 
65121   if( p->iSub<=p->nSub ){
65122 
65123     if( p->iSub==0 ){
65124       aOp = v->aOp;
65125       nOp = v->nOp;
65126     }else{
65127       aOp = p->apSub[p->iSub-1]->aOp;
65128       nOp = p->apSub[p->iSub-1]->nOp;
65129     }
65130     assert( p->iAddr<nOp );
65131 
65132     pRet = &aOp[p->iAddr];
65133     p->iAddr++;
65134     if( p->iAddr==nOp ){
65135       p->iSub++;
65136       p->iAddr = 0;
65137     }
65138 
65139     if( pRet->p4type==P4_SUBPROGRAM ){
65140       int nByte = (p->nSub+1)*sizeof(SubProgram*);
65141       int j;
65142       for(j=0; j<p->nSub; j++){
65143         if( p->apSub[j]==pRet->p4.pProgram ) break;
65144       }
65145       if( j==p->nSub ){
65146         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
65147         if( !p->apSub ){
65148           pRet = 0;
65149         }else{
65150           p->apSub[p->nSub++] = pRet->p4.pProgram;
65151         }
65152       }
65153     }
65154   }
65155 
65156   return pRet;
65157 }
65158 
65159 /*
65160 ** Check if the program stored in the VM associated with pParse may
65161 ** throw an ABORT exception (causing the statement, but not entire transaction
65162 ** to be rolled back). This condition is true if the main program or any
65163 ** sub-programs contains any of the following:
65164 **
65165 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
65166 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
65167 **   *  OP_Destroy
65168 **   *  OP_VUpdate
65169 **   *  OP_VRename
65170 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
65171 **
65172 ** Then check that the value of Parse.mayAbort is true if an
65173 ** ABORT may be thrown, or false otherwise. Return true if it does
65174 ** match, or false otherwise. This function is intended to be used as
65175 ** part of an assert statement in the compiler. Similar to:
65176 **
65177 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
65178 */
65179 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
65180   int hasAbort = 0;
65181   int hasFkCounter = 0;
65182   Op *pOp;
65183   VdbeOpIter sIter;
65184   memset(&sIter, 0, sizeof(sIter));
65185   sIter.v = v;
65186 
65187   while( (pOp = opIterNext(&sIter))!=0 ){
65188     int opcode = pOp->opcode;
65189     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
65190      || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
65191       && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
65192     ){
65193       hasAbort = 1;
65194       break;
65195     }
65196 #ifndef SQLITE_OMIT_FOREIGN_KEY
65197     if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
65198       hasFkCounter = 1;
65199     }
65200 #endif
65201   }
65202   sqlite3DbFree(v->db, sIter.apSub);
65203 
65204   /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
65205   ** If malloc failed, then the while() loop above may not have iterated
65206   ** through all opcodes and hasAbort may be set incorrectly. Return
65207   ** true for this case to prevent the assert() in the callers frame
65208   ** from failing.  */
65209   return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter );
65210 }
65211 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
65212 
65213 /*
65214 ** Loop through the program looking for P2 values that are negative
65215 ** on jump instructions.  Each such value is a label.  Resolve the
65216 ** label by setting the P2 value to its correct non-zero value.
65217 **
65218 ** This routine is called once after all opcodes have been inserted.
65219 **
65220 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
65221 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
65222 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
65223 **
65224 ** The Op.opflags field is set on all opcodes.
65225 */
65226 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
65227   int i;
65228   int nMaxArgs = *pMaxFuncArgs;
65229   Op *pOp;
65230   Parse *pParse = p->pParse;
65231   int *aLabel = pParse->aLabel;
65232   p->readOnly = 1;
65233   p->bIsReader = 0;
65234   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
65235     u8 opcode = pOp->opcode;
65236 
65237     /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
65238     ** cases from this switch! */
65239     switch( opcode ){
65240       case OP_Function:
65241       case OP_AggStep: {
65242         if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
65243         break;
65244       }
65245       case OP_Transaction: {
65246         if( pOp->p2!=0 ) p->readOnly = 0;
65247         /* fall thru */
65248       }
65249       case OP_AutoCommit:
65250       case OP_Savepoint: {
65251         p->bIsReader = 1;
65252         break;
65253       }
65254 #ifndef SQLITE_OMIT_WAL
65255       case OP_Checkpoint:
65256 #endif
65257       case OP_Vacuum:
65258       case OP_JournalMode: {
65259         p->readOnly = 0;
65260         p->bIsReader = 1;
65261         break;
65262       }
65263 #ifndef SQLITE_OMIT_VIRTUALTABLE
65264       case OP_VUpdate: {
65265         if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
65266         break;
65267       }
65268       case OP_VFilter: {
65269         int n;
65270         assert( p->nOp - i >= 3 );
65271         assert( pOp[-1].opcode==OP_Integer );
65272         n = pOp[-1].p1;
65273         if( n>nMaxArgs ) nMaxArgs = n;
65274         break;
65275       }
65276 #endif
65277       case OP_Next:
65278       case OP_NextIfOpen:
65279       case OP_SorterNext: {
65280         pOp->p4.xAdvance = sqlite3BtreeNext;
65281         pOp->p4type = P4_ADVANCE;
65282         break;
65283       }
65284       case OP_Prev:
65285       case OP_PrevIfOpen: {
65286         pOp->p4.xAdvance = sqlite3BtreePrevious;
65287         pOp->p4type = P4_ADVANCE;
65288         break;
65289       }
65290     }
65291 
65292     pOp->opflags = sqlite3OpcodeProperty[opcode];
65293     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
65294       assert( -1-pOp->p2<pParse->nLabel );
65295       pOp->p2 = aLabel[-1-pOp->p2];
65296     }
65297   }
65298   sqlite3DbFree(p->db, pParse->aLabel);
65299   pParse->aLabel = 0;
65300   pParse->nLabel = 0;
65301   *pMaxFuncArgs = nMaxArgs;
65302   assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
65303 }
65304 
65305 /*
65306 ** Return the address of the next instruction to be inserted.
65307 */
65308 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
65309   assert( p->magic==VDBE_MAGIC_INIT );
65310   return p->nOp;
65311 }
65312 
65313 /*
65314 ** This function returns a pointer to the array of opcodes associated with
65315 ** the Vdbe passed as the first argument. It is the callers responsibility
65316 ** to arrange for the returned array to be eventually freed using the
65317 ** vdbeFreeOpArray() function.
65318 **
65319 ** Before returning, *pnOp is set to the number of entries in the returned
65320 ** array. Also, *pnMaxArg is set to the larger of its current value and
65321 ** the number of entries in the Vdbe.apArg[] array required to execute the
65322 ** returned program.
65323 */
65324 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
65325   VdbeOp *aOp = p->aOp;
65326   assert( aOp && !p->db->mallocFailed );
65327 
65328   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
65329   assert( DbMaskAllZero(p->btreeMask) );
65330 
65331   resolveP2Values(p, pnMaxArg);
65332   *pnOp = p->nOp;
65333   p->aOp = 0;
65334   return aOp;
65335 }
65336 
65337 /*
65338 ** Add a whole list of operations to the operation stack.  Return the
65339 ** address of the first operation added.
65340 */
65341 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
65342   int addr;
65343   assert( p->magic==VDBE_MAGIC_INIT );
65344   if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
65345     return 0;
65346   }
65347   addr = p->nOp;
65348   if( ALWAYS(nOp>0) ){
65349     int i;
65350     VdbeOpList const *pIn = aOp;
65351     for(i=0; i<nOp; i++, pIn++){
65352       int p2 = pIn->p2;
65353       VdbeOp *pOut = &p->aOp[i+addr];
65354       pOut->opcode = pIn->opcode;
65355       pOut->p1 = pIn->p1;
65356       if( p2<0 ){
65357         assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
65358         pOut->p2 = addr + ADDR(p2);
65359       }else{
65360         pOut->p2 = p2;
65361       }
65362       pOut->p3 = pIn->p3;
65363       pOut->p4type = P4_NOTUSED;
65364       pOut->p4.p = 0;
65365       pOut->p5 = 0;
65366 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
65367       pOut->zComment = 0;
65368 #endif
65369 #ifdef SQLITE_VDBE_COVERAGE
65370       pOut->iSrcLine = iLineno+i;
65371 #else
65372       (void)iLineno;
65373 #endif
65374 #ifdef SQLITE_DEBUG
65375       if( p->db->flags & SQLITE_VdbeAddopTrace ){
65376         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
65377       }
65378 #endif
65379     }
65380     p->nOp += nOp;
65381   }
65382   return addr;
65383 }
65384 
65385 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
65386 /*
65387 ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
65388 */
65389 SQLITE_PRIVATE void sqlite3VdbeScanStatus(
65390   Vdbe *p,                        /* VM to add scanstatus() to */
65391   int addrExplain,                /* Address of OP_Explain (or 0) */
65392   int addrLoop,                   /* Address of loop counter */
65393   int addrVisit,                  /* Address of rows visited counter */
65394   LogEst nEst,                    /* Estimated number of output rows */
65395   const char *zName               /* Name of table or index being scanned */
65396 ){
65397   int nByte = (p->nScan+1) * sizeof(ScanStatus);
65398   ScanStatus *aNew;
65399   aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
65400   if( aNew ){
65401     ScanStatus *pNew = &aNew[p->nScan++];
65402     pNew->addrExplain = addrExplain;
65403     pNew->addrLoop = addrLoop;
65404     pNew->addrVisit = addrVisit;
65405     pNew->nEst = nEst;
65406     pNew->zName = sqlite3DbStrDup(p->db, zName);
65407     p->aScan = aNew;
65408   }
65409 }
65410 #endif
65411 
65412 
65413 /*
65414 ** Change the value of the P1 operand for a specific instruction.
65415 ** This routine is useful when a large program is loaded from a
65416 ** static array using sqlite3VdbeAddOpList but we want to make a
65417 ** few minor changes to the program.
65418 */
65419 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
65420   assert( p!=0 );
65421   if( ((u32)p->nOp)>addr ){
65422     p->aOp[addr].p1 = val;
65423   }
65424 }
65425 
65426 /*
65427 ** Change the value of the P2 operand for a specific instruction.
65428 ** This routine is useful for setting a jump destination.
65429 */
65430 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
65431   assert( p!=0 );
65432   if( ((u32)p->nOp)>addr ){
65433     p->aOp[addr].p2 = val;
65434   }
65435 }
65436 
65437 /*
65438 ** Change the value of the P3 operand for a specific instruction.
65439 */
65440 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
65441   assert( p!=0 );
65442   if( ((u32)p->nOp)>addr ){
65443     p->aOp[addr].p3 = val;
65444   }
65445 }
65446 
65447 /*
65448 ** Change the value of the P5 operand for the most recently
65449 ** added operation.
65450 */
65451 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
65452   assert( p!=0 );
65453   if( p->aOp ){
65454     assert( p->nOp>0 );
65455     p->aOp[p->nOp-1].p5 = val;
65456   }
65457 }
65458 
65459 /*
65460 ** Change the P2 operand of instruction addr so that it points to
65461 ** the address of the next instruction to be coded.
65462 */
65463 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
65464   sqlite3VdbeChangeP2(p, addr, p->nOp);
65465   p->pParse->iFixedOp = p->nOp - 1;
65466 }
65467 
65468 
65469 /*
65470 ** If the input FuncDef structure is ephemeral, then free it.  If
65471 ** the FuncDef is not ephermal, then do nothing.
65472 */
65473 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
65474   if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
65475     sqlite3DbFree(db, pDef);
65476   }
65477 }
65478 
65479 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
65480 
65481 /*
65482 ** Delete a P4 value if necessary.
65483 */
65484 static void freeP4(sqlite3 *db, int p4type, void *p4){
65485   if( p4 ){
65486     assert( db );
65487     switch( p4type ){
65488       case P4_REAL:
65489       case P4_INT64:
65490       case P4_DYNAMIC:
65491       case P4_INTARRAY: {
65492         sqlite3DbFree(db, p4);
65493         break;
65494       }
65495       case P4_KEYINFO: {
65496         if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
65497         break;
65498       }
65499       case P4_MPRINTF: {
65500         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
65501         break;
65502       }
65503       case P4_FUNCDEF: {
65504         freeEphemeralFunction(db, (FuncDef*)p4);
65505         break;
65506       }
65507       case P4_MEM: {
65508         if( db->pnBytesFreed==0 ){
65509           sqlite3ValueFree((sqlite3_value*)p4);
65510         }else{
65511           Mem *p = (Mem*)p4;
65512           if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
65513           sqlite3DbFree(db, p);
65514         }
65515         break;
65516       }
65517       case P4_VTAB : {
65518         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
65519         break;
65520       }
65521     }
65522   }
65523 }
65524 
65525 /*
65526 ** Free the space allocated for aOp and any p4 values allocated for the
65527 ** opcodes contained within. If aOp is not NULL it is assumed to contain
65528 ** nOp entries.
65529 */
65530 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
65531   if( aOp ){
65532     Op *pOp;
65533     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
65534       freeP4(db, pOp->p4type, pOp->p4.p);
65535 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
65536       sqlite3DbFree(db, pOp->zComment);
65537 #endif
65538     }
65539   }
65540   sqlite3DbFree(db, aOp);
65541 }
65542 
65543 /*
65544 ** Link the SubProgram object passed as the second argument into the linked
65545 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
65546 ** objects when the VM is no longer required.
65547 */
65548 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
65549   p->pNext = pVdbe->pProgram;
65550   pVdbe->pProgram = p;
65551 }
65552 
65553 /*
65554 ** Change the opcode at addr into OP_Noop
65555 */
65556 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
65557   if( addr<p->nOp ){
65558     VdbeOp *pOp = &p->aOp[addr];
65559     sqlite3 *db = p->db;
65560     freeP4(db, pOp->p4type, pOp->p4.p);
65561     memset(pOp, 0, sizeof(pOp[0]));
65562     pOp->opcode = OP_Noop;
65563     if( addr==p->nOp-1 ) p->nOp--;
65564   }
65565 }
65566 
65567 /*
65568 ** If the last opcode is "op" and it is not a jump destination,
65569 ** then remove it.  Return true if and only if an opcode was removed.
65570 */
65571 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
65572   if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
65573     sqlite3VdbeChangeToNoop(p, p->nOp-1);
65574     return 1;
65575   }else{
65576     return 0;
65577   }
65578 }
65579 
65580 /*
65581 ** Change the value of the P4 operand for a specific instruction.
65582 ** This routine is useful when a large program is loaded from a
65583 ** static array using sqlite3VdbeAddOpList but we want to make a
65584 ** few minor changes to the program.
65585 **
65586 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
65587 ** the string is made into memory obtained from sqlite3_malloc().
65588 ** A value of n==0 means copy bytes of zP4 up to and including the
65589 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
65590 **
65591 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
65592 ** to a string or structure that is guaranteed to exist for the lifetime of
65593 ** the Vdbe. In these cases we can just copy the pointer.
65594 **
65595 ** If addr<0 then change P4 on the most recently inserted instruction.
65596 */
65597 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
65598   Op *pOp;
65599   sqlite3 *db;
65600   assert( p!=0 );
65601   db = p->db;
65602   assert( p->magic==VDBE_MAGIC_INIT );
65603   if( p->aOp==0 || db->mallocFailed ){
65604     if( n!=P4_VTAB ){
65605       freeP4(db, n, (void*)*(char**)&zP4);
65606     }
65607     return;
65608   }
65609   assert( p->nOp>0 );
65610   assert( addr<p->nOp );
65611   if( addr<0 ){
65612     addr = p->nOp - 1;
65613   }
65614   pOp = &p->aOp[addr];
65615   assert( pOp->p4type==P4_NOTUSED
65616        || pOp->p4type==P4_INT32
65617        || pOp->p4type==P4_KEYINFO );
65618   freeP4(db, pOp->p4type, pOp->p4.p);
65619   pOp->p4.p = 0;
65620   if( n==P4_INT32 ){
65621     /* Note: this cast is safe, because the origin data point was an int
65622     ** that was cast to a (const char *). */
65623     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
65624     pOp->p4type = P4_INT32;
65625   }else if( zP4==0 ){
65626     pOp->p4.p = 0;
65627     pOp->p4type = P4_NOTUSED;
65628   }else if( n==P4_KEYINFO ){
65629     pOp->p4.p = (void*)zP4;
65630     pOp->p4type = P4_KEYINFO;
65631   }else if( n==P4_VTAB ){
65632     pOp->p4.p = (void*)zP4;
65633     pOp->p4type = P4_VTAB;
65634     sqlite3VtabLock((VTable *)zP4);
65635     assert( ((VTable *)zP4)->db==p->db );
65636   }else if( n<0 ){
65637     pOp->p4.p = (void*)zP4;
65638     pOp->p4type = (signed char)n;
65639   }else{
65640     if( n==0 ) n = sqlite3Strlen30(zP4);
65641     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
65642     pOp->p4type = P4_DYNAMIC;
65643   }
65644 }
65645 
65646 /*
65647 ** Set the P4 on the most recently added opcode to the KeyInfo for the
65648 ** index given.
65649 */
65650 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
65651   Vdbe *v = pParse->pVdbe;
65652   assert( v!=0 );
65653   assert( pIdx!=0 );
65654   sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
65655                       P4_KEYINFO);
65656 }
65657 
65658 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
65659 /*
65660 ** Change the comment on the most recently coded instruction.  Or
65661 ** insert a No-op and add the comment to that new instruction.  This
65662 ** makes the code easier to read during debugging.  None of this happens
65663 ** in a production build.
65664 */
65665 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
65666   assert( p->nOp>0 || p->aOp==0 );
65667   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
65668   if( p->nOp ){
65669     assert( p->aOp );
65670     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
65671     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
65672   }
65673 }
65674 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
65675   va_list ap;
65676   if( p ){
65677     va_start(ap, zFormat);
65678     vdbeVComment(p, zFormat, ap);
65679     va_end(ap);
65680   }
65681 }
65682 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
65683   va_list ap;
65684   if( p ){
65685     sqlite3VdbeAddOp0(p, OP_Noop);
65686     va_start(ap, zFormat);
65687     vdbeVComment(p, zFormat, ap);
65688     va_end(ap);
65689   }
65690 }
65691 #endif  /* NDEBUG */
65692 
65693 #ifdef SQLITE_VDBE_COVERAGE
65694 /*
65695 ** Set the value if the iSrcLine field for the previously coded instruction.
65696 */
65697 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
65698   sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
65699 }
65700 #endif /* SQLITE_VDBE_COVERAGE */
65701 
65702 /*
65703 ** Return the opcode for a given address.  If the address is -1, then
65704 ** return the most recently inserted opcode.
65705 **
65706 ** If a memory allocation error has occurred prior to the calling of this
65707 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
65708 ** is readable but not writable, though it is cast to a writable value.
65709 ** The return of a dummy opcode allows the call to continue functioning
65710 ** after an OOM fault without having to check to see if the return from
65711 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
65712 ** dummy will never be written to.  This is verified by code inspection and
65713 ** by running with Valgrind.
65714 */
65715 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
65716   /* C89 specifies that the constant "dummy" will be initialized to all
65717   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
65718   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
65719   assert( p->magic==VDBE_MAGIC_INIT );
65720   if( addr<0 ){
65721     addr = p->nOp - 1;
65722   }
65723   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
65724   if( p->db->mallocFailed ){
65725     return (VdbeOp*)&dummy;
65726   }else{
65727     return &p->aOp[addr];
65728   }
65729 }
65730 
65731 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
65732 /*
65733 ** Return an integer value for one of the parameters to the opcode pOp
65734 ** determined by character c.
65735 */
65736 static int translateP(char c, const Op *pOp){
65737   if( c=='1' ) return pOp->p1;
65738   if( c=='2' ) return pOp->p2;
65739   if( c=='3' ) return pOp->p3;
65740   if( c=='4' ) return pOp->p4.i;
65741   return pOp->p5;
65742 }
65743 
65744 /*
65745 ** Compute a string for the "comment" field of a VDBE opcode listing.
65746 **
65747 ** The Synopsis: field in comments in the vdbe.c source file gets converted
65748 ** to an extra string that is appended to the sqlite3OpcodeName().  In the
65749 ** absence of other comments, this synopsis becomes the comment on the opcode.
65750 ** Some translation occurs:
65751 **
65752 **       "PX"      ->  "r[X]"
65753 **       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
65754 **       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
65755 **       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
65756 */
65757 static int displayComment(
65758   const Op *pOp,     /* The opcode to be commented */
65759   const char *zP4,   /* Previously obtained value for P4 */
65760   char *zTemp,       /* Write result here */
65761   int nTemp          /* Space available in zTemp[] */
65762 ){
65763   const char *zOpName;
65764   const char *zSynopsis;
65765   int nOpName;
65766   int ii, jj;
65767   zOpName = sqlite3OpcodeName(pOp->opcode);
65768   nOpName = sqlite3Strlen30(zOpName);
65769   if( zOpName[nOpName+1] ){
65770     int seenCom = 0;
65771     char c;
65772     zSynopsis = zOpName += nOpName + 1;
65773     for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
65774       if( c=='P' ){
65775         c = zSynopsis[++ii];
65776         if( c=='4' ){
65777           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
65778         }else if( c=='X' ){
65779           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
65780           seenCom = 1;
65781         }else{
65782           int v1 = translateP(c, pOp);
65783           int v2;
65784           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
65785           if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
65786             ii += 3;
65787             jj += sqlite3Strlen30(zTemp+jj);
65788             v2 = translateP(zSynopsis[ii], pOp);
65789             if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
65790               ii += 2;
65791               v2++;
65792             }
65793             if( v2>1 ){
65794               sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
65795             }
65796           }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
65797             ii += 4;
65798           }
65799         }
65800         jj += sqlite3Strlen30(zTemp+jj);
65801       }else{
65802         zTemp[jj++] = c;
65803       }
65804     }
65805     if( !seenCom && jj<nTemp-5 && pOp->zComment ){
65806       sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
65807       jj += sqlite3Strlen30(zTemp+jj);
65808     }
65809     if( jj<nTemp ) zTemp[jj] = 0;
65810   }else if( pOp->zComment ){
65811     sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
65812     jj = sqlite3Strlen30(zTemp);
65813   }else{
65814     zTemp[0] = 0;
65815     jj = 0;
65816   }
65817   return jj;
65818 }
65819 #endif /* SQLITE_DEBUG */
65820 
65821 
65822 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
65823      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
65824 /*
65825 ** Compute a string that describes the P4 parameter for an opcode.
65826 ** Use zTemp for any required temporary buffer space.
65827 */
65828 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
65829   char *zP4 = zTemp;
65830   assert( nTemp>=20 );
65831   switch( pOp->p4type ){
65832     case P4_KEYINFO: {
65833       int i, j;
65834       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
65835       assert( pKeyInfo->aSortOrder!=0 );
65836       sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
65837       i = sqlite3Strlen30(zTemp);
65838       for(j=0; j<pKeyInfo->nField; j++){
65839         CollSeq *pColl = pKeyInfo->aColl[j];
65840         const char *zColl = pColl ? pColl->zName : "nil";
65841         int n = sqlite3Strlen30(zColl);
65842         if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
65843           zColl = "B";
65844           n = 1;
65845         }
65846         if( i+n>nTemp-6 ){
65847           memcpy(&zTemp[i],",...",4);
65848           break;
65849         }
65850         zTemp[i++] = ',';
65851         if( pKeyInfo->aSortOrder[j] ){
65852           zTemp[i++] = '-';
65853         }
65854         memcpy(&zTemp[i], zColl, n+1);
65855         i += n;
65856       }
65857       zTemp[i++] = ')';
65858       zTemp[i] = 0;
65859       assert( i<nTemp );
65860       break;
65861     }
65862     case P4_COLLSEQ: {
65863       CollSeq *pColl = pOp->p4.pColl;
65864       sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
65865       break;
65866     }
65867     case P4_FUNCDEF: {
65868       FuncDef *pDef = pOp->p4.pFunc;
65869       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
65870       break;
65871     }
65872     case P4_INT64: {
65873       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
65874       break;
65875     }
65876     case P4_INT32: {
65877       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
65878       break;
65879     }
65880     case P4_REAL: {
65881       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
65882       break;
65883     }
65884     case P4_MEM: {
65885       Mem *pMem = pOp->p4.pMem;
65886       if( pMem->flags & MEM_Str ){
65887         zP4 = pMem->z;
65888       }else if( pMem->flags & MEM_Int ){
65889         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
65890       }else if( pMem->flags & MEM_Real ){
65891         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
65892       }else if( pMem->flags & MEM_Null ){
65893         sqlite3_snprintf(nTemp, zTemp, "NULL");
65894       }else{
65895         assert( pMem->flags & MEM_Blob );
65896         zP4 = "(blob)";
65897       }
65898       break;
65899     }
65900 #ifndef SQLITE_OMIT_VIRTUALTABLE
65901     case P4_VTAB: {
65902       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
65903       sqlite3_snprintf(nTemp, zTemp, "vtab:%p", pVtab);
65904       break;
65905     }
65906 #endif
65907     case P4_INTARRAY: {
65908       sqlite3_snprintf(nTemp, zTemp, "intarray");
65909       break;
65910     }
65911     case P4_SUBPROGRAM: {
65912       sqlite3_snprintf(nTemp, zTemp, "program");
65913       break;
65914     }
65915     case P4_ADVANCE: {
65916       zTemp[0] = 0;
65917       break;
65918     }
65919     default: {
65920       zP4 = pOp->p4.z;
65921       if( zP4==0 ){
65922         zP4 = zTemp;
65923         zTemp[0] = 0;
65924       }
65925     }
65926   }
65927   assert( zP4!=0 );
65928   return zP4;
65929 }
65930 #endif
65931 
65932 /*
65933 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
65934 **
65935 ** The prepared statements need to know in advance the complete set of
65936 ** attached databases that will be use.  A mask of these databases
65937 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
65938 ** p->btreeMask of databases that will require a lock.
65939 */
65940 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
65941   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
65942   assert( i<(int)sizeof(p->btreeMask)*8 );
65943   DbMaskSet(p->btreeMask, i);
65944   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
65945     DbMaskSet(p->lockMask, i);
65946   }
65947 }
65948 
65949 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
65950 /*
65951 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
65952 ** this routine obtains the mutex associated with each BtShared structure
65953 ** that may be accessed by the VM passed as an argument. In doing so it also
65954 ** sets the BtShared.db member of each of the BtShared structures, ensuring
65955 ** that the correct busy-handler callback is invoked if required.
65956 **
65957 ** If SQLite is not threadsafe but does support shared-cache mode, then
65958 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
65959 ** of all of BtShared structures accessible via the database handle
65960 ** associated with the VM.
65961 **
65962 ** If SQLite is not threadsafe and does not support shared-cache mode, this
65963 ** function is a no-op.
65964 **
65965 ** The p->btreeMask field is a bitmask of all btrees that the prepared
65966 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
65967 ** corresponding to btrees that use shared cache.  Then the runtime of
65968 ** this routine is N*N.  But as N is rarely more than 1, this should not
65969 ** be a problem.
65970 */
65971 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
65972   int i;
65973   sqlite3 *db;
65974   Db *aDb;
65975   int nDb;
65976   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
65977   db = p->db;
65978   aDb = db->aDb;
65979   nDb = db->nDb;
65980   for(i=0; i<nDb; i++){
65981     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
65982       sqlite3BtreeEnter(aDb[i].pBt);
65983     }
65984   }
65985 }
65986 #endif
65987 
65988 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
65989 /*
65990 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
65991 */
65992 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
65993   int i;
65994   sqlite3 *db;
65995   Db *aDb;
65996   int nDb;
65997   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
65998   db = p->db;
65999   aDb = db->aDb;
66000   nDb = db->nDb;
66001   for(i=0; i<nDb; i++){
66002     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
66003       sqlite3BtreeLeave(aDb[i].pBt);
66004     }
66005   }
66006 }
66007 #endif
66008 
66009 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
66010 /*
66011 ** Print a single opcode.  This routine is used for debugging only.
66012 */
66013 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
66014   char *zP4;
66015   char zPtr[50];
66016   char zCom[100];
66017   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
66018   if( pOut==0 ) pOut = stdout;
66019   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
66020 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
66021   displayComment(pOp, zP4, zCom, sizeof(zCom));
66022 #else
66023   zCom[0] = 0;
66024 #endif
66025   /* NB:  The sqlite3OpcodeName() function is implemented by code created
66026   ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
66027   ** information from the vdbe.c source text */
66028   fprintf(pOut, zFormat1, pc,
66029       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
66030       zCom
66031   );
66032   fflush(pOut);
66033 }
66034 #endif
66035 
66036 /*
66037 ** Release an array of N Mem elements
66038 */
66039 static void releaseMemArray(Mem *p, int N){
66040   if( p && N ){
66041     Mem *pEnd = &p[N];
66042     sqlite3 *db = p->db;
66043     u8 malloc_failed = db->mallocFailed;
66044     if( db->pnBytesFreed ){
66045       do{
66046         if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
66047       }while( (++p)<pEnd );
66048       return;
66049     }
66050     do{
66051       assert( (&p[1])==pEnd || p[0].db==p[1].db );
66052       assert( sqlite3VdbeCheckMemInvariants(p) );
66053 
66054       /* This block is really an inlined version of sqlite3VdbeMemRelease()
66055       ** that takes advantage of the fact that the memory cell value is
66056       ** being set to NULL after releasing any dynamic resources.
66057       **
66058       ** The justification for duplicating code is that according to
66059       ** callgrind, this causes a certain test case to hit the CPU 4.7
66060       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
66061       ** sqlite3MemRelease() were called from here. With -O2, this jumps
66062       ** to 6.6 percent. The test case is inserting 1000 rows into a table
66063       ** with no indexes using a single prepared INSERT statement, bind()
66064       ** and reset(). Inserts are grouped into a transaction.
66065       */
66066       testcase( p->flags & MEM_Agg );
66067       testcase( p->flags & MEM_Dyn );
66068       testcase( p->flags & MEM_Frame );
66069       testcase( p->flags & MEM_RowSet );
66070       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
66071         sqlite3VdbeMemRelease(p);
66072       }else if( p->szMalloc ){
66073         sqlite3DbFree(db, p->zMalloc);
66074         p->szMalloc = 0;
66075       }
66076 
66077       p->flags = MEM_Undefined;
66078     }while( (++p)<pEnd );
66079     db->mallocFailed = malloc_failed;
66080   }
66081 }
66082 
66083 /*
66084 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
66085 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
66086 */
66087 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
66088   int i;
66089   Mem *aMem = VdbeFrameMem(p);
66090   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
66091   for(i=0; i<p->nChildCsr; i++){
66092     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
66093   }
66094   releaseMemArray(aMem, p->nChildMem);
66095   sqlite3DbFree(p->v->db, p);
66096 }
66097 
66098 #ifndef SQLITE_OMIT_EXPLAIN
66099 /*
66100 ** Give a listing of the program in the virtual machine.
66101 **
66102 ** The interface is the same as sqlite3VdbeExec().  But instead of
66103 ** running the code, it invokes the callback once for each instruction.
66104 ** This feature is used to implement "EXPLAIN".
66105 **
66106 ** When p->explain==1, each instruction is listed.  When
66107 ** p->explain==2, only OP_Explain instructions are listed and these
66108 ** are shown in a different format.  p->explain==2 is used to implement
66109 ** EXPLAIN QUERY PLAN.
66110 **
66111 ** When p->explain==1, first the main program is listed, then each of
66112 ** the trigger subprograms are listed one by one.
66113 */
66114 SQLITE_PRIVATE int sqlite3VdbeList(
66115   Vdbe *p                   /* The VDBE */
66116 ){
66117   int nRow;                            /* Stop when row count reaches this */
66118   int nSub = 0;                        /* Number of sub-vdbes seen so far */
66119   SubProgram **apSub = 0;              /* Array of sub-vdbes */
66120   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
66121   sqlite3 *db = p->db;                 /* The database connection */
66122   int i;                               /* Loop counter */
66123   int rc = SQLITE_OK;                  /* Return code */
66124   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
66125 
66126   assert( p->explain );
66127   assert( p->magic==VDBE_MAGIC_RUN );
66128   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
66129 
66130   /* Even though this opcode does not use dynamic strings for
66131   ** the result, result columns may become dynamic if the user calls
66132   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
66133   */
66134   releaseMemArray(pMem, 8);
66135   p->pResultSet = 0;
66136 
66137   if( p->rc==SQLITE_NOMEM ){
66138     /* This happens if a malloc() inside a call to sqlite3_column_text() or
66139     ** sqlite3_column_text16() failed.  */
66140     db->mallocFailed = 1;
66141     return SQLITE_ERROR;
66142   }
66143 
66144   /* When the number of output rows reaches nRow, that means the
66145   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
66146   ** nRow is the sum of the number of rows in the main program, plus
66147   ** the sum of the number of rows in all trigger subprograms encountered
66148   ** so far.  The nRow value will increase as new trigger subprograms are
66149   ** encountered, but p->pc will eventually catch up to nRow.
66150   */
66151   nRow = p->nOp;
66152   if( p->explain==1 ){
66153     /* The first 8 memory cells are used for the result set.  So we will
66154     ** commandeer the 9th cell to use as storage for an array of pointers
66155     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
66156     ** cells.  */
66157     assert( p->nMem>9 );
66158     pSub = &p->aMem[9];
66159     if( pSub->flags&MEM_Blob ){
66160       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
66161       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
66162       nSub = pSub->n/sizeof(Vdbe*);
66163       apSub = (SubProgram **)pSub->z;
66164     }
66165     for(i=0; i<nSub; i++){
66166       nRow += apSub[i]->nOp;
66167     }
66168   }
66169 
66170   do{
66171     i = p->pc++;
66172   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
66173   if( i>=nRow ){
66174     p->rc = SQLITE_OK;
66175     rc = SQLITE_DONE;
66176   }else if( db->u1.isInterrupted ){
66177     p->rc = SQLITE_INTERRUPT;
66178     rc = SQLITE_ERROR;
66179     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
66180   }else{
66181     char *zP4;
66182     Op *pOp;
66183     if( i<p->nOp ){
66184       /* The output line number is small enough that we are still in the
66185       ** main program. */
66186       pOp = &p->aOp[i];
66187     }else{
66188       /* We are currently listing subprograms.  Figure out which one and
66189       ** pick up the appropriate opcode. */
66190       int j;
66191       i -= p->nOp;
66192       for(j=0; i>=apSub[j]->nOp; j++){
66193         i -= apSub[j]->nOp;
66194       }
66195       pOp = &apSub[j]->aOp[i];
66196     }
66197     if( p->explain==1 ){
66198       pMem->flags = MEM_Int;
66199       pMem->u.i = i;                                /* Program counter */
66200       pMem++;
66201 
66202       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
66203       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
66204       assert( pMem->z!=0 );
66205       pMem->n = sqlite3Strlen30(pMem->z);
66206       pMem->enc = SQLITE_UTF8;
66207       pMem++;
66208 
66209       /* When an OP_Program opcode is encounter (the only opcode that has
66210       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
66211       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
66212       ** has not already been seen.
66213       */
66214       if( pOp->p4type==P4_SUBPROGRAM ){
66215         int nByte = (nSub+1)*sizeof(SubProgram*);
66216         int j;
66217         for(j=0; j<nSub; j++){
66218           if( apSub[j]==pOp->p4.pProgram ) break;
66219         }
66220         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
66221           apSub = (SubProgram **)pSub->z;
66222           apSub[nSub++] = pOp->p4.pProgram;
66223           pSub->flags |= MEM_Blob;
66224           pSub->n = nSub*sizeof(SubProgram*);
66225         }
66226       }
66227     }
66228 
66229     pMem->flags = MEM_Int;
66230     pMem->u.i = pOp->p1;                          /* P1 */
66231     pMem++;
66232 
66233     pMem->flags = MEM_Int;
66234     pMem->u.i = pOp->p2;                          /* P2 */
66235     pMem++;
66236 
66237     pMem->flags = MEM_Int;
66238     pMem->u.i = pOp->p3;                          /* P3 */
66239     pMem++;
66240 
66241     if( sqlite3VdbeMemClearAndResize(pMem, 32) ){ /* P4 */
66242       assert( p->db->mallocFailed );
66243       return SQLITE_ERROR;
66244     }
66245     pMem->flags = MEM_Str|MEM_Term;
66246     zP4 = displayP4(pOp, pMem->z, 32);
66247     if( zP4!=pMem->z ){
66248       sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
66249     }else{
66250       assert( pMem->z!=0 );
66251       pMem->n = sqlite3Strlen30(pMem->z);
66252       pMem->enc = SQLITE_UTF8;
66253     }
66254     pMem++;
66255 
66256     if( p->explain==1 ){
66257       if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
66258         assert( p->db->mallocFailed );
66259         return SQLITE_ERROR;
66260       }
66261       pMem->flags = MEM_Str|MEM_Term;
66262       pMem->n = 2;
66263       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
66264       pMem->enc = SQLITE_UTF8;
66265       pMem++;
66266 
66267 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
66268       if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
66269         assert( p->db->mallocFailed );
66270         return SQLITE_ERROR;
66271       }
66272       pMem->flags = MEM_Str|MEM_Term;
66273       pMem->n = displayComment(pOp, zP4, pMem->z, 500);
66274       pMem->enc = SQLITE_UTF8;
66275 #else
66276       pMem->flags = MEM_Null;                       /* Comment */
66277 #endif
66278     }
66279 
66280     p->nResColumn = 8 - 4*(p->explain-1);
66281     p->pResultSet = &p->aMem[1];
66282     p->rc = SQLITE_OK;
66283     rc = SQLITE_ROW;
66284   }
66285   return rc;
66286 }
66287 #endif /* SQLITE_OMIT_EXPLAIN */
66288 
66289 #ifdef SQLITE_DEBUG
66290 /*
66291 ** Print the SQL that was used to generate a VDBE program.
66292 */
66293 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
66294   const char *z = 0;
66295   if( p->zSql ){
66296     z = p->zSql;
66297   }else if( p->nOp>=1 ){
66298     const VdbeOp *pOp = &p->aOp[0];
66299     if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
66300       z = pOp->p4.z;
66301       while( sqlite3Isspace(*z) ) z++;
66302     }
66303   }
66304   if( z ) printf("SQL: [%s]\n", z);
66305 }
66306 #endif
66307 
66308 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
66309 /*
66310 ** Print an IOTRACE message showing SQL content.
66311 */
66312 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
66313   int nOp = p->nOp;
66314   VdbeOp *pOp;
66315   if( sqlite3IoTrace==0 ) return;
66316   if( nOp<1 ) return;
66317   pOp = &p->aOp[0];
66318   if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
66319     int i, j;
66320     char z[1000];
66321     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
66322     for(i=0; sqlite3Isspace(z[i]); i++){}
66323     for(j=0; z[i]; i++){
66324       if( sqlite3Isspace(z[i]) ){
66325         if( z[i-1]!=' ' ){
66326           z[j++] = ' ';
66327         }
66328       }else{
66329         z[j++] = z[i];
66330       }
66331     }
66332     z[j] = 0;
66333     sqlite3IoTrace("SQL %s\n", z);
66334   }
66335 }
66336 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
66337 
66338 /*
66339 ** Allocate space from a fixed size buffer and return a pointer to
66340 ** that space.  If insufficient space is available, return NULL.
66341 **
66342 ** The pBuf parameter is the initial value of a pointer which will
66343 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
66344 ** NULL, it means that memory space has already been allocated and that
66345 ** this routine should not allocate any new memory.  When pBuf is not
66346 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
66347 ** is NULL.
66348 **
66349 ** nByte is the number of bytes of space needed.
66350 **
66351 ** *ppFrom points to available space and pEnd points to the end of the
66352 ** available space.  When space is allocated, *ppFrom is advanced past
66353 ** the end of the allocated space.
66354 **
66355 ** *pnByte is a counter of the number of bytes of space that have failed
66356 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
66357 ** request, then increment *pnByte by the amount of the request.
66358 */
66359 static void *allocSpace(
66360   void *pBuf,          /* Where return pointer will be stored */
66361   int nByte,           /* Number of bytes to allocate */
66362   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
66363   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
66364   int *pnByte          /* If allocation cannot be made, increment *pnByte */
66365 ){
66366   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
66367   if( pBuf ) return pBuf;
66368   nByte = ROUND8(nByte);
66369   if( &(*ppFrom)[nByte] <= pEnd ){
66370     pBuf = (void*)*ppFrom;
66371     *ppFrom += nByte;
66372   }else{
66373     *pnByte += nByte;
66374   }
66375   return pBuf;
66376 }
66377 
66378 /*
66379 ** Rewind the VDBE back to the beginning in preparation for
66380 ** running it.
66381 */
66382 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
66383 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
66384   int i;
66385 #endif
66386   assert( p!=0 );
66387   assert( p->magic==VDBE_MAGIC_INIT );
66388 
66389   /* There should be at least one opcode.
66390   */
66391   assert( p->nOp>0 );
66392 
66393   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
66394   p->magic = VDBE_MAGIC_RUN;
66395 
66396 #ifdef SQLITE_DEBUG
66397   for(i=1; i<p->nMem; i++){
66398     assert( p->aMem[i].db==p->db );
66399   }
66400 #endif
66401   p->pc = -1;
66402   p->rc = SQLITE_OK;
66403   p->errorAction = OE_Abort;
66404   p->magic = VDBE_MAGIC_RUN;
66405   p->nChange = 0;
66406   p->cacheCtr = 1;
66407   p->minWriteFileFormat = 255;
66408   p->iStatement = 0;
66409   p->nFkConstraint = 0;
66410 #ifdef VDBE_PROFILE
66411   for(i=0; i<p->nOp; i++){
66412     p->aOp[i].cnt = 0;
66413     p->aOp[i].cycles = 0;
66414   }
66415 #endif
66416 }
66417 
66418 /*
66419 ** Prepare a virtual machine for execution for the first time after
66420 ** creating the virtual machine.  This involves things such
66421 ** as allocating registers and initializing the program counter.
66422 ** After the VDBE has be prepped, it can be executed by one or more
66423 ** calls to sqlite3VdbeExec().
66424 **
66425 ** This function may be called exactly once on each virtual machine.
66426 ** After this routine is called the VM has been "packaged" and is ready
66427 ** to run.  After this routine is called, further calls to
66428 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
66429 ** the Vdbe from the Parse object that helped generate it so that the
66430 ** the Vdbe becomes an independent entity and the Parse object can be
66431 ** destroyed.
66432 **
66433 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
66434 ** to its initial state after it has been run.
66435 */
66436 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
66437   Vdbe *p,                       /* The VDBE */
66438   Parse *pParse                  /* Parsing context */
66439 ){
66440   sqlite3 *db;                   /* The database connection */
66441   int nVar;                      /* Number of parameters */
66442   int nMem;                      /* Number of VM memory registers */
66443   int nCursor;                   /* Number of cursors required */
66444   int nArg;                      /* Number of arguments in subprograms */
66445   int nOnce;                     /* Number of OP_Once instructions */
66446   int n;                         /* Loop counter */
66447   u8 *zCsr;                      /* Memory available for allocation */
66448   u8 *zEnd;                      /* First byte past allocated memory */
66449   int nByte;                     /* How much extra memory is needed */
66450 
66451   assert( p!=0 );
66452   assert( p->nOp>0 );
66453   assert( pParse!=0 );
66454   assert( p->magic==VDBE_MAGIC_INIT );
66455   assert( pParse==p->pParse );
66456   db = p->db;
66457   assert( db->mallocFailed==0 );
66458   nVar = pParse->nVar;
66459   nMem = pParse->nMem;
66460   nCursor = pParse->nTab;
66461   nArg = pParse->nMaxArg;
66462   nOnce = pParse->nOnce;
66463   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
66464 
66465   /* For each cursor required, also allocate a memory cell. Memory
66466   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
66467   ** the vdbe program. Instead they are used to allocate space for
66468   ** VdbeCursor/BtCursor structures. The blob of memory associated with
66469   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
66470   ** stores the blob of memory associated with cursor 1, etc.
66471   **
66472   ** See also: allocateCursor().
66473   */
66474   nMem += nCursor;
66475 
66476   /* Allocate space for memory registers, SQL variables, VDBE cursors and
66477   ** an array to marshal SQL function arguments in.
66478   */
66479   zCsr = (u8*)&p->aOp[p->nOp];            /* Memory avaliable for allocation */
66480   zEnd = (u8*)&p->aOp[pParse->nOpAlloc];  /* First byte past end of zCsr[] */
66481 
66482   resolveP2Values(p, &nArg);
66483   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
66484   if( pParse->explain && nMem<10 ){
66485     nMem = 10;
66486   }
66487   memset(zCsr, 0, zEnd-zCsr);
66488   zCsr += (zCsr - (u8*)0)&7;
66489   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
66490   p->expired = 0;
66491 
66492   /* Memory for registers, parameters, cursor, etc, is allocated in two
66493   ** passes.  On the first pass, we try to reuse unused space at the
66494   ** end of the opcode array.  If we are unable to satisfy all memory
66495   ** requirements by reusing the opcode array tail, then the second
66496   ** pass will fill in the rest using a fresh allocation.
66497   **
66498   ** This two-pass approach that reuses as much memory as possible from
66499   ** the leftover space at the end of the opcode array can significantly
66500   ** reduce the amount of memory held by a prepared statement.
66501   */
66502   do {
66503     nByte = 0;
66504     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
66505     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
66506     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
66507     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
66508     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
66509                           &zCsr, zEnd, &nByte);
66510     p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
66511 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
66512     p->anExec = allocSpace(p->anExec, p->nOp*sizeof(i64), &zCsr, zEnd, &nByte);
66513 #endif
66514     if( nByte ){
66515       p->pFree = sqlite3DbMallocZero(db, nByte);
66516     }
66517     zCsr = p->pFree;
66518     zEnd = &zCsr[nByte];
66519   }while( nByte && !db->mallocFailed );
66520 
66521   p->nCursor = nCursor;
66522   p->nOnceFlag = nOnce;
66523   if( p->aVar ){
66524     p->nVar = (ynVar)nVar;
66525     for(n=0; n<nVar; n++){
66526       p->aVar[n].flags = MEM_Null;
66527       p->aVar[n].db = db;
66528     }
66529   }
66530   if( p->azVar && pParse->nzVar>0 ){
66531     p->nzVar = pParse->nzVar;
66532     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
66533     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
66534   }
66535   if( p->aMem ){
66536     p->aMem--;                      /* aMem[] goes from 1..nMem */
66537     p->nMem = nMem;                 /*       not from 0..nMem-1 */
66538     for(n=1; n<=nMem; n++){
66539       p->aMem[n].flags = MEM_Undefined;
66540       p->aMem[n].db = db;
66541     }
66542   }
66543   p->explain = pParse->explain;
66544   sqlite3VdbeRewind(p);
66545 }
66546 
66547 /*
66548 ** Close a VDBE cursor and release all the resources that cursor
66549 ** happens to hold.
66550 */
66551 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
66552   if( pCx==0 ){
66553     return;
66554   }
66555   sqlite3VdbeSorterClose(p->db, pCx);
66556   if( pCx->pBt ){
66557     sqlite3BtreeClose(pCx->pBt);
66558     /* The pCx->pCursor will be close automatically, if it exists, by
66559     ** the call above. */
66560   }else if( pCx->pCursor ){
66561     sqlite3BtreeCloseCursor(pCx->pCursor);
66562   }
66563 #ifndef SQLITE_OMIT_VIRTUALTABLE
66564   else if( pCx->pVtabCursor ){
66565     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
66566     const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
66567     assert( pVtabCursor->pVtab->nRef>0 );
66568     pVtabCursor->pVtab->nRef--;
66569     pModule->xClose(pVtabCursor);
66570   }
66571 #endif
66572 }
66573 
66574 /*
66575 ** Close all cursors in the current frame.
66576 */
66577 static void closeCursorsInFrame(Vdbe *p){
66578   if( p->apCsr ){
66579     int i;
66580     for(i=0; i<p->nCursor; i++){
66581       VdbeCursor *pC = p->apCsr[i];
66582       if( pC ){
66583         sqlite3VdbeFreeCursor(p, pC);
66584         p->apCsr[i] = 0;
66585       }
66586     }
66587   }
66588 }
66589 
66590 /*
66591 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
66592 ** is used, for example, when a trigger sub-program is halted to restore
66593 ** control to the main program.
66594 */
66595 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
66596   Vdbe *v = pFrame->v;
66597   closeCursorsInFrame(v);
66598 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
66599   v->anExec = pFrame->anExec;
66600 #endif
66601   v->aOnceFlag = pFrame->aOnceFlag;
66602   v->nOnceFlag = pFrame->nOnceFlag;
66603   v->aOp = pFrame->aOp;
66604   v->nOp = pFrame->nOp;
66605   v->aMem = pFrame->aMem;
66606   v->nMem = pFrame->nMem;
66607   v->apCsr = pFrame->apCsr;
66608   v->nCursor = pFrame->nCursor;
66609   v->db->lastRowid = pFrame->lastRowid;
66610   v->nChange = pFrame->nChange;
66611   v->db->nChange = pFrame->nDbChange;
66612   return pFrame->pc;
66613 }
66614 
66615 /*
66616 ** Close all cursors.
66617 **
66618 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
66619 ** cell array. This is necessary as the memory cell array may contain
66620 ** pointers to VdbeFrame objects, which may in turn contain pointers to
66621 ** open cursors.
66622 */
66623 static void closeAllCursors(Vdbe *p){
66624   if( p->pFrame ){
66625     VdbeFrame *pFrame;
66626     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
66627     sqlite3VdbeFrameRestore(pFrame);
66628     p->pFrame = 0;
66629     p->nFrame = 0;
66630   }
66631   assert( p->nFrame==0 );
66632   closeCursorsInFrame(p);
66633   if( p->aMem ){
66634     releaseMemArray(&p->aMem[1], p->nMem);
66635   }
66636   while( p->pDelFrame ){
66637     VdbeFrame *pDel = p->pDelFrame;
66638     p->pDelFrame = pDel->pParent;
66639     sqlite3VdbeFrameDelete(pDel);
66640   }
66641 
66642   /* Delete any auxdata allocations made by the VM */
66643   if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
66644   assert( p->pAuxData==0 );
66645 }
66646 
66647 /*
66648 ** Clean up the VM after a single run.
66649 */
66650 static void Cleanup(Vdbe *p){
66651   sqlite3 *db = p->db;
66652 
66653 #ifdef SQLITE_DEBUG
66654   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
66655   ** Vdbe.aMem[] arrays have already been cleaned up.  */
66656   int i;
66657   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
66658   if( p->aMem ){
66659     for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
66660   }
66661 #endif
66662 
66663   sqlite3DbFree(db, p->zErrMsg);
66664   p->zErrMsg = 0;
66665   p->pResultSet = 0;
66666 }
66667 
66668 /*
66669 ** Set the number of result columns that will be returned by this SQL
66670 ** statement. This is now set at compile time, rather than during
66671 ** execution of the vdbe program so that sqlite3_column_count() can
66672 ** be called on an SQL statement before sqlite3_step().
66673 */
66674 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
66675   Mem *pColName;
66676   int n;
66677   sqlite3 *db = p->db;
66678 
66679   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
66680   sqlite3DbFree(db, p->aColName);
66681   n = nResColumn*COLNAME_N;
66682   p->nResColumn = (u16)nResColumn;
66683   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
66684   if( p->aColName==0 ) return;
66685   while( n-- > 0 ){
66686     pColName->flags = MEM_Null;
66687     pColName->db = p->db;
66688     pColName++;
66689   }
66690 }
66691 
66692 /*
66693 ** Set the name of the idx'th column to be returned by the SQL statement.
66694 ** zName must be a pointer to a nul terminated string.
66695 **
66696 ** This call must be made after a call to sqlite3VdbeSetNumCols().
66697 **
66698 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
66699 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
66700 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
66701 */
66702 SQLITE_PRIVATE int sqlite3VdbeSetColName(
66703   Vdbe *p,                         /* Vdbe being configured */
66704   int idx,                         /* Index of column zName applies to */
66705   int var,                         /* One of the COLNAME_* constants */
66706   const char *zName,               /* Pointer to buffer containing name */
66707   void (*xDel)(void*)              /* Memory management strategy for zName */
66708 ){
66709   int rc;
66710   Mem *pColName;
66711   assert( idx<p->nResColumn );
66712   assert( var<COLNAME_N );
66713   if( p->db->mallocFailed ){
66714     assert( !zName || xDel!=SQLITE_DYNAMIC );
66715     return SQLITE_NOMEM;
66716   }
66717   assert( p->aColName!=0 );
66718   pColName = &(p->aColName[idx+var*p->nResColumn]);
66719   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
66720   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
66721   return rc;
66722 }
66723 
66724 /*
66725 ** A read or write transaction may or may not be active on database handle
66726 ** db. If a transaction is active, commit it. If there is a
66727 ** write-transaction spanning more than one database file, this routine
66728 ** takes care of the master journal trickery.
66729 */
66730 static int vdbeCommit(sqlite3 *db, Vdbe *p){
66731   int i;
66732   int nTrans = 0;  /* Number of databases with an active write-transaction */
66733   int rc = SQLITE_OK;
66734   int needXcommit = 0;
66735 
66736 #ifdef SQLITE_OMIT_VIRTUALTABLE
66737   /* With this option, sqlite3VtabSync() is defined to be simply
66738   ** SQLITE_OK so p is not used.
66739   */
66740   UNUSED_PARAMETER(p);
66741 #endif
66742 
66743   /* Before doing anything else, call the xSync() callback for any
66744   ** virtual module tables written in this transaction. This has to
66745   ** be done before determining whether a master journal file is
66746   ** required, as an xSync() callback may add an attached database
66747   ** to the transaction.
66748   */
66749   rc = sqlite3VtabSync(db, p);
66750 
66751   /* This loop determines (a) if the commit hook should be invoked and
66752   ** (b) how many database files have open write transactions, not
66753   ** including the temp database. (b) is important because if more than
66754   ** one database file has an open write transaction, a master journal
66755   ** file is required for an atomic commit.
66756   */
66757   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
66758     Btree *pBt = db->aDb[i].pBt;
66759     if( sqlite3BtreeIsInTrans(pBt) ){
66760       needXcommit = 1;
66761       if( i!=1 ) nTrans++;
66762       sqlite3BtreeEnter(pBt);
66763       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
66764       sqlite3BtreeLeave(pBt);
66765     }
66766   }
66767   if( rc!=SQLITE_OK ){
66768     return rc;
66769   }
66770 
66771   /* If there are any write-transactions at all, invoke the commit hook */
66772   if( needXcommit && db->xCommitCallback ){
66773     rc = db->xCommitCallback(db->pCommitArg);
66774     if( rc ){
66775       return SQLITE_CONSTRAINT_COMMITHOOK;
66776     }
66777   }
66778 
66779   /* The simple case - no more than one database file (not counting the
66780   ** TEMP database) has a transaction active.   There is no need for the
66781   ** master-journal.
66782   **
66783   ** If the return value of sqlite3BtreeGetFilename() is a zero length
66784   ** string, it means the main database is :memory: or a temp file.  In
66785   ** that case we do not support atomic multi-file commits, so use the
66786   ** simple case then too.
66787   */
66788   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
66789    || nTrans<=1
66790   ){
66791     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
66792       Btree *pBt = db->aDb[i].pBt;
66793       if( pBt ){
66794         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
66795       }
66796     }
66797 
66798     /* Do the commit only if all databases successfully complete phase 1.
66799     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
66800     ** IO error while deleting or truncating a journal file. It is unlikely,
66801     ** but could happen. In this case abandon processing and return the error.
66802     */
66803     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
66804       Btree *pBt = db->aDb[i].pBt;
66805       if( pBt ){
66806         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
66807       }
66808     }
66809     if( rc==SQLITE_OK ){
66810       sqlite3VtabCommit(db);
66811     }
66812   }
66813 
66814   /* The complex case - There is a multi-file write-transaction active.
66815   ** This requires a master journal file to ensure the transaction is
66816   ** committed atomically.
66817   */
66818 #ifndef SQLITE_OMIT_DISKIO
66819   else{
66820     sqlite3_vfs *pVfs = db->pVfs;
66821     int needSync = 0;
66822     char *zMaster = 0;   /* File-name for the master journal */
66823     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
66824     sqlite3_file *pMaster = 0;
66825     i64 offset = 0;
66826     int res;
66827     int retryCount = 0;
66828     int nMainFile;
66829 
66830     /* Select a master journal file name */
66831     nMainFile = sqlite3Strlen30(zMainFile);
66832     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
66833     if( zMaster==0 ) return SQLITE_NOMEM;
66834     do {
66835       u32 iRandom;
66836       if( retryCount ){
66837         if( retryCount>100 ){
66838           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
66839           sqlite3OsDelete(pVfs, zMaster, 0);
66840           break;
66841         }else if( retryCount==1 ){
66842           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
66843         }
66844       }
66845       retryCount++;
66846       sqlite3_randomness(sizeof(iRandom), &iRandom);
66847       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
66848                                (iRandom>>8)&0xffffff, iRandom&0xff);
66849       /* The antipenultimate character of the master journal name must
66850       ** be "9" to avoid name collisions when using 8+3 filenames. */
66851       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
66852       sqlite3FileSuffix3(zMainFile, zMaster);
66853       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
66854     }while( rc==SQLITE_OK && res );
66855     if( rc==SQLITE_OK ){
66856       /* Open the master journal. */
66857       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
66858           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
66859           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
66860       );
66861     }
66862     if( rc!=SQLITE_OK ){
66863       sqlite3DbFree(db, zMaster);
66864       return rc;
66865     }
66866 
66867     /* Write the name of each database file in the transaction into the new
66868     ** master journal file. If an error occurs at this point close
66869     ** and delete the master journal file. All the individual journal files
66870     ** still have 'null' as the master journal pointer, so they will roll
66871     ** back independently if a failure occurs.
66872     */
66873     for(i=0; i<db->nDb; i++){
66874       Btree *pBt = db->aDb[i].pBt;
66875       if( sqlite3BtreeIsInTrans(pBt) ){
66876         char const *zFile = sqlite3BtreeGetJournalname(pBt);
66877         if( zFile==0 ){
66878           continue;  /* Ignore TEMP and :memory: databases */
66879         }
66880         assert( zFile[0]!=0 );
66881         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
66882           needSync = 1;
66883         }
66884         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
66885         offset += sqlite3Strlen30(zFile)+1;
66886         if( rc!=SQLITE_OK ){
66887           sqlite3OsCloseFree(pMaster);
66888           sqlite3OsDelete(pVfs, zMaster, 0);
66889           sqlite3DbFree(db, zMaster);
66890           return rc;
66891         }
66892       }
66893     }
66894 
66895     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
66896     ** flag is set this is not required.
66897     */
66898     if( needSync
66899      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
66900      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
66901     ){
66902       sqlite3OsCloseFree(pMaster);
66903       sqlite3OsDelete(pVfs, zMaster, 0);
66904       sqlite3DbFree(db, zMaster);
66905       return rc;
66906     }
66907 
66908     /* Sync all the db files involved in the transaction. The same call
66909     ** sets the master journal pointer in each individual journal. If
66910     ** an error occurs here, do not delete the master journal file.
66911     **
66912     ** If the error occurs during the first call to
66913     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
66914     ** master journal file will be orphaned. But we cannot delete it,
66915     ** in case the master journal file name was written into the journal
66916     ** file before the failure occurred.
66917     */
66918     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
66919       Btree *pBt = db->aDb[i].pBt;
66920       if( pBt ){
66921         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
66922       }
66923     }
66924     sqlite3OsCloseFree(pMaster);
66925     assert( rc!=SQLITE_BUSY );
66926     if( rc!=SQLITE_OK ){
66927       sqlite3DbFree(db, zMaster);
66928       return rc;
66929     }
66930 
66931     /* Delete the master journal file. This commits the transaction. After
66932     ** doing this the directory is synced again before any individual
66933     ** transaction files are deleted.
66934     */
66935     rc = sqlite3OsDelete(pVfs, zMaster, needSync);
66936     sqlite3DbFree(db, zMaster);
66937     zMaster = 0;
66938     if( rc ){
66939       return rc;
66940     }
66941 
66942     /* All files and directories have already been synced, so the following
66943     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
66944     ** deleting or truncating journals. If something goes wrong while
66945     ** this is happening we don't really care. The integrity of the
66946     ** transaction is already guaranteed, but some stray 'cold' journals
66947     ** may be lying around. Returning an error code won't help matters.
66948     */
66949     disable_simulated_io_errors();
66950     sqlite3BeginBenignMalloc();
66951     for(i=0; i<db->nDb; i++){
66952       Btree *pBt = db->aDb[i].pBt;
66953       if( pBt ){
66954         sqlite3BtreeCommitPhaseTwo(pBt, 1);
66955       }
66956     }
66957     sqlite3EndBenignMalloc();
66958     enable_simulated_io_errors();
66959 
66960     sqlite3VtabCommit(db);
66961   }
66962 #endif
66963 
66964   return rc;
66965 }
66966 
66967 /*
66968 ** This routine checks that the sqlite3.nVdbeActive count variable
66969 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
66970 ** currently active. An assertion fails if the two counts do not match.
66971 ** This is an internal self-check only - it is not an essential processing
66972 ** step.
66973 **
66974 ** This is a no-op if NDEBUG is defined.
66975 */
66976 #ifndef NDEBUG
66977 static void checkActiveVdbeCnt(sqlite3 *db){
66978   Vdbe *p;
66979   int cnt = 0;
66980   int nWrite = 0;
66981   int nRead = 0;
66982   p = db->pVdbe;
66983   while( p ){
66984     if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
66985       cnt++;
66986       if( p->readOnly==0 ) nWrite++;
66987       if( p->bIsReader ) nRead++;
66988     }
66989     p = p->pNext;
66990   }
66991   assert( cnt==db->nVdbeActive );
66992   assert( nWrite==db->nVdbeWrite );
66993   assert( nRead==db->nVdbeRead );
66994 }
66995 #else
66996 #define checkActiveVdbeCnt(x)
66997 #endif
66998 
66999 /*
67000 ** If the Vdbe passed as the first argument opened a statement-transaction,
67001 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
67002 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
67003 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
67004 ** statement transaction is committed.
67005 **
67006 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
67007 ** Otherwise SQLITE_OK.
67008 */
67009 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
67010   sqlite3 *const db = p->db;
67011   int rc = SQLITE_OK;
67012 
67013   /* If p->iStatement is greater than zero, then this Vdbe opened a
67014   ** statement transaction that should be closed here. The only exception
67015   ** is that an IO error may have occurred, causing an emergency rollback.
67016   ** In this case (db->nStatement==0), and there is nothing to do.
67017   */
67018   if( db->nStatement && p->iStatement ){
67019     int i;
67020     const int iSavepoint = p->iStatement-1;
67021 
67022     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
67023     assert( db->nStatement>0 );
67024     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
67025 
67026     for(i=0; i<db->nDb; i++){
67027       int rc2 = SQLITE_OK;
67028       Btree *pBt = db->aDb[i].pBt;
67029       if( pBt ){
67030         if( eOp==SAVEPOINT_ROLLBACK ){
67031           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
67032         }
67033         if( rc2==SQLITE_OK ){
67034           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
67035         }
67036         if( rc==SQLITE_OK ){
67037           rc = rc2;
67038         }
67039       }
67040     }
67041     db->nStatement--;
67042     p->iStatement = 0;
67043 
67044     if( rc==SQLITE_OK ){
67045       if( eOp==SAVEPOINT_ROLLBACK ){
67046         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
67047       }
67048       if( rc==SQLITE_OK ){
67049         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
67050       }
67051     }
67052 
67053     /* If the statement transaction is being rolled back, also restore the
67054     ** database handles deferred constraint counter to the value it had when
67055     ** the statement transaction was opened.  */
67056     if( eOp==SAVEPOINT_ROLLBACK ){
67057       db->nDeferredCons = p->nStmtDefCons;
67058       db->nDeferredImmCons = p->nStmtDefImmCons;
67059     }
67060   }
67061   return rc;
67062 }
67063 
67064 /*
67065 ** This function is called when a transaction opened by the database
67066 ** handle associated with the VM passed as an argument is about to be
67067 ** committed. If there are outstanding deferred foreign key constraint
67068 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
67069 **
67070 ** If there are outstanding FK violations and this function returns
67071 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
67072 ** and write an error message to it. Then return SQLITE_ERROR.
67073 */
67074 #ifndef SQLITE_OMIT_FOREIGN_KEY
67075 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
67076   sqlite3 *db = p->db;
67077   if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
67078    || (!deferred && p->nFkConstraint>0)
67079   ){
67080     p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
67081     p->errorAction = OE_Abort;
67082     sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
67083     return SQLITE_ERROR;
67084   }
67085   return SQLITE_OK;
67086 }
67087 #endif
67088 
67089 /*
67090 ** This routine is called the when a VDBE tries to halt.  If the VDBE
67091 ** has made changes and is in autocommit mode, then commit those
67092 ** changes.  If a rollback is needed, then do the rollback.
67093 **
67094 ** This routine is the only way to move the state of a VM from
67095 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
67096 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
67097 **
67098 ** Return an error code.  If the commit could not complete because of
67099 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
67100 ** means the close did not happen and needs to be repeated.
67101 */
67102 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
67103   int rc;                         /* Used to store transient return codes */
67104   sqlite3 *db = p->db;
67105 
67106   /* This function contains the logic that determines if a statement or
67107   ** transaction will be committed or rolled back as a result of the
67108   ** execution of this virtual machine.
67109   **
67110   ** If any of the following errors occur:
67111   **
67112   **     SQLITE_NOMEM
67113   **     SQLITE_IOERR
67114   **     SQLITE_FULL
67115   **     SQLITE_INTERRUPT
67116   **
67117   ** Then the internal cache might have been left in an inconsistent
67118   ** state.  We need to rollback the statement transaction, if there is
67119   ** one, or the complete transaction if there is no statement transaction.
67120   */
67121 
67122   if( p->db->mallocFailed ){
67123     p->rc = SQLITE_NOMEM;
67124   }
67125   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
67126   closeAllCursors(p);
67127   if( p->magic!=VDBE_MAGIC_RUN ){
67128     return SQLITE_OK;
67129   }
67130   checkActiveVdbeCnt(db);
67131 
67132   /* No commit or rollback needed if the program never started or if the
67133   ** SQL statement does not read or write a database file.  */
67134   if( p->pc>=0 && p->bIsReader ){
67135     int mrc;   /* Primary error code from p->rc */
67136     int eStatementOp = 0;
67137     int isSpecialError;            /* Set to true if a 'special' error */
67138 
67139     /* Lock all btrees used by the statement */
67140     sqlite3VdbeEnter(p);
67141 
67142     /* Check for one of the special errors */
67143     mrc = p->rc & 0xff;
67144     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
67145                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
67146     if( isSpecialError ){
67147       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
67148       ** no rollback is necessary. Otherwise, at least a savepoint
67149       ** transaction must be rolled back to restore the database to a
67150       ** consistent state.
67151       **
67152       ** Even if the statement is read-only, it is important to perform
67153       ** a statement or transaction rollback operation. If the error
67154       ** occurred while writing to the journal, sub-journal or database
67155       ** file as part of an effort to free up cache space (see function
67156       ** pagerStress() in pager.c), the rollback is required to restore
67157       ** the pager to a consistent state.
67158       */
67159       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
67160         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
67161           eStatementOp = SAVEPOINT_ROLLBACK;
67162         }else{
67163           /* We are forced to roll back the active transaction. Before doing
67164           ** so, abort any other statements this handle currently has active.
67165           */
67166           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
67167           sqlite3CloseSavepoints(db);
67168           db->autoCommit = 1;
67169           p->nChange = 0;
67170         }
67171       }
67172     }
67173 
67174     /* Check for immediate foreign key violations. */
67175     if( p->rc==SQLITE_OK ){
67176       sqlite3VdbeCheckFk(p, 0);
67177     }
67178 
67179     /* If the auto-commit flag is set and this is the only active writer
67180     ** VM, then we do either a commit or rollback of the current transaction.
67181     **
67182     ** Note: This block also runs if one of the special errors handled
67183     ** above has occurred.
67184     */
67185     if( !sqlite3VtabInSync(db)
67186      && db->autoCommit
67187      && db->nVdbeWrite==(p->readOnly==0)
67188     ){
67189       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
67190         rc = sqlite3VdbeCheckFk(p, 1);
67191         if( rc!=SQLITE_OK ){
67192           if( NEVER(p->readOnly) ){
67193             sqlite3VdbeLeave(p);
67194             return SQLITE_ERROR;
67195           }
67196           rc = SQLITE_CONSTRAINT_FOREIGNKEY;
67197         }else{
67198           /* The auto-commit flag is true, the vdbe program was successful
67199           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
67200           ** key constraints to hold up the transaction. This means a commit
67201           ** is required. */
67202           rc = vdbeCommit(db, p);
67203         }
67204         if( rc==SQLITE_BUSY && p->readOnly ){
67205           sqlite3VdbeLeave(p);
67206           return SQLITE_BUSY;
67207         }else if( rc!=SQLITE_OK ){
67208           p->rc = rc;
67209           sqlite3RollbackAll(db, SQLITE_OK);
67210           p->nChange = 0;
67211         }else{
67212           db->nDeferredCons = 0;
67213           db->nDeferredImmCons = 0;
67214           db->flags &= ~SQLITE_DeferFKs;
67215           sqlite3CommitInternalChanges(db);
67216         }
67217       }else{
67218         sqlite3RollbackAll(db, SQLITE_OK);
67219         p->nChange = 0;
67220       }
67221       db->nStatement = 0;
67222     }else if( eStatementOp==0 ){
67223       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
67224         eStatementOp = SAVEPOINT_RELEASE;
67225       }else if( p->errorAction==OE_Abort ){
67226         eStatementOp = SAVEPOINT_ROLLBACK;
67227       }else{
67228         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
67229         sqlite3CloseSavepoints(db);
67230         db->autoCommit = 1;
67231         p->nChange = 0;
67232       }
67233     }
67234 
67235     /* If eStatementOp is non-zero, then a statement transaction needs to
67236     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
67237     ** do so. If this operation returns an error, and the current statement
67238     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
67239     ** current statement error code.
67240     */
67241     if( eStatementOp ){
67242       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
67243       if( rc ){
67244         if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
67245           p->rc = rc;
67246           sqlite3DbFree(db, p->zErrMsg);
67247           p->zErrMsg = 0;
67248         }
67249         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
67250         sqlite3CloseSavepoints(db);
67251         db->autoCommit = 1;
67252         p->nChange = 0;
67253       }
67254     }
67255 
67256     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
67257     ** has been rolled back, update the database connection change-counter.
67258     */
67259     if( p->changeCntOn ){
67260       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
67261         sqlite3VdbeSetChanges(db, p->nChange);
67262       }else{
67263         sqlite3VdbeSetChanges(db, 0);
67264       }
67265       p->nChange = 0;
67266     }
67267 
67268     /* Release the locks */
67269     sqlite3VdbeLeave(p);
67270   }
67271 
67272   /* We have successfully halted and closed the VM.  Record this fact. */
67273   if( p->pc>=0 ){
67274     db->nVdbeActive--;
67275     if( !p->readOnly ) db->nVdbeWrite--;
67276     if( p->bIsReader ) db->nVdbeRead--;
67277     assert( db->nVdbeActive>=db->nVdbeRead );
67278     assert( db->nVdbeRead>=db->nVdbeWrite );
67279     assert( db->nVdbeWrite>=0 );
67280   }
67281   p->magic = VDBE_MAGIC_HALT;
67282   checkActiveVdbeCnt(db);
67283   if( p->db->mallocFailed ){
67284     p->rc = SQLITE_NOMEM;
67285   }
67286 
67287   /* If the auto-commit flag is set to true, then any locks that were held
67288   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
67289   ** to invoke any required unlock-notify callbacks.
67290   */
67291   if( db->autoCommit ){
67292     sqlite3ConnectionUnlocked(db);
67293   }
67294 
67295   assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
67296   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
67297 }
67298 
67299 
67300 /*
67301 ** Each VDBE holds the result of the most recent sqlite3_step() call
67302 ** in p->rc.  This routine sets that result back to SQLITE_OK.
67303 */
67304 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
67305   p->rc = SQLITE_OK;
67306 }
67307 
67308 /*
67309 ** Copy the error code and error message belonging to the VDBE passed
67310 ** as the first argument to its database handle (so that they will be
67311 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
67312 **
67313 ** This function does not clear the VDBE error code or message, just
67314 ** copies them to the database handle.
67315 */
67316 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
67317   sqlite3 *db = p->db;
67318   int rc = p->rc;
67319   if( p->zErrMsg ){
67320     u8 mallocFailed = db->mallocFailed;
67321     sqlite3BeginBenignMalloc();
67322     if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
67323     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
67324     sqlite3EndBenignMalloc();
67325     db->mallocFailed = mallocFailed;
67326     db->errCode = rc;
67327   }else{
67328     sqlite3Error(db, rc);
67329   }
67330   return rc;
67331 }
67332 
67333 #ifdef SQLITE_ENABLE_SQLLOG
67334 /*
67335 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
67336 ** invoke it.
67337 */
67338 static void vdbeInvokeSqllog(Vdbe *v){
67339   if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
67340     char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
67341     assert( v->db->init.busy==0 );
67342     if( zExpanded ){
67343       sqlite3GlobalConfig.xSqllog(
67344           sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
67345       );
67346       sqlite3DbFree(v->db, zExpanded);
67347     }
67348   }
67349 }
67350 #else
67351 # define vdbeInvokeSqllog(x)
67352 #endif
67353 
67354 /*
67355 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
67356 ** Write any error messages into *pzErrMsg.  Return the result code.
67357 **
67358 ** After this routine is run, the VDBE should be ready to be executed
67359 ** again.
67360 **
67361 ** To look at it another way, this routine resets the state of the
67362 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
67363 ** VDBE_MAGIC_INIT.
67364 */
67365 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
67366   sqlite3 *db;
67367   db = p->db;
67368 
67369   /* If the VM did not run to completion or if it encountered an
67370   ** error, then it might not have been halted properly.  So halt
67371   ** it now.
67372   */
67373   sqlite3VdbeHalt(p);
67374 
67375   /* If the VDBE has be run even partially, then transfer the error code
67376   ** and error message from the VDBE into the main database structure.  But
67377   ** if the VDBE has just been set to run but has not actually executed any
67378   ** instructions yet, leave the main database error information unchanged.
67379   */
67380   if( p->pc>=0 ){
67381     vdbeInvokeSqllog(p);
67382     sqlite3VdbeTransferError(p);
67383     sqlite3DbFree(db, p->zErrMsg);
67384     p->zErrMsg = 0;
67385     if( p->runOnlyOnce ) p->expired = 1;
67386   }else if( p->rc && p->expired ){
67387     /* The expired flag was set on the VDBE before the first call
67388     ** to sqlite3_step(). For consistency (since sqlite3_step() was
67389     ** called), set the database error in this case as well.
67390     */
67391     sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
67392     sqlite3DbFree(db, p->zErrMsg);
67393     p->zErrMsg = 0;
67394   }
67395 
67396   /* Reclaim all memory used by the VDBE
67397   */
67398   Cleanup(p);
67399 
67400   /* Save profiling information from this VDBE run.
67401   */
67402 #ifdef VDBE_PROFILE
67403   {
67404     FILE *out = fopen("vdbe_profile.out", "a");
67405     if( out ){
67406       int i;
67407       fprintf(out, "---- ");
67408       for(i=0; i<p->nOp; i++){
67409         fprintf(out, "%02x", p->aOp[i].opcode);
67410       }
67411       fprintf(out, "\n");
67412       if( p->zSql ){
67413         char c, pc = 0;
67414         fprintf(out, "-- ");
67415         for(i=0; (c = p->zSql[i])!=0; i++){
67416           if( pc=='\n' ) fprintf(out, "-- ");
67417           putc(c, out);
67418           pc = c;
67419         }
67420         if( pc!='\n' ) fprintf(out, "\n");
67421       }
67422       for(i=0; i<p->nOp; i++){
67423         char zHdr[100];
67424         sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
67425            p->aOp[i].cnt,
67426            p->aOp[i].cycles,
67427            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
67428         );
67429         fprintf(out, "%s", zHdr);
67430         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
67431       }
67432       fclose(out);
67433     }
67434   }
67435 #endif
67436   p->iCurrentTime = 0;
67437   p->magic = VDBE_MAGIC_INIT;
67438   return p->rc & db->errMask;
67439 }
67440 
67441 /*
67442 ** Clean up and delete a VDBE after execution.  Return an integer which is
67443 ** the result code.  Write any error message text into *pzErrMsg.
67444 */
67445 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
67446   int rc = SQLITE_OK;
67447   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
67448     rc = sqlite3VdbeReset(p);
67449     assert( (rc & p->db->errMask)==rc );
67450   }
67451   sqlite3VdbeDelete(p);
67452   return rc;
67453 }
67454 
67455 /*
67456 ** If parameter iOp is less than zero, then invoke the destructor for
67457 ** all auxiliary data pointers currently cached by the VM passed as
67458 ** the first argument.
67459 **
67460 ** Or, if iOp is greater than or equal to zero, then the destructor is
67461 ** only invoked for those auxiliary data pointers created by the user
67462 ** function invoked by the OP_Function opcode at instruction iOp of
67463 ** VM pVdbe, and only then if:
67464 **
67465 **    * the associated function parameter is the 32nd or later (counting
67466 **      from left to right), or
67467 **
67468 **    * the corresponding bit in argument mask is clear (where the first
67469 **      function parameter corresponds to bit 0 etc.).
67470 */
67471 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
67472   AuxData **pp = &pVdbe->pAuxData;
67473   while( *pp ){
67474     AuxData *pAux = *pp;
67475     if( (iOp<0)
67476      || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
67477     ){
67478       testcase( pAux->iArg==31 );
67479       if( pAux->xDelete ){
67480         pAux->xDelete(pAux->pAux);
67481       }
67482       *pp = pAux->pNext;
67483       sqlite3DbFree(pVdbe->db, pAux);
67484     }else{
67485       pp= &pAux->pNext;
67486     }
67487   }
67488 }
67489 
67490 /*
67491 ** Free all memory associated with the Vdbe passed as the second argument,
67492 ** except for object itself, which is preserved.
67493 **
67494 ** The difference between this function and sqlite3VdbeDelete() is that
67495 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
67496 ** the database connection and frees the object itself.
67497 */
67498 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
67499   SubProgram *pSub, *pNext;
67500   int i;
67501   assert( p->db==0 || p->db==db );
67502   releaseMemArray(p->aVar, p->nVar);
67503   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
67504   for(pSub=p->pProgram; pSub; pSub=pNext){
67505     pNext = pSub->pNext;
67506     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
67507     sqlite3DbFree(db, pSub);
67508   }
67509   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
67510   vdbeFreeOpArray(db, p->aOp, p->nOp);
67511   sqlite3DbFree(db, p->aColName);
67512   sqlite3DbFree(db, p->zSql);
67513   sqlite3DbFree(db, p->pFree);
67514 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
67515   for(i=0; i<p->nScan; i++){
67516     sqlite3DbFree(db, p->aScan[i].zName);
67517   }
67518   sqlite3DbFree(db, p->aScan);
67519 #endif
67520 }
67521 
67522 /*
67523 ** Delete an entire VDBE.
67524 */
67525 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
67526   sqlite3 *db;
67527 
67528   if( NEVER(p==0) ) return;
67529   db = p->db;
67530   assert( sqlite3_mutex_held(db->mutex) );
67531   sqlite3VdbeClearObject(db, p);
67532   if( p->pPrev ){
67533     p->pPrev->pNext = p->pNext;
67534   }else{
67535     assert( db->pVdbe==p );
67536     db->pVdbe = p->pNext;
67537   }
67538   if( p->pNext ){
67539     p->pNext->pPrev = p->pPrev;
67540   }
67541   p->magic = VDBE_MAGIC_DEAD;
67542   p->db = 0;
67543   sqlite3DbFree(db, p);
67544 }
67545 
67546 /*
67547 ** The cursor "p" has a pending seek operation that has not yet been
67548 ** carried out.  Seek the cursor now.  If an error occurs, return
67549 ** the appropriate error code.
67550 */
67551 static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
67552   int res, rc;
67553 #ifdef SQLITE_TEST
67554   extern int sqlite3_search_count;
67555 #endif
67556   assert( p->deferredMoveto );
67557   assert( p->isTable );
67558   rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
67559   if( rc ) return rc;
67560   if( res!=0 ) return SQLITE_CORRUPT_BKPT;
67561 #ifdef SQLITE_TEST
67562   sqlite3_search_count++;
67563 #endif
67564   p->deferredMoveto = 0;
67565   p->cacheStatus = CACHE_STALE;
67566   return SQLITE_OK;
67567 }
67568 
67569 /*
67570 ** Something has moved cursor "p" out of place.  Maybe the row it was
67571 ** pointed to was deleted out from under it.  Or maybe the btree was
67572 ** rebalanced.  Whatever the cause, try to restore "p" to the place it
67573 ** is supposed to be pointing.  If the row was deleted out from under the
67574 ** cursor, set the cursor to point to a NULL row.
67575 */
67576 static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
67577   int isDifferentRow, rc;
67578   assert( p->pCursor!=0 );
67579   assert( sqlite3BtreeCursorHasMoved(p->pCursor) );
67580   rc = sqlite3BtreeCursorRestore(p->pCursor, &isDifferentRow);
67581   p->cacheStatus = CACHE_STALE;
67582   if( isDifferentRow ) p->nullRow = 1;
67583   return rc;
67584 }
67585 
67586 /*
67587 ** Check to ensure that the cursor is valid.  Restore the cursor
67588 ** if need be.  Return any I/O error from the restore operation.
67589 */
67590 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
67591   if( sqlite3BtreeCursorHasMoved(p->pCursor) ){
67592     return handleMovedCursor(p);
67593   }
67594   return SQLITE_OK;
67595 }
67596 
67597 /*
67598 ** Make sure the cursor p is ready to read or write the row to which it
67599 ** was last positioned.  Return an error code if an OOM fault or I/O error
67600 ** prevents us from positioning the cursor to its correct position.
67601 **
67602 ** If a MoveTo operation is pending on the given cursor, then do that
67603 ** MoveTo now.  If no move is pending, check to see if the row has been
67604 ** deleted out from under the cursor and if it has, mark the row as
67605 ** a NULL row.
67606 **
67607 ** If the cursor is already pointing to the correct row and that row has
67608 ** not been deleted out from under the cursor, then this routine is a no-op.
67609 */
67610 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
67611   if( p->deferredMoveto ){
67612     return handleDeferredMoveto(p);
67613   }
67614   if( p->pCursor && sqlite3BtreeCursorHasMoved(p->pCursor) ){
67615     return handleMovedCursor(p);
67616   }
67617   return SQLITE_OK;
67618 }
67619 
67620 /*
67621 ** The following functions:
67622 **
67623 ** sqlite3VdbeSerialType()
67624 ** sqlite3VdbeSerialTypeLen()
67625 ** sqlite3VdbeSerialLen()
67626 ** sqlite3VdbeSerialPut()
67627 ** sqlite3VdbeSerialGet()
67628 **
67629 ** encapsulate the code that serializes values for storage in SQLite
67630 ** data and index records. Each serialized value consists of a
67631 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
67632 ** integer, stored as a varint.
67633 **
67634 ** In an SQLite index record, the serial type is stored directly before
67635 ** the blob of data that it corresponds to. In a table record, all serial
67636 ** types are stored at the start of the record, and the blobs of data at
67637 ** the end. Hence these functions allow the caller to handle the
67638 ** serial-type and data blob separately.
67639 **
67640 ** The following table describes the various storage classes for data:
67641 **
67642 **   serial type        bytes of data      type
67643 **   --------------     ---------------    ---------------
67644 **      0                     0            NULL
67645 **      1                     1            signed integer
67646 **      2                     2            signed integer
67647 **      3                     3            signed integer
67648 **      4                     4            signed integer
67649 **      5                     6            signed integer
67650 **      6                     8            signed integer
67651 **      7                     8            IEEE float
67652 **      8                     0            Integer constant 0
67653 **      9                     0            Integer constant 1
67654 **     10,11                               reserved for expansion
67655 **    N>=12 and even       (N-12)/2        BLOB
67656 **    N>=13 and odd        (N-13)/2        text
67657 **
67658 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
67659 ** of SQLite will not understand those serial types.
67660 */
67661 
67662 /*
67663 ** Return the serial-type for the value stored in pMem.
67664 */
67665 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
67666   int flags = pMem->flags;
67667   u32 n;
67668 
67669   if( flags&MEM_Null ){
67670     return 0;
67671   }
67672   if( flags&MEM_Int ){
67673     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
67674 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
67675     i64 i = pMem->u.i;
67676     u64 u;
67677     if( i<0 ){
67678       u = ~i;
67679     }else{
67680       u = i;
67681     }
67682     if( u<=127 ){
67683       return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
67684     }
67685     if( u<=32767 ) return 2;
67686     if( u<=8388607 ) return 3;
67687     if( u<=2147483647 ) return 4;
67688     if( u<=MAX_6BYTE ) return 5;
67689     return 6;
67690   }
67691   if( flags&MEM_Real ){
67692     return 7;
67693   }
67694   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
67695   assert( pMem->n>=0 );
67696   n = (u32)pMem->n;
67697   if( flags & MEM_Zero ){
67698     n += pMem->u.nZero;
67699   }
67700   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
67701 }
67702 
67703 /*
67704 ** Return the length of the data corresponding to the supplied serial-type.
67705 */
67706 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
67707   if( serial_type>=12 ){
67708     return (serial_type-12)/2;
67709   }else{
67710     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
67711     return aSize[serial_type];
67712   }
67713 }
67714 
67715 /*
67716 ** If we are on an architecture with mixed-endian floating
67717 ** points (ex: ARM7) then swap the lower 4 bytes with the
67718 ** upper 4 bytes.  Return the result.
67719 **
67720 ** For most architectures, this is a no-op.
67721 **
67722 ** (later):  It is reported to me that the mixed-endian problem
67723 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
67724 ** that early versions of GCC stored the two words of a 64-bit
67725 ** float in the wrong order.  And that error has been propagated
67726 ** ever since.  The blame is not necessarily with GCC, though.
67727 ** GCC might have just copying the problem from a prior compiler.
67728 ** I am also told that newer versions of GCC that follow a different
67729 ** ABI get the byte order right.
67730 **
67731 ** Developers using SQLite on an ARM7 should compile and run their
67732 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
67733 ** enabled, some asserts below will ensure that the byte order of
67734 ** floating point values is correct.
67735 **
67736 ** (2007-08-30)  Frank van Vugt has studied this problem closely
67737 ** and has send his findings to the SQLite developers.  Frank
67738 ** writes that some Linux kernels offer floating point hardware
67739 ** emulation that uses only 32-bit mantissas instead of a full
67740 ** 48-bits as required by the IEEE standard.  (This is the
67741 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
67742 ** byte swapping becomes very complicated.  To avoid problems,
67743 ** the necessary byte swapping is carried out using a 64-bit integer
67744 ** rather than a 64-bit float.  Frank assures us that the code here
67745 ** works for him.  We, the developers, have no way to independently
67746 ** verify this, but Frank seems to know what he is talking about
67747 ** so we trust him.
67748 */
67749 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
67750 static u64 floatSwap(u64 in){
67751   union {
67752     u64 r;
67753     u32 i[2];
67754   } u;
67755   u32 t;
67756 
67757   u.r = in;
67758   t = u.i[0];
67759   u.i[0] = u.i[1];
67760   u.i[1] = t;
67761   return u.r;
67762 }
67763 # define swapMixedEndianFloat(X)  X = floatSwap(X)
67764 #else
67765 # define swapMixedEndianFloat(X)
67766 #endif
67767 
67768 /*
67769 ** Write the serialized data blob for the value stored in pMem into
67770 ** buf. It is assumed that the caller has allocated sufficient space.
67771 ** Return the number of bytes written.
67772 **
67773 ** nBuf is the amount of space left in buf[].  The caller is responsible
67774 ** for allocating enough space to buf[] to hold the entire field, exclusive
67775 ** of the pMem->u.nZero bytes for a MEM_Zero value.
67776 **
67777 ** Return the number of bytes actually written into buf[].  The number
67778 ** of bytes in the zero-filled tail is included in the return value only
67779 ** if those bytes were zeroed in buf[].
67780 */
67781 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
67782   u32 len;
67783 
67784   /* Integer and Real */
67785   if( serial_type<=7 && serial_type>0 ){
67786     u64 v;
67787     u32 i;
67788     if( serial_type==7 ){
67789       assert( sizeof(v)==sizeof(pMem->u.r) );
67790       memcpy(&v, &pMem->u.r, sizeof(v));
67791       swapMixedEndianFloat(v);
67792     }else{
67793       v = pMem->u.i;
67794     }
67795     len = i = sqlite3VdbeSerialTypeLen(serial_type);
67796     assert( i>0 );
67797     do{
67798       buf[--i] = (u8)(v&0xFF);
67799       v >>= 8;
67800     }while( i );
67801     return len;
67802   }
67803 
67804   /* String or blob */
67805   if( serial_type>=12 ){
67806     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
67807              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
67808     len = pMem->n;
67809     memcpy(buf, pMem->z, len);
67810     return len;
67811   }
67812 
67813   /* NULL or constants 0 or 1 */
67814   return 0;
67815 }
67816 
67817 /* Input "x" is a sequence of unsigned characters that represent a
67818 ** big-endian integer.  Return the equivalent native integer
67819 */
67820 #define ONE_BYTE_INT(x)    ((i8)(x)[0])
67821 #define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
67822 #define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
67823 #define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
67824 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
67825 
67826 /*
67827 ** Deserialize the data blob pointed to by buf as serial type serial_type
67828 ** and store the result in pMem.  Return the number of bytes read.
67829 **
67830 ** This function is implemented as two separate routines for performance.
67831 ** The few cases that require local variables are broken out into a separate
67832 ** routine so that in most cases the overhead of moving the stack pointer
67833 ** is avoided.
67834 */
67835 static u32 SQLITE_NOINLINE serialGet(
67836   const unsigned char *buf,     /* Buffer to deserialize from */
67837   u32 serial_type,              /* Serial type to deserialize */
67838   Mem *pMem                     /* Memory cell to write value into */
67839 ){
67840   u64 x = FOUR_BYTE_UINT(buf);
67841   u32 y = FOUR_BYTE_UINT(buf+4);
67842   x = (x<<32) + y;
67843   if( serial_type==6 ){
67844     /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
67845     ** twos-complement integer. */
67846     pMem->u.i = *(i64*)&x;
67847     pMem->flags = MEM_Int;
67848     testcase( pMem->u.i<0 );
67849   }else{
67850     /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
67851     ** floating point number. */
67852 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
67853     /* Verify that integers and floating point values use the same
67854     ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
67855     ** defined that 64-bit floating point values really are mixed
67856     ** endian.
67857     */
67858     static const u64 t1 = ((u64)0x3ff00000)<<32;
67859     static const double r1 = 1.0;
67860     u64 t2 = t1;
67861     swapMixedEndianFloat(t2);
67862     assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
67863 #endif
67864     assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
67865     swapMixedEndianFloat(x);
67866     memcpy(&pMem->u.r, &x, sizeof(x));
67867     pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
67868   }
67869   return 8;
67870 }
67871 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
67872   const unsigned char *buf,     /* Buffer to deserialize from */
67873   u32 serial_type,              /* Serial type to deserialize */
67874   Mem *pMem                     /* Memory cell to write value into */
67875 ){
67876   switch( serial_type ){
67877     case 10:   /* Reserved for future use */
67878     case 11:   /* Reserved for future use */
67879     case 0: {  /* Null */
67880       /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
67881       pMem->flags = MEM_Null;
67882       break;
67883     }
67884     case 1: {
67885       /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
67886       ** integer. */
67887       pMem->u.i = ONE_BYTE_INT(buf);
67888       pMem->flags = MEM_Int;
67889       testcase( pMem->u.i<0 );
67890       return 1;
67891     }
67892     case 2: { /* 2-byte signed integer */
67893       /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
67894       ** twos-complement integer. */
67895       pMem->u.i = TWO_BYTE_INT(buf);
67896       pMem->flags = MEM_Int;
67897       testcase( pMem->u.i<0 );
67898       return 2;
67899     }
67900     case 3: { /* 3-byte signed integer */
67901       /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
67902       ** twos-complement integer. */
67903       pMem->u.i = THREE_BYTE_INT(buf);
67904       pMem->flags = MEM_Int;
67905       testcase( pMem->u.i<0 );
67906       return 3;
67907     }
67908     case 4: { /* 4-byte signed integer */
67909       /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
67910       ** twos-complement integer. */
67911       pMem->u.i = FOUR_BYTE_INT(buf);
67912       pMem->flags = MEM_Int;
67913       testcase( pMem->u.i<0 );
67914       return 4;
67915     }
67916     case 5: { /* 6-byte signed integer */
67917       /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
67918       ** twos-complement integer. */
67919       pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
67920       pMem->flags = MEM_Int;
67921       testcase( pMem->u.i<0 );
67922       return 6;
67923     }
67924     case 6:   /* 8-byte signed integer */
67925     case 7: { /* IEEE floating point */
67926       /* These use local variables, so do them in a separate routine
67927       ** to avoid having to move the frame pointer in the common case */
67928       return serialGet(buf,serial_type,pMem);
67929     }
67930     case 8:    /* Integer 0 */
67931     case 9: {  /* Integer 1 */
67932       /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
67933       /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
67934       pMem->u.i = serial_type-8;
67935       pMem->flags = MEM_Int;
67936       return 0;
67937     }
67938     default: {
67939       /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
67940       ** length.
67941       ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
67942       ** (N-13)/2 bytes in length. */
67943       static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
67944       pMem->z = (char *)buf;
67945       pMem->n = (serial_type-12)/2;
67946       pMem->flags = aFlag[serial_type&1];
67947       return pMem->n;
67948     }
67949   }
67950   return 0;
67951 }
67952 /*
67953 ** This routine is used to allocate sufficient space for an UnpackedRecord
67954 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
67955 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
67956 **
67957 ** The space is either allocated using sqlite3DbMallocRaw() or from within
67958 ** the unaligned buffer passed via the second and third arguments (presumably
67959 ** stack space). If the former, then *ppFree is set to a pointer that should
67960 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
67961 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
67962 ** before returning.
67963 **
67964 ** If an OOM error occurs, NULL is returned.
67965 */
67966 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
67967   KeyInfo *pKeyInfo,              /* Description of the record */
67968   char *pSpace,                   /* Unaligned space available */
67969   int szSpace,                    /* Size of pSpace[] in bytes */
67970   char **ppFree                   /* OUT: Caller should free this pointer */
67971 ){
67972   UnpackedRecord *p;              /* Unpacked record to return */
67973   int nOff;                       /* Increment pSpace by nOff to align it */
67974   int nByte;                      /* Number of bytes required for *p */
67975 
67976   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
67977   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
67978   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
67979   */
67980   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
67981   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
67982   if( nByte>szSpace+nOff ){
67983     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
67984     *ppFree = (char *)p;
67985     if( !p ) return 0;
67986   }else{
67987     p = (UnpackedRecord*)&pSpace[nOff];
67988     *ppFree = 0;
67989   }
67990 
67991   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
67992   assert( pKeyInfo->aSortOrder!=0 );
67993   p->pKeyInfo = pKeyInfo;
67994   p->nField = pKeyInfo->nField + 1;
67995   return p;
67996 }
67997 
67998 /*
67999 ** Given the nKey-byte encoding of a record in pKey[], populate the
68000 ** UnpackedRecord structure indicated by the fourth argument with the
68001 ** contents of the decoded record.
68002 */
68003 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
68004   KeyInfo *pKeyInfo,     /* Information about the record format */
68005   int nKey,              /* Size of the binary record */
68006   const void *pKey,      /* The binary record */
68007   UnpackedRecord *p      /* Populate this structure before returning. */
68008 ){
68009   const unsigned char *aKey = (const unsigned char *)pKey;
68010   int d;
68011   u32 idx;                        /* Offset in aKey[] to read from */
68012   u16 u;                          /* Unsigned loop counter */
68013   u32 szHdr;
68014   Mem *pMem = p->aMem;
68015 
68016   p->default_rc = 0;
68017   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
68018   idx = getVarint32(aKey, szHdr);
68019   d = szHdr;
68020   u = 0;
68021   while( idx<szHdr && d<=nKey ){
68022     u32 serial_type;
68023 
68024     idx += getVarint32(&aKey[idx], serial_type);
68025     pMem->enc = pKeyInfo->enc;
68026     pMem->db = pKeyInfo->db;
68027     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
68028     pMem->szMalloc = 0;
68029     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
68030     pMem++;
68031     if( (++u)>=p->nField ) break;
68032   }
68033   assert( u<=pKeyInfo->nField + 1 );
68034   p->nField = u;
68035 }
68036 
68037 #if SQLITE_DEBUG
68038 /*
68039 ** This function compares two index or table record keys in the same way
68040 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
68041 ** this function deserializes and compares values using the
68042 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
68043 ** in assert() statements to ensure that the optimized code in
68044 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
68045 **
68046 ** Return true if the result of comparison is equivalent to desiredResult.
68047 ** Return false if there is a disagreement.
68048 */
68049 static int vdbeRecordCompareDebug(
68050   int nKey1, const void *pKey1, /* Left key */
68051   const UnpackedRecord *pPKey2, /* Right key */
68052   int desiredResult             /* Correct answer */
68053 ){
68054   u32 d1;            /* Offset into aKey[] of next data element */
68055   u32 idx1;          /* Offset into aKey[] of next header element */
68056   u32 szHdr1;        /* Number of bytes in header */
68057   int i = 0;
68058   int rc = 0;
68059   const unsigned char *aKey1 = (const unsigned char *)pKey1;
68060   KeyInfo *pKeyInfo;
68061   Mem mem1;
68062 
68063   pKeyInfo = pPKey2->pKeyInfo;
68064   if( pKeyInfo->db==0 ) return 1;
68065   mem1.enc = pKeyInfo->enc;
68066   mem1.db = pKeyInfo->db;
68067   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
68068   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
68069 
68070   /* Compilers may complain that mem1.u.i is potentially uninitialized.
68071   ** We could initialize it, as shown here, to silence those complaints.
68072   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
68073   ** the unnecessary initialization has a measurable negative performance
68074   ** impact, since this routine is a very high runner.  And so, we choose
68075   ** to ignore the compiler warnings and leave this variable uninitialized.
68076   */
68077   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
68078 
68079   idx1 = getVarint32(aKey1, szHdr1);
68080   d1 = szHdr1;
68081   assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
68082   assert( pKeyInfo->aSortOrder!=0 );
68083   assert( pKeyInfo->nField>0 );
68084   assert( idx1<=szHdr1 || CORRUPT_DB );
68085   do{
68086     u32 serial_type1;
68087 
68088     /* Read the serial types for the next element in each key. */
68089     idx1 += getVarint32( aKey1+idx1, serial_type1 );
68090 
68091     /* Verify that there is enough key space remaining to avoid
68092     ** a buffer overread.  The "d1+serial_type1+2" subexpression will
68093     ** always be greater than or equal to the amount of required key space.
68094     ** Use that approximation to avoid the more expensive call to
68095     ** sqlite3VdbeSerialTypeLen() in the common case.
68096     */
68097     if( d1+serial_type1+2>(u32)nKey1
68098      && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
68099     ){
68100       break;
68101     }
68102 
68103     /* Extract the values to be compared.
68104     */
68105     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
68106 
68107     /* Do the comparison
68108     */
68109     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
68110     if( rc!=0 ){
68111       assert( mem1.szMalloc==0 );  /* See comment below */
68112       if( pKeyInfo->aSortOrder[i] ){
68113         rc = -rc;  /* Invert the result for DESC sort order. */
68114       }
68115       goto debugCompareEnd;
68116     }
68117     i++;
68118   }while( idx1<szHdr1 && i<pPKey2->nField );
68119 
68120   /* No memory allocation is ever used on mem1.  Prove this using
68121   ** the following assert().  If the assert() fails, it indicates a
68122   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
68123   */
68124   assert( mem1.szMalloc==0 );
68125 
68126   /* rc==0 here means that one of the keys ran out of fields and
68127   ** all the fields up to that point were equal. Return the default_rc
68128   ** value.  */
68129   rc = pPKey2->default_rc;
68130 
68131 debugCompareEnd:
68132   if( desiredResult==0 && rc==0 ) return 1;
68133   if( desiredResult<0 && rc<0 ) return 1;
68134   if( desiredResult>0 && rc>0 ) return 1;
68135   if( CORRUPT_DB ) return 1;
68136   if( pKeyInfo->db->mallocFailed ) return 1;
68137   return 0;
68138 }
68139 #endif
68140 
68141 #if SQLITE_DEBUG
68142 /*
68143 ** Count the number of fields (a.k.a. columns) in the record given by
68144 ** pKey,nKey.  The verify that this count is less than or equal to the
68145 ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
68146 **
68147 ** If this constraint is not satisfied, it means that the high-speed
68148 ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
68149 ** not work correctly.  If this assert() ever fires, it probably means
68150 ** that the KeyInfo.nField or KeyInfo.nXField values were computed
68151 ** incorrectly.
68152 */
68153 static void vdbeAssertFieldCountWithinLimits(
68154   int nKey, const void *pKey,   /* The record to verify */
68155   const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
68156 ){
68157   int nField = 0;
68158   u32 szHdr;
68159   u32 idx;
68160   u32 notUsed;
68161   const unsigned char *aKey = (const unsigned char*)pKey;
68162 
68163   if( CORRUPT_DB ) return;
68164   idx = getVarint32(aKey, szHdr);
68165   assert( nKey>=0 );
68166   assert( szHdr<=(u32)nKey );
68167   while( idx<szHdr ){
68168     idx += getVarint32(aKey+idx, notUsed);
68169     nField++;
68170   }
68171   assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
68172 }
68173 #else
68174 # define vdbeAssertFieldCountWithinLimits(A,B,C)
68175 #endif
68176 
68177 /*
68178 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
68179 ** using the collation sequence pColl. As usual, return a negative , zero
68180 ** or positive value if *pMem1 is less than, equal to or greater than
68181 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
68182 */
68183 static int vdbeCompareMemString(
68184   const Mem *pMem1,
68185   const Mem *pMem2,
68186   const CollSeq *pColl,
68187   u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
68188 ){
68189   if( pMem1->enc==pColl->enc ){
68190     /* The strings are already in the correct encoding.  Call the
68191      ** comparison function directly */
68192     return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
68193   }else{
68194     int rc;
68195     const void *v1, *v2;
68196     int n1, n2;
68197     Mem c1;
68198     Mem c2;
68199     sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
68200     sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
68201     sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
68202     sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
68203     v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
68204     n1 = v1==0 ? 0 : c1.n;
68205     v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
68206     n2 = v2==0 ? 0 : c2.n;
68207     rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
68208     sqlite3VdbeMemRelease(&c1);
68209     sqlite3VdbeMemRelease(&c2);
68210     if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
68211     return rc;
68212   }
68213 }
68214 
68215 /*
68216 ** Compare two blobs.  Return negative, zero, or positive if the first
68217 ** is less than, equal to, or greater than the second, respectively.
68218 ** If one blob is a prefix of the other, then the shorter is the lessor.
68219 */
68220 static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
68221   int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
68222   if( c ) return c;
68223   return pB1->n - pB2->n;
68224 }
68225 
68226 
68227 /*
68228 ** Compare the values contained by the two memory cells, returning
68229 ** negative, zero or positive if pMem1 is less than, equal to, or greater
68230 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
68231 ** and reals) sorted numerically, followed by text ordered by the collating
68232 ** sequence pColl and finally blob's ordered by memcmp().
68233 **
68234 ** Two NULL values are considered equal by this function.
68235 */
68236 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
68237   int f1, f2;
68238   int combined_flags;
68239 
68240   f1 = pMem1->flags;
68241   f2 = pMem2->flags;
68242   combined_flags = f1|f2;
68243   assert( (combined_flags & MEM_RowSet)==0 );
68244 
68245   /* If one value is NULL, it is less than the other. If both values
68246   ** are NULL, return 0.
68247   */
68248   if( combined_flags&MEM_Null ){
68249     return (f2&MEM_Null) - (f1&MEM_Null);
68250   }
68251 
68252   /* If one value is a number and the other is not, the number is less.
68253   ** If both are numbers, compare as reals if one is a real, or as integers
68254   ** if both values are integers.
68255   */
68256   if( combined_flags&(MEM_Int|MEM_Real) ){
68257     double r1, r2;
68258     if( (f1 & f2 & MEM_Int)!=0 ){
68259       if( pMem1->u.i < pMem2->u.i ) return -1;
68260       if( pMem1->u.i > pMem2->u.i ) return 1;
68261       return 0;
68262     }
68263     if( (f1&MEM_Real)!=0 ){
68264       r1 = pMem1->u.r;
68265     }else if( (f1&MEM_Int)!=0 ){
68266       r1 = (double)pMem1->u.i;
68267     }else{
68268       return 1;
68269     }
68270     if( (f2&MEM_Real)!=0 ){
68271       r2 = pMem2->u.r;
68272     }else if( (f2&MEM_Int)!=0 ){
68273       r2 = (double)pMem2->u.i;
68274     }else{
68275       return -1;
68276     }
68277     if( r1<r2 ) return -1;
68278     if( r1>r2 ) return 1;
68279     return 0;
68280   }
68281 
68282   /* If one value is a string and the other is a blob, the string is less.
68283   ** If both are strings, compare using the collating functions.
68284   */
68285   if( combined_flags&MEM_Str ){
68286     if( (f1 & MEM_Str)==0 ){
68287       return 1;
68288     }
68289     if( (f2 & MEM_Str)==0 ){
68290       return -1;
68291     }
68292 
68293     assert( pMem1->enc==pMem2->enc );
68294     assert( pMem1->enc==SQLITE_UTF8 ||
68295             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
68296 
68297     /* The collation sequence must be defined at this point, even if
68298     ** the user deletes the collation sequence after the vdbe program is
68299     ** compiled (this was not always the case).
68300     */
68301     assert( !pColl || pColl->xCmp );
68302 
68303     if( pColl ){
68304       return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
68305     }
68306     /* If a NULL pointer was passed as the collate function, fall through
68307     ** to the blob case and use memcmp().  */
68308   }
68309 
68310   /* Both values must be blobs.  Compare using memcmp().  */
68311   return sqlite3BlobCompare(pMem1, pMem2);
68312 }
68313 
68314 
68315 /*
68316 ** The first argument passed to this function is a serial-type that
68317 ** corresponds to an integer - all values between 1 and 9 inclusive
68318 ** except 7. The second points to a buffer containing an integer value
68319 ** serialized according to serial_type. This function deserializes
68320 ** and returns the value.
68321 */
68322 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
68323   u32 y;
68324   assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
68325   switch( serial_type ){
68326     case 0:
68327     case 1:
68328       testcase( aKey[0]&0x80 );
68329       return ONE_BYTE_INT(aKey);
68330     case 2:
68331       testcase( aKey[0]&0x80 );
68332       return TWO_BYTE_INT(aKey);
68333     case 3:
68334       testcase( aKey[0]&0x80 );
68335       return THREE_BYTE_INT(aKey);
68336     case 4: {
68337       testcase( aKey[0]&0x80 );
68338       y = FOUR_BYTE_UINT(aKey);
68339       return (i64)*(int*)&y;
68340     }
68341     case 5: {
68342       testcase( aKey[0]&0x80 );
68343       return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
68344     }
68345     case 6: {
68346       u64 x = FOUR_BYTE_UINT(aKey);
68347       testcase( aKey[0]&0x80 );
68348       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
68349       return (i64)*(i64*)&x;
68350     }
68351   }
68352 
68353   return (serial_type - 8);
68354 }
68355 
68356 /*
68357 ** This function compares the two table rows or index records
68358 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
68359 ** or positive integer if key1 is less than, equal to or
68360 ** greater than key2.  The {nKey1, pKey1} key must be a blob
68361 ** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
68362 ** key must be a parsed key such as obtained from
68363 ** sqlite3VdbeParseRecord.
68364 **
68365 ** If argument bSkip is non-zero, it is assumed that the caller has already
68366 ** determined that the first fields of the keys are equal.
68367 **
68368 ** Key1 and Key2 do not have to contain the same number of fields. If all
68369 ** fields that appear in both keys are equal, then pPKey2->default_rc is
68370 ** returned.
68371 **
68372 ** If database corruption is discovered, set pPKey2->errCode to
68373 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
68374 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
68375 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
68376 */
68377 SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
68378   int nKey1, const void *pKey1,   /* Left key */
68379   UnpackedRecord *pPKey2,         /* Right key */
68380   int bSkip                       /* If true, skip the first field */
68381 ){
68382   u32 d1;                         /* Offset into aKey[] of next data element */
68383   int i;                          /* Index of next field to compare */
68384   u32 szHdr1;                     /* Size of record header in bytes */
68385   u32 idx1;                       /* Offset of first type in header */
68386   int rc = 0;                     /* Return value */
68387   Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
68388   KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
68389   const unsigned char *aKey1 = (const unsigned char *)pKey1;
68390   Mem mem1;
68391 
68392   /* If bSkip is true, then the caller has already determined that the first
68393   ** two elements in the keys are equal. Fix the various stack variables so
68394   ** that this routine begins comparing at the second field. */
68395   if( bSkip ){
68396     u32 s1;
68397     idx1 = 1 + getVarint32(&aKey1[1], s1);
68398     szHdr1 = aKey1[0];
68399     d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
68400     i = 1;
68401     pRhs++;
68402   }else{
68403     idx1 = getVarint32(aKey1, szHdr1);
68404     d1 = szHdr1;
68405     if( d1>(unsigned)nKey1 ){
68406       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
68407       return 0;  /* Corruption */
68408     }
68409     i = 0;
68410   }
68411 
68412   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
68413   assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
68414        || CORRUPT_DB );
68415   assert( pPKey2->pKeyInfo->aSortOrder!=0 );
68416   assert( pPKey2->pKeyInfo->nField>0 );
68417   assert( idx1<=szHdr1 || CORRUPT_DB );
68418   do{
68419     u32 serial_type;
68420 
68421     /* RHS is an integer */
68422     if( pRhs->flags & MEM_Int ){
68423       serial_type = aKey1[idx1];
68424       testcase( serial_type==12 );
68425       if( serial_type>=12 ){
68426         rc = +1;
68427       }else if( serial_type==0 ){
68428         rc = -1;
68429       }else if( serial_type==7 ){
68430         double rhs = (double)pRhs->u.i;
68431         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
68432         if( mem1.u.r<rhs ){
68433           rc = -1;
68434         }else if( mem1.u.r>rhs ){
68435           rc = +1;
68436         }
68437       }else{
68438         i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
68439         i64 rhs = pRhs->u.i;
68440         if( lhs<rhs ){
68441           rc = -1;
68442         }else if( lhs>rhs ){
68443           rc = +1;
68444         }
68445       }
68446     }
68447 
68448     /* RHS is real */
68449     else if( pRhs->flags & MEM_Real ){
68450       serial_type = aKey1[idx1];
68451       if( serial_type>=12 ){
68452         rc = +1;
68453       }else if( serial_type==0 ){
68454         rc = -1;
68455       }else{
68456         double rhs = pRhs->u.r;
68457         double lhs;
68458         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
68459         if( serial_type==7 ){
68460           lhs = mem1.u.r;
68461         }else{
68462           lhs = (double)mem1.u.i;
68463         }
68464         if( lhs<rhs ){
68465           rc = -1;
68466         }else if( lhs>rhs ){
68467           rc = +1;
68468         }
68469       }
68470     }
68471 
68472     /* RHS is a string */
68473     else if( pRhs->flags & MEM_Str ){
68474       getVarint32(&aKey1[idx1], serial_type);
68475       testcase( serial_type==12 );
68476       if( serial_type<12 ){
68477         rc = -1;
68478       }else if( !(serial_type & 0x01) ){
68479         rc = +1;
68480       }else{
68481         mem1.n = (serial_type - 12) / 2;
68482         testcase( (d1+mem1.n)==(unsigned)nKey1 );
68483         testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
68484         if( (d1+mem1.n) > (unsigned)nKey1 ){
68485           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
68486           return 0;                /* Corruption */
68487         }else if( pKeyInfo->aColl[i] ){
68488           mem1.enc = pKeyInfo->enc;
68489           mem1.db = pKeyInfo->db;
68490           mem1.flags = MEM_Str;
68491           mem1.z = (char*)&aKey1[d1];
68492           rc = vdbeCompareMemString(
68493               &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
68494           );
68495         }else{
68496           int nCmp = MIN(mem1.n, pRhs->n);
68497           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
68498           if( rc==0 ) rc = mem1.n - pRhs->n;
68499         }
68500       }
68501     }
68502 
68503     /* RHS is a blob */
68504     else if( pRhs->flags & MEM_Blob ){
68505       getVarint32(&aKey1[idx1], serial_type);
68506       testcase( serial_type==12 );
68507       if( serial_type<12 || (serial_type & 0x01) ){
68508         rc = -1;
68509       }else{
68510         int nStr = (serial_type - 12) / 2;
68511         testcase( (d1+nStr)==(unsigned)nKey1 );
68512         testcase( (d1+nStr+1)==(unsigned)nKey1 );
68513         if( (d1+nStr) > (unsigned)nKey1 ){
68514           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
68515           return 0;                /* Corruption */
68516         }else{
68517           int nCmp = MIN(nStr, pRhs->n);
68518           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
68519           if( rc==0 ) rc = nStr - pRhs->n;
68520         }
68521       }
68522     }
68523 
68524     /* RHS is null */
68525     else{
68526       serial_type = aKey1[idx1];
68527       rc = (serial_type!=0);
68528     }
68529 
68530     if( rc!=0 ){
68531       if( pKeyInfo->aSortOrder[i] ){
68532         rc = -rc;
68533       }
68534       assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
68535       assert( mem1.szMalloc==0 );  /* See comment below */
68536       return rc;
68537     }
68538 
68539     i++;
68540     pRhs++;
68541     d1 += sqlite3VdbeSerialTypeLen(serial_type);
68542     idx1 += sqlite3VarintLen(serial_type);
68543   }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
68544 
68545   /* No memory allocation is ever used on mem1.  Prove this using
68546   ** the following assert().  If the assert() fails, it indicates a
68547   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
68548   assert( mem1.szMalloc==0 );
68549 
68550   /* rc==0 here means that one or both of the keys ran out of fields and
68551   ** all the fields up to that point were equal. Return the default_rc
68552   ** value.  */
68553   assert( CORRUPT_DB
68554        || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
68555        || pKeyInfo->db->mallocFailed
68556   );
68557   return pPKey2->default_rc;
68558 }
68559 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
68560   int nKey1, const void *pKey1,   /* Left key */
68561   UnpackedRecord *pPKey2          /* Right key */
68562 ){
68563   return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
68564 }
68565 
68566 
68567 /*
68568 ** This function is an optimized version of sqlite3VdbeRecordCompare()
68569 ** that (a) the first field of pPKey2 is an integer, and (b) the
68570 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
68571 ** byte (i.e. is less than 128).
68572 **
68573 ** To avoid concerns about buffer overreads, this routine is only used
68574 ** on schemas where the maximum valid header size is 63 bytes or less.
68575 */
68576 static int vdbeRecordCompareInt(
68577   int nKey1, const void *pKey1, /* Left key */
68578   UnpackedRecord *pPKey2        /* Right key */
68579 ){
68580   const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
68581   int serial_type = ((const u8*)pKey1)[1];
68582   int res;
68583   u32 y;
68584   u64 x;
68585   i64 v = pPKey2->aMem[0].u.i;
68586   i64 lhs;
68587 
68588   vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
68589   assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
68590   switch( serial_type ){
68591     case 1: { /* 1-byte signed integer */
68592       lhs = ONE_BYTE_INT(aKey);
68593       testcase( lhs<0 );
68594       break;
68595     }
68596     case 2: { /* 2-byte signed integer */
68597       lhs = TWO_BYTE_INT(aKey);
68598       testcase( lhs<0 );
68599       break;
68600     }
68601     case 3: { /* 3-byte signed integer */
68602       lhs = THREE_BYTE_INT(aKey);
68603       testcase( lhs<0 );
68604       break;
68605     }
68606     case 4: { /* 4-byte signed integer */
68607       y = FOUR_BYTE_UINT(aKey);
68608       lhs = (i64)*(int*)&y;
68609       testcase( lhs<0 );
68610       break;
68611     }
68612     case 5: { /* 6-byte signed integer */
68613       lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
68614       testcase( lhs<0 );
68615       break;
68616     }
68617     case 6: { /* 8-byte signed integer */
68618       x = FOUR_BYTE_UINT(aKey);
68619       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
68620       lhs = *(i64*)&x;
68621       testcase( lhs<0 );
68622       break;
68623     }
68624     case 8:
68625       lhs = 0;
68626       break;
68627     case 9:
68628       lhs = 1;
68629       break;
68630 
68631     /* This case could be removed without changing the results of running
68632     ** this code. Including it causes gcc to generate a faster switch
68633     ** statement (since the range of switch targets now starts at zero and
68634     ** is contiguous) but does not cause any duplicate code to be generated
68635     ** (as gcc is clever enough to combine the two like cases). Other
68636     ** compilers might be similar.  */
68637     case 0: case 7:
68638       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
68639 
68640     default:
68641       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
68642   }
68643 
68644   if( v>lhs ){
68645     res = pPKey2->r1;
68646   }else if( v<lhs ){
68647     res = pPKey2->r2;
68648   }else if( pPKey2->nField>1 ){
68649     /* The first fields of the two keys are equal. Compare the trailing
68650     ** fields.  */
68651     res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
68652   }else{
68653     /* The first fields of the two keys are equal and there are no trailing
68654     ** fields. Return pPKey2->default_rc in this case. */
68655     res = pPKey2->default_rc;
68656   }
68657 
68658   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
68659   return res;
68660 }
68661 
68662 /*
68663 ** This function is an optimized version of sqlite3VdbeRecordCompare()
68664 ** that (a) the first field of pPKey2 is a string, that (b) the first field
68665 ** uses the collation sequence BINARY and (c) that the size-of-header varint
68666 ** at the start of (pKey1/nKey1) fits in a single byte.
68667 */
68668 static int vdbeRecordCompareString(
68669   int nKey1, const void *pKey1, /* Left key */
68670   UnpackedRecord *pPKey2        /* Right key */
68671 ){
68672   const u8 *aKey1 = (const u8*)pKey1;
68673   int serial_type;
68674   int res;
68675 
68676   vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
68677   getVarint32(&aKey1[1], serial_type);
68678   if( serial_type<12 ){
68679     res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
68680   }else if( !(serial_type & 0x01) ){
68681     res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
68682   }else{
68683     int nCmp;
68684     int nStr;
68685     int szHdr = aKey1[0];
68686 
68687     nStr = (serial_type-12) / 2;
68688     if( (szHdr + nStr) > nKey1 ){
68689       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
68690       return 0;    /* Corruption */
68691     }
68692     nCmp = MIN( pPKey2->aMem[0].n, nStr );
68693     res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
68694 
68695     if( res==0 ){
68696       res = nStr - pPKey2->aMem[0].n;
68697       if( res==0 ){
68698         if( pPKey2->nField>1 ){
68699           res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
68700         }else{
68701           res = pPKey2->default_rc;
68702         }
68703       }else if( res>0 ){
68704         res = pPKey2->r2;
68705       }else{
68706         res = pPKey2->r1;
68707       }
68708     }else if( res>0 ){
68709       res = pPKey2->r2;
68710     }else{
68711       res = pPKey2->r1;
68712     }
68713   }
68714 
68715   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
68716        || CORRUPT_DB
68717        || pPKey2->pKeyInfo->db->mallocFailed
68718   );
68719   return res;
68720 }
68721 
68722 /*
68723 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
68724 ** suitable for comparing serialized records to the unpacked record passed
68725 ** as the only argument.
68726 */
68727 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
68728   /* varintRecordCompareInt() and varintRecordCompareString() both assume
68729   ** that the size-of-header varint that occurs at the start of each record
68730   ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
68731   ** also assumes that it is safe to overread a buffer by at least the
68732   ** maximum possible legal header size plus 8 bytes. Because there is
68733   ** guaranteed to be at least 74 (but not 136) bytes of padding following each
68734   ** buffer passed to varintRecordCompareInt() this makes it convenient to
68735   ** limit the size of the header to 64 bytes in cases where the first field
68736   ** is an integer.
68737   **
68738   ** The easiest way to enforce this limit is to consider only records with
68739   ** 13 fields or less. If the first field is an integer, the maximum legal
68740   ** header size is (12*5 + 1 + 1) bytes.  */
68741   if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
68742     int flags = p->aMem[0].flags;
68743     if( p->pKeyInfo->aSortOrder[0] ){
68744       p->r1 = 1;
68745       p->r2 = -1;
68746     }else{
68747       p->r1 = -1;
68748       p->r2 = 1;
68749     }
68750     if( (flags & MEM_Int) ){
68751       return vdbeRecordCompareInt;
68752     }
68753     testcase( flags & MEM_Real );
68754     testcase( flags & MEM_Null );
68755     testcase( flags & MEM_Blob );
68756     if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
68757       assert( flags & MEM_Str );
68758       return vdbeRecordCompareString;
68759     }
68760   }
68761 
68762   return sqlite3VdbeRecordCompare;
68763 }
68764 
68765 /*
68766 ** pCur points at an index entry created using the OP_MakeRecord opcode.
68767 ** Read the rowid (the last field in the record) and store it in *rowid.
68768 ** Return SQLITE_OK if everything works, or an error code otherwise.
68769 **
68770 ** pCur might be pointing to text obtained from a corrupt database file.
68771 ** So the content cannot be trusted.  Do appropriate checks on the content.
68772 */
68773 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
68774   i64 nCellKey = 0;
68775   int rc;
68776   u32 szHdr;        /* Size of the header */
68777   u32 typeRowid;    /* Serial type of the rowid */
68778   u32 lenRowid;     /* Size of the rowid */
68779   Mem m, v;
68780 
68781   /* Get the size of the index entry.  Only indices entries of less
68782   ** than 2GiB are support - anything large must be database corruption.
68783   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
68784   ** this code can safely assume that nCellKey is 32-bits
68785   */
68786   assert( sqlite3BtreeCursorIsValid(pCur) );
68787   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
68788   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
68789   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
68790 
68791   /* Read in the complete content of the index entry */
68792   sqlite3VdbeMemInit(&m, db, 0);
68793   rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
68794   if( rc ){
68795     return rc;
68796   }
68797 
68798   /* The index entry must begin with a header size */
68799   (void)getVarint32((u8*)m.z, szHdr);
68800   testcase( szHdr==3 );
68801   testcase( szHdr==m.n );
68802   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
68803     goto idx_rowid_corruption;
68804   }
68805 
68806   /* The last field of the index should be an integer - the ROWID.
68807   ** Verify that the last entry really is an integer. */
68808   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
68809   testcase( typeRowid==1 );
68810   testcase( typeRowid==2 );
68811   testcase( typeRowid==3 );
68812   testcase( typeRowid==4 );
68813   testcase( typeRowid==5 );
68814   testcase( typeRowid==6 );
68815   testcase( typeRowid==8 );
68816   testcase( typeRowid==9 );
68817   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
68818     goto idx_rowid_corruption;
68819   }
68820   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
68821   testcase( (u32)m.n==szHdr+lenRowid );
68822   if( unlikely((u32)m.n<szHdr+lenRowid) ){
68823     goto idx_rowid_corruption;
68824   }
68825 
68826   /* Fetch the integer off the end of the index record */
68827   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
68828   *rowid = v.u.i;
68829   sqlite3VdbeMemRelease(&m);
68830   return SQLITE_OK;
68831 
68832   /* Jump here if database corruption is detected after m has been
68833   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
68834 idx_rowid_corruption:
68835   testcase( m.szMalloc!=0 );
68836   sqlite3VdbeMemRelease(&m);
68837   return SQLITE_CORRUPT_BKPT;
68838 }
68839 
68840 /*
68841 ** Compare the key of the index entry that cursor pC is pointing to against
68842 ** the key string in pUnpacked.  Write into *pRes a number
68843 ** that is negative, zero, or positive if pC is less than, equal to,
68844 ** or greater than pUnpacked.  Return SQLITE_OK on success.
68845 **
68846 ** pUnpacked is either created without a rowid or is truncated so that it
68847 ** omits the rowid at the end.  The rowid at the end of the index entry
68848 ** is ignored as well.  Hence, this routine only compares the prefixes
68849 ** of the keys prior to the final rowid, not the entire key.
68850 */
68851 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
68852   sqlite3 *db,                     /* Database connection */
68853   VdbeCursor *pC,                  /* The cursor to compare against */
68854   UnpackedRecord *pUnpacked,       /* Unpacked version of key */
68855   int *res                         /* Write the comparison result here */
68856 ){
68857   i64 nCellKey = 0;
68858   int rc;
68859   BtCursor *pCur = pC->pCursor;
68860   Mem m;
68861 
68862   assert( sqlite3BtreeCursorIsValid(pCur) );
68863   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
68864   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
68865   /* nCellKey will always be between 0 and 0xffffffff because of the way
68866   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
68867   if( nCellKey<=0 || nCellKey>0x7fffffff ){
68868     *res = 0;
68869     return SQLITE_CORRUPT_BKPT;
68870   }
68871   sqlite3VdbeMemInit(&m, db, 0);
68872   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
68873   if( rc ){
68874     return rc;
68875   }
68876   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
68877   sqlite3VdbeMemRelease(&m);
68878   return SQLITE_OK;
68879 }
68880 
68881 /*
68882 ** This routine sets the value to be returned by subsequent calls to
68883 ** sqlite3_changes() on the database handle 'db'.
68884 */
68885 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
68886   assert( sqlite3_mutex_held(db->mutex) );
68887   db->nChange = nChange;
68888   db->nTotalChange += nChange;
68889 }
68890 
68891 /*
68892 ** Set a flag in the vdbe to update the change counter when it is finalised
68893 ** or reset.
68894 */
68895 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
68896   v->changeCntOn = 1;
68897 }
68898 
68899 /*
68900 ** Mark every prepared statement associated with a database connection
68901 ** as expired.
68902 **
68903 ** An expired statement means that recompilation of the statement is
68904 ** recommend.  Statements expire when things happen that make their
68905 ** programs obsolete.  Removing user-defined functions or collating
68906 ** sequences, or changing an authorization function are the types of
68907 ** things that make prepared statements obsolete.
68908 */
68909 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
68910   Vdbe *p;
68911   for(p = db->pVdbe; p; p=p->pNext){
68912     p->expired = 1;
68913   }
68914 }
68915 
68916 /*
68917 ** Return the database associated with the Vdbe.
68918 */
68919 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
68920   return v->db;
68921 }
68922 
68923 /*
68924 ** Return a pointer to an sqlite3_value structure containing the value bound
68925 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
68926 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
68927 ** constants) to the value before returning it.
68928 **
68929 ** The returned value must be freed by the caller using sqlite3ValueFree().
68930 */
68931 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
68932   assert( iVar>0 );
68933   if( v ){
68934     Mem *pMem = &v->aVar[iVar-1];
68935     if( 0==(pMem->flags & MEM_Null) ){
68936       sqlite3_value *pRet = sqlite3ValueNew(v->db);
68937       if( pRet ){
68938         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
68939         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
68940       }
68941       return pRet;
68942     }
68943   }
68944   return 0;
68945 }
68946 
68947 /*
68948 ** Configure SQL variable iVar so that binding a new value to it signals
68949 ** to sqlite3_reoptimize() that re-preparing the statement may result
68950 ** in a better query plan.
68951 */
68952 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
68953   assert( iVar>0 );
68954   if( iVar>32 ){
68955     v->expmask = 0xffffffff;
68956   }else{
68957     v->expmask |= ((u32)1 << (iVar-1));
68958   }
68959 }
68960 
68961 #ifndef SQLITE_OMIT_VIRTUALTABLE
68962 /*
68963 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
68964 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
68965 ** in memory obtained from sqlite3DbMalloc).
68966 */
68967 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
68968   sqlite3 *db = p->db;
68969   sqlite3DbFree(db, p->zErrMsg);
68970   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
68971   sqlite3_free(pVtab->zErrMsg);
68972   pVtab->zErrMsg = 0;
68973 }
68974 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68975 
68976 /************** End of vdbeaux.c *********************************************/
68977 /************** Begin file vdbeapi.c *****************************************/
68978 /*
68979 ** 2004 May 26
68980 **
68981 ** The author disclaims copyright to this source code.  In place of
68982 ** a legal notice, here is a blessing:
68983 **
68984 **    May you do good and not evil.
68985 **    May you find forgiveness for yourself and forgive others.
68986 **    May you share freely, never taking more than you give.
68987 **
68988 *************************************************************************
68989 **
68990 ** This file contains code use to implement APIs that are part of the
68991 ** VDBE.
68992 */
68993 
68994 #ifndef SQLITE_OMIT_DEPRECATED
68995 /*
68996 ** Return TRUE (non-zero) of the statement supplied as an argument needs
68997 ** to be recompiled.  A statement needs to be recompiled whenever the
68998 ** execution environment changes in a way that would alter the program
68999 ** that sqlite3_prepare() generates.  For example, if new functions or
69000 ** collating sequences are registered or if an authorizer function is
69001 ** added or changed.
69002 */
69003 SQLITE_API int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt *pStmt){
69004   Vdbe *p = (Vdbe*)pStmt;
69005   return p==0 || p->expired;
69006 }
69007 #endif
69008 
69009 /*
69010 ** Check on a Vdbe to make sure it has not been finalized.  Log
69011 ** an error and return true if it has been finalized (or is otherwise
69012 ** invalid).  Return false if it is ok.
69013 */
69014 static int vdbeSafety(Vdbe *p){
69015   if( p->db==0 ){
69016     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
69017     return 1;
69018   }else{
69019     return 0;
69020   }
69021 }
69022 static int vdbeSafetyNotNull(Vdbe *p){
69023   if( p==0 ){
69024     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
69025     return 1;
69026   }else{
69027     return vdbeSafety(p);
69028   }
69029 }
69030 
69031 /*
69032 ** The following routine destroys a virtual machine that is created by
69033 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
69034 ** success/failure code that describes the result of executing the virtual
69035 ** machine.
69036 **
69037 ** This routine sets the error code and string returned by
69038 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
69039 */
69040 SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt){
69041   int rc;
69042   if( pStmt==0 ){
69043     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
69044     ** pointer is a harmless no-op. */
69045     rc = SQLITE_OK;
69046   }else{
69047     Vdbe *v = (Vdbe*)pStmt;
69048     sqlite3 *db = v->db;
69049     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
69050     sqlite3_mutex_enter(db->mutex);
69051     rc = sqlite3VdbeFinalize(v);
69052     rc = sqlite3ApiExit(db, rc);
69053     sqlite3LeaveMutexAndCloseZombie(db);
69054   }
69055   return rc;
69056 }
69057 
69058 /*
69059 ** Terminate the current execution of an SQL statement and reset it
69060 ** back to its starting state so that it can be reused. A success code from
69061 ** the prior execution is returned.
69062 **
69063 ** This routine sets the error code and string returned by
69064 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
69065 */
69066 SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt){
69067   int rc;
69068   if( pStmt==0 ){
69069     rc = SQLITE_OK;
69070   }else{
69071     Vdbe *v = (Vdbe*)pStmt;
69072     sqlite3_mutex_enter(v->db->mutex);
69073     rc = sqlite3VdbeReset(v);
69074     sqlite3VdbeRewind(v);
69075     assert( (rc & (v->db->errMask))==rc );
69076     rc = sqlite3ApiExit(v->db, rc);
69077     sqlite3_mutex_leave(v->db->mutex);
69078   }
69079   return rc;
69080 }
69081 
69082 /*
69083 ** Set all the parameters in the compiled SQL statement to NULL.
69084 */
69085 SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt *pStmt){
69086   int i;
69087   int rc = SQLITE_OK;
69088   Vdbe *p = (Vdbe*)pStmt;
69089 #if SQLITE_THREADSAFE
69090   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
69091 #endif
69092   sqlite3_mutex_enter(mutex);
69093   for(i=0; i<p->nVar; i++){
69094     sqlite3VdbeMemRelease(&p->aVar[i]);
69095     p->aVar[i].flags = MEM_Null;
69096   }
69097   if( p->isPrepareV2 && p->expmask ){
69098     p->expired = 1;
69099   }
69100   sqlite3_mutex_leave(mutex);
69101   return rc;
69102 }
69103 
69104 
69105 /**************************** sqlite3_value_  *******************************
69106 ** The following routines extract information from a Mem or sqlite3_value
69107 ** structure.
69108 */
69109 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value *pVal){
69110   Mem *p = (Mem*)pVal;
69111   if( p->flags & (MEM_Blob|MEM_Str) ){
69112     sqlite3VdbeMemExpandBlob(p);
69113     p->flags |= MEM_Blob;
69114     return p->n ? p->z : 0;
69115   }else{
69116     return sqlite3_value_text(pVal);
69117   }
69118 }
69119 SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value *pVal){
69120   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
69121 }
69122 SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value *pVal){
69123   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
69124 }
69125 SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value *pVal){
69126   return sqlite3VdbeRealValue((Mem*)pVal);
69127 }
69128 SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value *pVal){
69129   return (int)sqlite3VdbeIntValue((Mem*)pVal);
69130 }
69131 SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value *pVal){
69132   return sqlite3VdbeIntValue((Mem*)pVal);
69133 }
69134 SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value *pVal){
69135   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
69136 }
69137 #ifndef SQLITE_OMIT_UTF16
69138 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value* pVal){
69139   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
69140 }
69141 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value *pVal){
69142   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
69143 }
69144 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value *pVal){
69145   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
69146 }
69147 #endif /* SQLITE_OMIT_UTF16 */
69148 /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
69149 ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
69150 ** point number string BLOB NULL
69151 */
69152 SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value* pVal){
69153   static const u8 aType[] = {
69154      SQLITE_BLOB,     /* 0x00 */
69155      SQLITE_NULL,     /* 0x01 */
69156      SQLITE_TEXT,     /* 0x02 */
69157      SQLITE_NULL,     /* 0x03 */
69158      SQLITE_INTEGER,  /* 0x04 */
69159      SQLITE_NULL,     /* 0x05 */
69160      SQLITE_INTEGER,  /* 0x06 */
69161      SQLITE_NULL,     /* 0x07 */
69162      SQLITE_FLOAT,    /* 0x08 */
69163      SQLITE_NULL,     /* 0x09 */
69164      SQLITE_FLOAT,    /* 0x0a */
69165      SQLITE_NULL,     /* 0x0b */
69166      SQLITE_INTEGER,  /* 0x0c */
69167      SQLITE_NULL,     /* 0x0d */
69168      SQLITE_INTEGER,  /* 0x0e */
69169      SQLITE_NULL,     /* 0x0f */
69170      SQLITE_BLOB,     /* 0x10 */
69171      SQLITE_NULL,     /* 0x11 */
69172      SQLITE_TEXT,     /* 0x12 */
69173      SQLITE_NULL,     /* 0x13 */
69174      SQLITE_INTEGER,  /* 0x14 */
69175      SQLITE_NULL,     /* 0x15 */
69176      SQLITE_INTEGER,  /* 0x16 */
69177      SQLITE_NULL,     /* 0x17 */
69178      SQLITE_FLOAT,    /* 0x18 */
69179      SQLITE_NULL,     /* 0x19 */
69180      SQLITE_FLOAT,    /* 0x1a */
69181      SQLITE_NULL,     /* 0x1b */
69182      SQLITE_INTEGER,  /* 0x1c */
69183      SQLITE_NULL,     /* 0x1d */
69184      SQLITE_INTEGER,  /* 0x1e */
69185      SQLITE_NULL,     /* 0x1f */
69186   };
69187   return aType[pVal->flags&MEM_AffMask];
69188 }
69189 
69190 /**************************** sqlite3_result_  *******************************
69191 ** The following routines are used by user-defined functions to specify
69192 ** the function result.
69193 **
69194 ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
69195 ** result as a string or blob but if the string or blob is too large, it
69196 ** then sets the error code to SQLITE_TOOBIG
69197 **
69198 ** The invokeValueDestructor(P,X) routine invokes destructor function X()
69199 ** on value P is not going to be used and need to be destroyed.
69200 */
69201 static void setResultStrOrError(
69202   sqlite3_context *pCtx,  /* Function context */
69203   const char *z,          /* String pointer */
69204   int n,                  /* Bytes in string, or negative */
69205   u8 enc,                 /* Encoding of z.  0 for BLOBs */
69206   void (*xDel)(void*)     /* Destructor function */
69207 ){
69208   if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
69209     sqlite3_result_error_toobig(pCtx);
69210   }
69211 }
69212 static int invokeValueDestructor(
69213   const void *p,             /* Value to destroy */
69214   void (*xDel)(void*),       /* The destructor */
69215   sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
69216 ){
69217   assert( xDel!=SQLITE_DYNAMIC );
69218   if( xDel==0 ){
69219     /* noop */
69220   }else if( xDel==SQLITE_TRANSIENT ){
69221     /* noop */
69222   }else{
69223     xDel((void*)p);
69224   }
69225   if( pCtx ) sqlite3_result_error_toobig(pCtx);
69226   return SQLITE_TOOBIG;
69227 }
69228 SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(
69229   sqlite3_context *pCtx,
69230   const void *z,
69231   int n,
69232   void (*xDel)(void *)
69233 ){
69234   assert( n>=0 );
69235   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69236   setResultStrOrError(pCtx, z, n, 0, xDel);
69237 }
69238 SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(
69239   sqlite3_context *pCtx,
69240   const void *z,
69241   sqlite3_uint64 n,
69242   void (*xDel)(void *)
69243 ){
69244   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69245   assert( xDel!=SQLITE_DYNAMIC );
69246   if( n>0x7fffffff ){
69247     (void)invokeValueDestructor(z, xDel, pCtx);
69248   }else{
69249     setResultStrOrError(pCtx, z, (int)n, 0, xDel);
69250   }
69251 }
69252 SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context *pCtx, double rVal){
69253   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69254   sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
69255 }
69256 SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
69257   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69258   pCtx->isError = SQLITE_ERROR;
69259   pCtx->fErrorOrAux = 1;
69260   sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
69261 }
69262 #ifndef SQLITE_OMIT_UTF16
69263 SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
69264   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69265   pCtx->isError = SQLITE_ERROR;
69266   pCtx->fErrorOrAux = 1;
69267   sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
69268 }
69269 #endif
69270 SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context *pCtx, int iVal){
69271   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69272   sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
69273 }
69274 SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
69275   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69276   sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
69277 }
69278 SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context *pCtx){
69279   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69280   sqlite3VdbeMemSetNull(pCtx->pOut);
69281 }
69282 SQLITE_API void SQLITE_STDCALL sqlite3_result_text(
69283   sqlite3_context *pCtx,
69284   const char *z,
69285   int n,
69286   void (*xDel)(void *)
69287 ){
69288   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69289   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
69290 }
69291 SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(
69292   sqlite3_context *pCtx,
69293   const char *z,
69294   sqlite3_uint64 n,
69295   void (*xDel)(void *),
69296   unsigned char enc
69297 ){
69298   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69299   assert( xDel!=SQLITE_DYNAMIC );
69300   if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
69301   if( n>0x7fffffff ){
69302     (void)invokeValueDestructor(z, xDel, pCtx);
69303   }else{
69304     setResultStrOrError(pCtx, z, (int)n, enc, xDel);
69305   }
69306 }
69307 #ifndef SQLITE_OMIT_UTF16
69308 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(
69309   sqlite3_context *pCtx,
69310   const void *z,
69311   int n,
69312   void (*xDel)(void *)
69313 ){
69314   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69315   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
69316 }
69317 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(
69318   sqlite3_context *pCtx,
69319   const void *z,
69320   int n,
69321   void (*xDel)(void *)
69322 ){
69323   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69324   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
69325 }
69326 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(
69327   sqlite3_context *pCtx,
69328   const void *z,
69329   int n,
69330   void (*xDel)(void *)
69331 ){
69332   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69333   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
69334 }
69335 #endif /* SQLITE_OMIT_UTF16 */
69336 SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
69337   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69338   sqlite3VdbeMemCopy(pCtx->pOut, pValue);
69339 }
69340 SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
69341   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69342   sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
69343 }
69344 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
69345   pCtx->isError = errCode;
69346   pCtx->fErrorOrAux = 1;
69347 #ifdef SQLITE_DEBUG
69348   if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
69349 #endif
69350   if( pCtx->pOut->flags & MEM_Null ){
69351     sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
69352                          SQLITE_UTF8, SQLITE_STATIC);
69353   }
69354 }
69355 
69356 /* Force an SQLITE_TOOBIG error. */
69357 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context *pCtx){
69358   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69359   pCtx->isError = SQLITE_TOOBIG;
69360   pCtx->fErrorOrAux = 1;
69361   sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
69362                        SQLITE_UTF8, SQLITE_STATIC);
69363 }
69364 
69365 /* An SQLITE_NOMEM error. */
69366 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context *pCtx){
69367   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69368   sqlite3VdbeMemSetNull(pCtx->pOut);
69369   pCtx->isError = SQLITE_NOMEM;
69370   pCtx->fErrorOrAux = 1;
69371   pCtx->pOut->db->mallocFailed = 1;
69372 }
69373 
69374 /*
69375 ** This function is called after a transaction has been committed. It
69376 ** invokes callbacks registered with sqlite3_wal_hook() as required.
69377 */
69378 static int doWalCallbacks(sqlite3 *db){
69379   int rc = SQLITE_OK;
69380 #ifndef SQLITE_OMIT_WAL
69381   int i;
69382   for(i=0; i<db->nDb; i++){
69383     Btree *pBt = db->aDb[i].pBt;
69384     if( pBt ){
69385       int nEntry;
69386       sqlite3BtreeEnter(pBt);
69387       nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
69388       sqlite3BtreeLeave(pBt);
69389       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
69390         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
69391       }
69392     }
69393   }
69394 #endif
69395   return rc;
69396 }
69397 
69398 /*
69399 ** Execute the statement pStmt, either until a row of data is ready, the
69400 ** statement is completely executed or an error occurs.
69401 **
69402 ** This routine implements the bulk of the logic behind the sqlite_step()
69403 ** API.  The only thing omitted is the automatic recompile if a
69404 ** schema change has occurred.  That detail is handled by the
69405 ** outer sqlite3_step() wrapper procedure.
69406 */
69407 static int sqlite3Step(Vdbe *p){
69408   sqlite3 *db;
69409   int rc;
69410 
69411   assert(p);
69412   if( p->magic!=VDBE_MAGIC_RUN ){
69413     /* We used to require that sqlite3_reset() be called before retrying
69414     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
69415     ** with version 3.7.0, we changed this so that sqlite3_reset() would
69416     ** be called automatically instead of throwing the SQLITE_MISUSE error.
69417     ** This "automatic-reset" change is not technically an incompatibility,
69418     ** since any application that receives an SQLITE_MISUSE is broken by
69419     ** definition.
69420     **
69421     ** Nevertheless, some published applications that were originally written
69422     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
69423     ** returns, and those were broken by the automatic-reset change.  As a
69424     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
69425     ** legacy behavior of returning SQLITE_MISUSE for cases where the
69426     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
69427     ** or SQLITE_BUSY error.
69428     */
69429 #ifdef SQLITE_OMIT_AUTORESET
69430     if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
69431       sqlite3_reset((sqlite3_stmt*)p);
69432     }else{
69433       return SQLITE_MISUSE_BKPT;
69434     }
69435 #else
69436     sqlite3_reset((sqlite3_stmt*)p);
69437 #endif
69438   }
69439 
69440   /* Check that malloc() has not failed. If it has, return early. */
69441   db = p->db;
69442   if( db->mallocFailed ){
69443     p->rc = SQLITE_NOMEM;
69444     return SQLITE_NOMEM;
69445   }
69446 
69447   if( p->pc<=0 && p->expired ){
69448     p->rc = SQLITE_SCHEMA;
69449     rc = SQLITE_ERROR;
69450     goto end_of_step;
69451   }
69452   if( p->pc<0 ){
69453     /* If there are no other statements currently running, then
69454     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
69455     ** from interrupting a statement that has not yet started.
69456     */
69457     if( db->nVdbeActive==0 ){
69458       db->u1.isInterrupted = 0;
69459     }
69460 
69461     assert( db->nVdbeWrite>0 || db->autoCommit==0
69462         || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
69463     );
69464 
69465 #ifndef SQLITE_OMIT_TRACE
69466     if( db->xProfile && !db->init.busy ){
69467       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
69468     }
69469 #endif
69470 
69471     db->nVdbeActive++;
69472     if( p->readOnly==0 ) db->nVdbeWrite++;
69473     if( p->bIsReader ) db->nVdbeRead++;
69474     p->pc = 0;
69475   }
69476 #ifdef SQLITE_DEBUG
69477   p->rcApp = SQLITE_OK;
69478 #endif
69479 #ifndef SQLITE_OMIT_EXPLAIN
69480   if( p->explain ){
69481     rc = sqlite3VdbeList(p);
69482   }else
69483 #endif /* SQLITE_OMIT_EXPLAIN */
69484   {
69485     db->nVdbeExec++;
69486     rc = sqlite3VdbeExec(p);
69487     db->nVdbeExec--;
69488   }
69489 
69490 #ifndef SQLITE_OMIT_TRACE
69491   /* Invoke the profile callback if there is one
69492   */
69493   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
69494     sqlite3_int64 iNow;
69495     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
69496     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
69497   }
69498 #endif
69499 
69500   if( rc==SQLITE_DONE ){
69501     assert( p->rc==SQLITE_OK );
69502     p->rc = doWalCallbacks(db);
69503     if( p->rc!=SQLITE_OK ){
69504       rc = SQLITE_ERROR;
69505     }
69506   }
69507 
69508   db->errCode = rc;
69509   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
69510     p->rc = SQLITE_NOMEM;
69511   }
69512 end_of_step:
69513   /* At this point local variable rc holds the value that should be
69514   ** returned if this statement was compiled using the legacy
69515   ** sqlite3_prepare() interface. According to the docs, this can only
69516   ** be one of the values in the first assert() below. Variable p->rc
69517   ** contains the value that would be returned if sqlite3_finalize()
69518   ** were called on statement p.
69519   */
69520   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
69521        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
69522   );
69523   assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
69524   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
69525     /* If this statement was prepared using sqlite3_prepare_v2(), and an
69526     ** error has occurred, then return the error code in p->rc to the
69527     ** caller. Set the error code in the database handle to the same value.
69528     */
69529     rc = sqlite3VdbeTransferError(p);
69530   }
69531   return (rc&db->errMask);
69532 }
69533 
69534 /*
69535 ** This is the top-level implementation of sqlite3_step().  Call
69536 ** sqlite3Step() to do most of the work.  If a schema error occurs,
69537 ** call sqlite3Reprepare() and try again.
69538 */
69539 SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt *pStmt){
69540   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
69541   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
69542   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
69543   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
69544   sqlite3 *db;             /* The database connection */
69545 
69546   if( vdbeSafetyNotNull(v) ){
69547     return SQLITE_MISUSE_BKPT;
69548   }
69549   db = v->db;
69550   sqlite3_mutex_enter(db->mutex);
69551   v->doingRerun = 0;
69552   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
69553          && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
69554     int savedPc = v->pc;
69555     rc2 = rc = sqlite3Reprepare(v);
69556     if( rc!=SQLITE_OK) break;
69557     sqlite3_reset(pStmt);
69558     if( savedPc>=0 ) v->doingRerun = 1;
69559     assert( v->expired==0 );
69560   }
69561   if( rc2!=SQLITE_OK ){
69562     /* This case occurs after failing to recompile an sql statement.
69563     ** The error message from the SQL compiler has already been loaded
69564     ** into the database handle. This block copies the error message
69565     ** from the database handle into the statement and sets the statement
69566     ** program counter to 0 to ensure that when the statement is
69567     ** finalized or reset the parser error message is available via
69568     ** sqlite3_errmsg() and sqlite3_errcode().
69569     */
69570     const char *zErr = (const char *)sqlite3_value_text(db->pErr);
69571     sqlite3DbFree(db, v->zErrMsg);
69572     if( !db->mallocFailed ){
69573       v->zErrMsg = sqlite3DbStrDup(db, zErr);
69574       v->rc = rc2;
69575     } else {
69576       v->zErrMsg = 0;
69577       v->rc = rc = SQLITE_NOMEM;
69578     }
69579   }
69580   rc = sqlite3ApiExit(db, rc);
69581   sqlite3_mutex_leave(db->mutex);
69582   return rc;
69583 }
69584 
69585 
69586 /*
69587 ** Extract the user data from a sqlite3_context structure and return a
69588 ** pointer to it.
69589 */
69590 SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context *p){
69591   assert( p && p->pFunc );
69592   return p->pFunc->pUserData;
69593 }
69594 
69595 /*
69596 ** Extract the user data from a sqlite3_context structure and return a
69597 ** pointer to it.
69598 **
69599 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
69600 ** returns a copy of the pointer to the database connection (the 1st
69601 ** parameter) of the sqlite3_create_function() and
69602 ** sqlite3_create_function16() routines that originally registered the
69603 ** application defined function.
69604 */
69605 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context *p){
69606   assert( p && p->pFunc );
69607   return p->pOut->db;
69608 }
69609 
69610 /*
69611 ** Return the current time for a statement.  If the current time
69612 ** is requested more than once within the same run of a single prepared
69613 ** statement, the exact same time is returned for each invocation regardless
69614 ** of the amount of time that elapses between invocations.  In other words,
69615 ** the time returned is always the time of the first call.
69616 */
69617 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
69618   int rc;
69619 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
69620   sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
69621   assert( p->pVdbe!=0 );
69622 #else
69623   sqlite3_int64 iTime = 0;
69624   sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
69625 #endif
69626   if( *piTime==0 ){
69627     rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
69628     if( rc ) *piTime = 0;
69629   }
69630   return *piTime;
69631 }
69632 
69633 /*
69634 ** The following is the implementation of an SQL function that always
69635 ** fails with an error message stating that the function is used in the
69636 ** wrong context.  The sqlite3_overload_function() API might construct
69637 ** SQL function that use this routine so that the functions will exist
69638 ** for name resolution but are actually overloaded by the xFindFunction
69639 ** method of virtual tables.
69640 */
69641 SQLITE_PRIVATE void sqlite3InvalidFunction(
69642   sqlite3_context *context,  /* The function calling context */
69643   int NotUsed,               /* Number of arguments to the function */
69644   sqlite3_value **NotUsed2   /* Value of each argument */
69645 ){
69646   const char *zName = context->pFunc->zName;
69647   char *zErr;
69648   UNUSED_PARAMETER2(NotUsed, NotUsed2);
69649   zErr = sqlite3_mprintf(
69650       "unable to use function %s in the requested context", zName);
69651   sqlite3_result_error(context, zErr, -1);
69652   sqlite3_free(zErr);
69653 }
69654 
69655 /*
69656 ** Create a new aggregate context for p and return a pointer to
69657 ** its pMem->z element.
69658 */
69659 static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
69660   Mem *pMem = p->pMem;
69661   assert( (pMem->flags & MEM_Agg)==0 );
69662   if( nByte<=0 ){
69663     sqlite3VdbeMemSetNull(pMem);
69664     pMem->z = 0;
69665   }else{
69666     sqlite3VdbeMemClearAndResize(pMem, nByte);
69667     pMem->flags = MEM_Agg;
69668     pMem->u.pDef = p->pFunc;
69669     if( pMem->z ){
69670       memset(pMem->z, 0, nByte);
69671     }
69672   }
69673   return (void*)pMem->z;
69674 }
69675 
69676 /*
69677 ** Allocate or return the aggregate context for a user function.  A new
69678 ** context is allocated on the first call.  Subsequent calls return the
69679 ** same context that was returned on prior calls.
69680 */
69681 SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context *p, int nByte){
69682   assert( p && p->pFunc && p->pFunc->xStep );
69683   assert( sqlite3_mutex_held(p->pOut->db->mutex) );
69684   testcase( nByte<0 );
69685   if( (p->pMem->flags & MEM_Agg)==0 ){
69686     return createAggContext(p, nByte);
69687   }else{
69688     return (void*)p->pMem->z;
69689   }
69690 }
69691 
69692 /*
69693 ** Return the auxiliary data pointer, if any, for the iArg'th argument to
69694 ** the user-function defined by pCtx.
69695 */
69696 SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
69697   AuxData *pAuxData;
69698 
69699   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69700 #if SQLITE_ENABLE_STAT3_OR_STAT4
69701   if( pCtx->pVdbe==0 ) return 0;
69702 #else
69703   assert( pCtx->pVdbe!=0 );
69704 #endif
69705   for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
69706     if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
69707   }
69708 
69709   return (pAuxData ? pAuxData->pAux : 0);
69710 }
69711 
69712 /*
69713 ** Set the auxiliary data pointer and delete function, for the iArg'th
69714 ** argument to the user-function defined by pCtx. Any previous value is
69715 ** deleted by calling the delete function specified when it was set.
69716 */
69717 SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(
69718   sqlite3_context *pCtx,
69719   int iArg,
69720   void *pAux,
69721   void (*xDelete)(void*)
69722 ){
69723   AuxData *pAuxData;
69724   Vdbe *pVdbe = pCtx->pVdbe;
69725 
69726   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69727   if( iArg<0 ) goto failed;
69728 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69729   if( pVdbe==0 ) goto failed;
69730 #else
69731   assert( pVdbe!=0 );
69732 #endif
69733 
69734   for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
69735     if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
69736   }
69737   if( pAuxData==0 ){
69738     pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
69739     if( !pAuxData ) goto failed;
69740     pAuxData->iOp = pCtx->iOp;
69741     pAuxData->iArg = iArg;
69742     pAuxData->pNext = pVdbe->pAuxData;
69743     pVdbe->pAuxData = pAuxData;
69744     if( pCtx->fErrorOrAux==0 ){
69745       pCtx->isError = 0;
69746       pCtx->fErrorOrAux = 1;
69747     }
69748   }else if( pAuxData->xDelete ){
69749     pAuxData->xDelete(pAuxData->pAux);
69750   }
69751 
69752   pAuxData->pAux = pAux;
69753   pAuxData->xDelete = xDelete;
69754   return;
69755 
69756 failed:
69757   if( xDelete ){
69758     xDelete(pAux);
69759   }
69760 }
69761 
69762 #ifndef SQLITE_OMIT_DEPRECATED
69763 /*
69764 ** Return the number of times the Step function of an aggregate has been
69765 ** called.
69766 **
69767 ** This function is deprecated.  Do not use it for new code.  It is
69768 ** provide only to avoid breaking legacy code.  New aggregate function
69769 ** implementations should keep their own counts within their aggregate
69770 ** context.
69771 */
69772 SQLITE_API int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context *p){
69773   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
69774   return p->pMem->n;
69775 }
69776 #endif
69777 
69778 /*
69779 ** Return the number of columns in the result set for the statement pStmt.
69780 */
69781 SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt){
69782   Vdbe *pVm = (Vdbe *)pStmt;
69783   return pVm ? pVm->nResColumn : 0;
69784 }
69785 
69786 /*
69787 ** Return the number of values available from the current row of the
69788 ** currently executing statement pStmt.
69789 */
69790 SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt){
69791   Vdbe *pVm = (Vdbe *)pStmt;
69792   if( pVm==0 || pVm->pResultSet==0 ) return 0;
69793   return pVm->nResColumn;
69794 }
69795 
69796 /*
69797 ** Return a pointer to static memory containing an SQL NULL value.
69798 */
69799 static const Mem *columnNullValue(void){
69800   /* Even though the Mem structure contains an element
69801   ** of type i64, on certain architectures (x86) with certain compiler
69802   ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
69803   ** instead of an 8-byte one. This all works fine, except that when
69804   ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
69805   ** that a Mem structure is located on an 8-byte boundary. To prevent
69806   ** these assert()s from failing, when building with SQLITE_DEBUG defined
69807   ** using gcc, we force nullMem to be 8-byte aligned using the magical
69808   ** __attribute__((aligned(8))) macro.  */
69809   static const Mem nullMem
69810 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
69811     __attribute__((aligned(8)))
69812 #endif
69813     = {
69814         /* .u          = */ {0},
69815         /* .flags      = */ MEM_Null,
69816         /* .enc        = */ 0,
69817         /* .n          = */ 0,
69818         /* .z          = */ 0,
69819         /* .zMalloc    = */ 0,
69820         /* .szMalloc   = */ 0,
69821         /* .iPadding1  = */ 0,
69822         /* .db         = */ 0,
69823         /* .xDel       = */ 0,
69824 #ifdef SQLITE_DEBUG
69825         /* .pScopyFrom = */ 0,
69826         /* .pFiller    = */ 0,
69827 #endif
69828       };
69829   return &nullMem;
69830 }
69831 
69832 /*
69833 ** Check to see if column iCol of the given statement is valid.  If
69834 ** it is, return a pointer to the Mem for the value of that column.
69835 ** If iCol is not valid, return a pointer to a Mem which has a value
69836 ** of NULL.
69837 */
69838 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
69839   Vdbe *pVm;
69840   Mem *pOut;
69841 
69842   pVm = (Vdbe *)pStmt;
69843   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
69844     sqlite3_mutex_enter(pVm->db->mutex);
69845     pOut = &pVm->pResultSet[i];
69846   }else{
69847     if( pVm && ALWAYS(pVm->db) ){
69848       sqlite3_mutex_enter(pVm->db->mutex);
69849       sqlite3Error(pVm->db, SQLITE_RANGE);
69850     }
69851     pOut = (Mem*)columnNullValue();
69852   }
69853   return pOut;
69854 }
69855 
69856 /*
69857 ** This function is called after invoking an sqlite3_value_XXX function on a
69858 ** column value (i.e. a value returned by evaluating an SQL expression in the
69859 ** select list of a SELECT statement) that may cause a malloc() failure. If
69860 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
69861 ** code of statement pStmt set to SQLITE_NOMEM.
69862 **
69863 ** Specifically, this is called from within:
69864 **
69865 **     sqlite3_column_int()
69866 **     sqlite3_column_int64()
69867 **     sqlite3_column_text()
69868 **     sqlite3_column_text16()
69869 **     sqlite3_column_real()
69870 **     sqlite3_column_bytes()
69871 **     sqlite3_column_bytes16()
69872 **     sqiite3_column_blob()
69873 */
69874 static void columnMallocFailure(sqlite3_stmt *pStmt)
69875 {
69876   /* If malloc() failed during an encoding conversion within an
69877   ** sqlite3_column_XXX API, then set the return code of the statement to
69878   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
69879   ** and _finalize() will return NOMEM.
69880   */
69881   Vdbe *p = (Vdbe *)pStmt;
69882   if( p ){
69883     p->rc = sqlite3ApiExit(p->db, p->rc);
69884     sqlite3_mutex_leave(p->db->mutex);
69885   }
69886 }
69887 
69888 /**************************** sqlite3_column_  *******************************
69889 ** The following routines are used to access elements of the current row
69890 ** in the result set.
69891 */
69892 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
69893   const void *val;
69894   val = sqlite3_value_blob( columnMem(pStmt,i) );
69895   /* Even though there is no encoding conversion, value_blob() might
69896   ** need to call malloc() to expand the result of a zeroblob()
69897   ** expression.
69898   */
69899   columnMallocFailure(pStmt);
69900   return val;
69901 }
69902 SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
69903   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
69904   columnMallocFailure(pStmt);
69905   return val;
69906 }
69907 SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
69908   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
69909   columnMallocFailure(pStmt);
69910   return val;
69911 }
69912 SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt *pStmt, int i){
69913   double val = sqlite3_value_double( columnMem(pStmt,i) );
69914   columnMallocFailure(pStmt);
69915   return val;
69916 }
69917 SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt *pStmt, int i){
69918   int val = sqlite3_value_int( columnMem(pStmt,i) );
69919   columnMallocFailure(pStmt);
69920   return val;
69921 }
69922 SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
69923   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
69924   columnMallocFailure(pStmt);
69925   return val;
69926 }
69927 SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt *pStmt, int i){
69928   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
69929   columnMallocFailure(pStmt);
69930   return val;
69931 }
69932 SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt *pStmt, int i){
69933   Mem *pOut = columnMem(pStmt, i);
69934   if( pOut->flags&MEM_Static ){
69935     pOut->flags &= ~MEM_Static;
69936     pOut->flags |= MEM_Ephem;
69937   }
69938   columnMallocFailure(pStmt);
69939   return (sqlite3_value *)pOut;
69940 }
69941 #ifndef SQLITE_OMIT_UTF16
69942 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
69943   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
69944   columnMallocFailure(pStmt);
69945   return val;
69946 }
69947 #endif /* SQLITE_OMIT_UTF16 */
69948 SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt *pStmt, int i){
69949   int iType = sqlite3_value_type( columnMem(pStmt,i) );
69950   columnMallocFailure(pStmt);
69951   return iType;
69952 }
69953 
69954 /*
69955 ** Convert the N-th element of pStmt->pColName[] into a string using
69956 ** xFunc() then return that string.  If N is out of range, return 0.
69957 **
69958 ** There are up to 5 names for each column.  useType determines which
69959 ** name is returned.  Here are the names:
69960 **
69961 **    0      The column name as it should be displayed for output
69962 **    1      The datatype name for the column
69963 **    2      The name of the database that the column derives from
69964 **    3      The name of the table that the column derives from
69965 **    4      The name of the table column that the result column derives from
69966 **
69967 ** If the result is not a simple column reference (if it is an expression
69968 ** or a constant) then useTypes 2, 3, and 4 return NULL.
69969 */
69970 static const void *columnName(
69971   sqlite3_stmt *pStmt,
69972   int N,
69973   const void *(*xFunc)(Mem*),
69974   int useType
69975 ){
69976   const void *ret;
69977   Vdbe *p;
69978   int n;
69979   sqlite3 *db;
69980 #ifdef SQLITE_ENABLE_API_ARMOR
69981   if( pStmt==0 ){
69982     (void)SQLITE_MISUSE_BKPT;
69983     return 0;
69984   }
69985 #endif
69986   ret = 0;
69987   p = (Vdbe *)pStmt;
69988   db = p->db;
69989   assert( db!=0 );
69990   n = sqlite3_column_count(pStmt);
69991   if( N<n && N>=0 ){
69992     N += useType*n;
69993     sqlite3_mutex_enter(db->mutex);
69994     assert( db->mallocFailed==0 );
69995     ret = xFunc(&p->aColName[N]);
69996      /* A malloc may have failed inside of the xFunc() call. If this
69997     ** is the case, clear the mallocFailed flag and return NULL.
69998     */
69999     if( db->mallocFailed ){
70000       db->mallocFailed = 0;
70001       ret = 0;
70002     }
70003     sqlite3_mutex_leave(db->mutex);
70004   }
70005   return ret;
70006 }
70007 
70008 /*
70009 ** Return the name of the Nth column of the result set returned by SQL
70010 ** statement pStmt.
70011 */
70012 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt *pStmt, int N){
70013   return columnName(
70014       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
70015 }
70016 #ifndef SQLITE_OMIT_UTF16
70017 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
70018   return columnName(
70019       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
70020 }
70021 #endif
70022 
70023 /*
70024 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
70025 ** not define OMIT_DECLTYPE.
70026 */
70027 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
70028 # error "Must not define both SQLITE_OMIT_DECLTYPE \
70029          and SQLITE_ENABLE_COLUMN_METADATA"
70030 #endif
70031 
70032 #ifndef SQLITE_OMIT_DECLTYPE
70033 /*
70034 ** Return the column declaration type (if applicable) of the 'i'th column
70035 ** of the result set of SQL statement pStmt.
70036 */
70037 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
70038   return columnName(
70039       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
70040 }
70041 #ifndef SQLITE_OMIT_UTF16
70042 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
70043   return columnName(
70044       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
70045 }
70046 #endif /* SQLITE_OMIT_UTF16 */
70047 #endif /* SQLITE_OMIT_DECLTYPE */
70048 
70049 #ifdef SQLITE_ENABLE_COLUMN_METADATA
70050 /*
70051 ** Return the name of the database from which a result column derives.
70052 ** NULL is returned if the result column is an expression or constant or
70053 ** anything else which is not an unambiguous reference to a database column.
70054 */
70055 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
70056   return columnName(
70057       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
70058 }
70059 #ifndef SQLITE_OMIT_UTF16
70060 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
70061   return columnName(
70062       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
70063 }
70064 #endif /* SQLITE_OMIT_UTF16 */
70065 
70066 /*
70067 ** Return the name of the table from which a result column derives.
70068 ** NULL is returned if the result column is an expression or constant or
70069 ** anything else which is not an unambiguous reference to a database column.
70070 */
70071 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
70072   return columnName(
70073       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
70074 }
70075 #ifndef SQLITE_OMIT_UTF16
70076 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
70077   return columnName(
70078       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
70079 }
70080 #endif /* SQLITE_OMIT_UTF16 */
70081 
70082 /*
70083 ** Return the name of the table column from which a result column derives.
70084 ** NULL is returned if the result column is an expression or constant or
70085 ** anything else which is not an unambiguous reference to a database column.
70086 */
70087 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
70088   return columnName(
70089       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
70090 }
70091 #ifndef SQLITE_OMIT_UTF16
70092 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
70093   return columnName(
70094       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
70095 }
70096 #endif /* SQLITE_OMIT_UTF16 */
70097 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
70098 
70099 
70100 /******************************* sqlite3_bind_  ***************************
70101 **
70102 ** Routines used to attach values to wildcards in a compiled SQL statement.
70103 */
70104 /*
70105 ** Unbind the value bound to variable i in virtual machine p. This is the
70106 ** the same as binding a NULL value to the column. If the "i" parameter is
70107 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
70108 **
70109 ** A successful evaluation of this routine acquires the mutex on p.
70110 ** the mutex is released if any kind of error occurs.
70111 **
70112 ** The error code stored in database p->db is overwritten with the return
70113 ** value in any case.
70114 */
70115 static int vdbeUnbind(Vdbe *p, int i){
70116   Mem *pVar;
70117   if( vdbeSafetyNotNull(p) ){
70118     return SQLITE_MISUSE_BKPT;
70119   }
70120   sqlite3_mutex_enter(p->db->mutex);
70121   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
70122     sqlite3Error(p->db, SQLITE_MISUSE);
70123     sqlite3_mutex_leave(p->db->mutex);
70124     sqlite3_log(SQLITE_MISUSE,
70125         "bind on a busy prepared statement: [%s]", p->zSql);
70126     return SQLITE_MISUSE_BKPT;
70127   }
70128   if( i<1 || i>p->nVar ){
70129     sqlite3Error(p->db, SQLITE_RANGE);
70130     sqlite3_mutex_leave(p->db->mutex);
70131     return SQLITE_RANGE;
70132   }
70133   i--;
70134   pVar = &p->aVar[i];
70135   sqlite3VdbeMemRelease(pVar);
70136   pVar->flags = MEM_Null;
70137   sqlite3Error(p->db, SQLITE_OK);
70138 
70139   /* If the bit corresponding to this variable in Vdbe.expmask is set, then
70140   ** binding a new value to this variable invalidates the current query plan.
70141   **
70142   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
70143   ** parameter in the WHERE clause might influence the choice of query plan
70144   ** for a statement, then the statement will be automatically recompiled,
70145   ** as if there had been a schema change, on the first sqlite3_step() call
70146   ** following any change to the bindings of that parameter.
70147   */
70148   if( p->isPrepareV2 &&
70149      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
70150   ){
70151     p->expired = 1;
70152   }
70153   return SQLITE_OK;
70154 }
70155 
70156 /*
70157 ** Bind a text or BLOB value.
70158 */
70159 static int bindText(
70160   sqlite3_stmt *pStmt,   /* The statement to bind against */
70161   int i,                 /* Index of the parameter to bind */
70162   const void *zData,     /* Pointer to the data to be bound */
70163   int nData,             /* Number of bytes of data to be bound */
70164   void (*xDel)(void*),   /* Destructor for the data */
70165   u8 encoding            /* Encoding for the data */
70166 ){
70167   Vdbe *p = (Vdbe *)pStmt;
70168   Mem *pVar;
70169   int rc;
70170 
70171   rc = vdbeUnbind(p, i);
70172   if( rc==SQLITE_OK ){
70173     if( zData!=0 ){
70174       pVar = &p->aVar[i-1];
70175       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
70176       if( rc==SQLITE_OK && encoding!=0 ){
70177         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
70178       }
70179       sqlite3Error(p->db, rc);
70180       rc = sqlite3ApiExit(p->db, rc);
70181     }
70182     sqlite3_mutex_leave(p->db->mutex);
70183   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
70184     xDel((void*)zData);
70185   }
70186   return rc;
70187 }
70188 
70189 
70190 /*
70191 ** Bind a blob value to an SQL statement variable.
70192 */
70193 SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(
70194   sqlite3_stmt *pStmt,
70195   int i,
70196   const void *zData,
70197   int nData,
70198   void (*xDel)(void*)
70199 ){
70200   return bindText(pStmt, i, zData, nData, xDel, 0);
70201 }
70202 SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(
70203   sqlite3_stmt *pStmt,
70204   int i,
70205   const void *zData,
70206   sqlite3_uint64 nData,
70207   void (*xDel)(void*)
70208 ){
70209   assert( xDel!=SQLITE_DYNAMIC );
70210   if( nData>0x7fffffff ){
70211     return invokeValueDestructor(zData, xDel, 0);
70212   }else{
70213     return bindText(pStmt, i, zData, (int)nData, xDel, 0);
70214   }
70215 }
70216 SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
70217   int rc;
70218   Vdbe *p = (Vdbe *)pStmt;
70219   rc = vdbeUnbind(p, i);
70220   if( rc==SQLITE_OK ){
70221     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
70222     sqlite3_mutex_leave(p->db->mutex);
70223   }
70224   return rc;
70225 }
70226 SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
70227   return sqlite3_bind_int64(p, i, (i64)iValue);
70228 }
70229 SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
70230   int rc;
70231   Vdbe *p = (Vdbe *)pStmt;
70232   rc = vdbeUnbind(p, i);
70233   if( rc==SQLITE_OK ){
70234     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
70235     sqlite3_mutex_leave(p->db->mutex);
70236   }
70237   return rc;
70238 }
70239 SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
70240   int rc;
70241   Vdbe *p = (Vdbe*)pStmt;
70242   rc = vdbeUnbind(p, i);
70243   if( rc==SQLITE_OK ){
70244     sqlite3_mutex_leave(p->db->mutex);
70245   }
70246   return rc;
70247 }
70248 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(
70249   sqlite3_stmt *pStmt,
70250   int i,
70251   const char *zData,
70252   int nData,
70253   void (*xDel)(void*)
70254 ){
70255   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
70256 }
70257 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(
70258   sqlite3_stmt *pStmt,
70259   int i,
70260   const char *zData,
70261   sqlite3_uint64 nData,
70262   void (*xDel)(void*),
70263   unsigned char enc
70264 ){
70265   assert( xDel!=SQLITE_DYNAMIC );
70266   if( nData>0x7fffffff ){
70267     return invokeValueDestructor(zData, xDel, 0);
70268   }else{
70269     if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
70270     return bindText(pStmt, i, zData, (int)nData, xDel, enc);
70271   }
70272 }
70273 #ifndef SQLITE_OMIT_UTF16
70274 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(
70275   sqlite3_stmt *pStmt,
70276   int i,
70277   const void *zData,
70278   int nData,
70279   void (*xDel)(void*)
70280 ){
70281   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
70282 }
70283 #endif /* SQLITE_OMIT_UTF16 */
70284 SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
70285   int rc;
70286   switch( sqlite3_value_type((sqlite3_value*)pValue) ){
70287     case SQLITE_INTEGER: {
70288       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
70289       break;
70290     }
70291     case SQLITE_FLOAT: {
70292       rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
70293       break;
70294     }
70295     case SQLITE_BLOB: {
70296       if( pValue->flags & MEM_Zero ){
70297         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
70298       }else{
70299         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
70300       }
70301       break;
70302     }
70303     case SQLITE_TEXT: {
70304       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
70305                               pValue->enc);
70306       break;
70307     }
70308     default: {
70309       rc = sqlite3_bind_null(pStmt, i);
70310       break;
70311     }
70312   }
70313   return rc;
70314 }
70315 SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
70316   int rc;
70317   Vdbe *p = (Vdbe *)pStmt;
70318   rc = vdbeUnbind(p, i);
70319   if( rc==SQLITE_OK ){
70320     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
70321     sqlite3_mutex_leave(p->db->mutex);
70322   }
70323   return rc;
70324 }
70325 
70326 /*
70327 ** Return the number of wildcards that can be potentially bound to.
70328 ** This routine is added to support DBD::SQLite.
70329 */
70330 SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
70331   Vdbe *p = (Vdbe*)pStmt;
70332   return p ? p->nVar : 0;
70333 }
70334 
70335 /*
70336 ** Return the name of a wildcard parameter.  Return NULL if the index
70337 ** is out of range or if the wildcard is unnamed.
70338 **
70339 ** The result is always UTF-8.
70340 */
70341 SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
70342   Vdbe *p = (Vdbe*)pStmt;
70343   if( p==0 || i<1 || i>p->nzVar ){
70344     return 0;
70345   }
70346   return p->azVar[i-1];
70347 }
70348 
70349 /*
70350 ** Given a wildcard parameter name, return the index of the variable
70351 ** with that name.  If there is no variable with the given name,
70352 ** return 0.
70353 */
70354 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
70355   int i;
70356   if( p==0 ){
70357     return 0;
70358   }
70359   if( zName ){
70360     for(i=0; i<p->nzVar; i++){
70361       const char *z = p->azVar[i];
70362       if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
70363         return i+1;
70364       }
70365     }
70366   }
70367   return 0;
70368 }
70369 SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
70370   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
70371 }
70372 
70373 /*
70374 ** Transfer all bindings from the first statement over to the second.
70375 */
70376 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
70377   Vdbe *pFrom = (Vdbe*)pFromStmt;
70378   Vdbe *pTo = (Vdbe*)pToStmt;
70379   int i;
70380   assert( pTo->db==pFrom->db );
70381   assert( pTo->nVar==pFrom->nVar );
70382   sqlite3_mutex_enter(pTo->db->mutex);
70383   for(i=0; i<pFrom->nVar; i++){
70384     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
70385   }
70386   sqlite3_mutex_leave(pTo->db->mutex);
70387   return SQLITE_OK;
70388 }
70389 
70390 #ifndef SQLITE_OMIT_DEPRECATED
70391 /*
70392 ** Deprecated external interface.  Internal/core SQLite code
70393 ** should call sqlite3TransferBindings.
70394 **
70395 ** It is misuse to call this routine with statements from different
70396 ** database connections.  But as this is a deprecated interface, we
70397 ** will not bother to check for that condition.
70398 **
70399 ** If the two statements contain a different number of bindings, then
70400 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
70401 ** SQLITE_OK is returned.
70402 */
70403 SQLITE_API int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
70404   Vdbe *pFrom = (Vdbe*)pFromStmt;
70405   Vdbe *pTo = (Vdbe*)pToStmt;
70406   if( pFrom->nVar!=pTo->nVar ){
70407     return SQLITE_ERROR;
70408   }
70409   if( pTo->isPrepareV2 && pTo->expmask ){
70410     pTo->expired = 1;
70411   }
70412   if( pFrom->isPrepareV2 && pFrom->expmask ){
70413     pFrom->expired = 1;
70414   }
70415   return sqlite3TransferBindings(pFromStmt, pToStmt);
70416 }
70417 #endif
70418 
70419 /*
70420 ** Return the sqlite3* database handle to which the prepared statement given
70421 ** in the argument belongs.  This is the same database handle that was
70422 ** the first argument to the sqlite3_prepare() that was used to create
70423 ** the statement in the first place.
70424 */
70425 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt *pStmt){
70426   return pStmt ? ((Vdbe*)pStmt)->db : 0;
70427 }
70428 
70429 /*
70430 ** Return true if the prepared statement is guaranteed to not modify the
70431 ** database.
70432 */
70433 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
70434   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
70435 }
70436 
70437 /*
70438 ** Return true if the prepared statement is in need of being reset.
70439 */
70440 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt *pStmt){
70441   Vdbe *v = (Vdbe*)pStmt;
70442   return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
70443 }
70444 
70445 /*
70446 ** Return a pointer to the next prepared statement after pStmt associated
70447 ** with database connection pDb.  If pStmt is NULL, return the first
70448 ** prepared statement for the database connection.  Return NULL if there
70449 ** are no more.
70450 */
70451 SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
70452   sqlite3_stmt *pNext;
70453 #ifdef SQLITE_ENABLE_API_ARMOR
70454   if( !sqlite3SafetyCheckOk(pDb) ){
70455     (void)SQLITE_MISUSE_BKPT;
70456     return 0;
70457   }
70458 #endif
70459   sqlite3_mutex_enter(pDb->mutex);
70460   if( pStmt==0 ){
70461     pNext = (sqlite3_stmt*)pDb->pVdbe;
70462   }else{
70463     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
70464   }
70465   sqlite3_mutex_leave(pDb->mutex);
70466   return pNext;
70467 }
70468 
70469 /*
70470 ** Return the value of a status counter for a prepared statement
70471 */
70472 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
70473   Vdbe *pVdbe = (Vdbe*)pStmt;
70474   u32 v;
70475 #ifdef SQLITE_ENABLE_API_ARMOR
70476   if( !pStmt ){
70477     (void)SQLITE_MISUSE_BKPT;
70478     return 0;
70479   }
70480 #endif
70481   v = pVdbe->aCounter[op];
70482   if( resetFlag ) pVdbe->aCounter[op] = 0;
70483   return (int)v;
70484 }
70485 
70486 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
70487 /*
70488 ** Return status data for a single loop within query pStmt.
70489 */
70490 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
70491   sqlite3_stmt *pStmt,            /* Prepared statement being queried */
70492   int idx,                        /* Index of loop to report on */
70493   int iScanStatusOp,              /* Which metric to return */
70494   void *pOut                      /* OUT: Write the answer here */
70495 ){
70496   Vdbe *p = (Vdbe*)pStmt;
70497   ScanStatus *pScan;
70498   if( idx<0 || idx>=p->nScan ) return 1;
70499   pScan = &p->aScan[idx];
70500   switch( iScanStatusOp ){
70501     case SQLITE_SCANSTAT_NLOOP: {
70502       *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
70503       break;
70504     }
70505     case SQLITE_SCANSTAT_NVISIT: {
70506       *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
70507       break;
70508     }
70509     case SQLITE_SCANSTAT_EST: {
70510       double r = 1.0;
70511       LogEst x = pScan->nEst;
70512       while( x<100 ){
70513         x += 10;
70514         r *= 0.5;
70515       }
70516       *(double*)pOut = r*sqlite3LogEstToInt(x);
70517       break;
70518     }
70519     case SQLITE_SCANSTAT_NAME: {
70520       *(const char**)pOut = pScan->zName;
70521       break;
70522     }
70523     case SQLITE_SCANSTAT_EXPLAIN: {
70524       if( pScan->addrExplain ){
70525         *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
70526       }else{
70527         *(const char**)pOut = 0;
70528       }
70529       break;
70530     }
70531     case SQLITE_SCANSTAT_SELECTID: {
70532       if( pScan->addrExplain ){
70533         *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
70534       }else{
70535         *(int*)pOut = -1;
70536       }
70537       break;
70538     }
70539     default: {
70540       return 1;
70541     }
70542   }
70543   return 0;
70544 }
70545 
70546 /*
70547 ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
70548 */
70549 SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
70550   Vdbe *p = (Vdbe*)pStmt;
70551   memset(p->anExec, 0, p->nOp * sizeof(i64));
70552 }
70553 #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
70554 
70555 /************** End of vdbeapi.c *********************************************/
70556 /************** Begin file vdbetrace.c ***************************************/
70557 /*
70558 ** 2009 November 25
70559 **
70560 ** The author disclaims copyright to this source code.  In place of
70561 ** a legal notice, here is a blessing:
70562 **
70563 **    May you do good and not evil.
70564 **    May you find forgiveness for yourself and forgive others.
70565 **    May you share freely, never taking more than you give.
70566 **
70567 *************************************************************************
70568 **
70569 ** This file contains code used to insert the values of host parameters
70570 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
70571 **
70572 ** The Vdbe parse-tree explainer is also found here.
70573 */
70574 
70575 #ifndef SQLITE_OMIT_TRACE
70576 
70577 /*
70578 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
70579 ** bytes in this text up to but excluding the first character in
70580 ** a host parameter.  If the text contains no host parameters, return
70581 ** the total number of bytes in the text.
70582 */
70583 static int findNextHostParameter(const char *zSql, int *pnToken){
70584   int tokenType;
70585   int nTotal = 0;
70586   int n;
70587 
70588   *pnToken = 0;
70589   while( zSql[0] ){
70590     n = sqlite3GetToken((u8*)zSql, &tokenType);
70591     assert( n>0 && tokenType!=TK_ILLEGAL );
70592     if( tokenType==TK_VARIABLE ){
70593       *pnToken = n;
70594       break;
70595     }
70596     nTotal += n;
70597     zSql += n;
70598   }
70599   return nTotal;
70600 }
70601 
70602 /*
70603 ** This function returns a pointer to a nul-terminated string in memory
70604 ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
70605 ** string contains a copy of zRawSql but with host parameters expanded to
70606 ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
70607 ** then the returned string holds a copy of zRawSql with "-- " prepended
70608 ** to each line of text.
70609 **
70610 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
70611 ** then long strings and blobs are truncated to that many bytes.  This
70612 ** can be used to prevent unreasonably large trace strings when dealing
70613 ** with large (multi-megabyte) strings and blobs.
70614 **
70615 ** The calling function is responsible for making sure the memory returned
70616 ** is eventually freed.
70617 **
70618 ** ALGORITHM:  Scan the input string looking for host parameters in any of
70619 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
70620 ** string literals, quoted identifier names, and comments.  For text forms,
70621 ** the host parameter index is found by scanning the prepared
70622 ** statement for the corresponding OP_Variable opcode.  Once the host
70623 ** parameter index is known, locate the value in p->aVar[].  Then render
70624 ** the value as a literal in place of the host parameter name.
70625 */
70626 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
70627   Vdbe *p,                 /* The prepared statement being evaluated */
70628   const char *zRawSql      /* Raw text of the SQL statement */
70629 ){
70630   sqlite3 *db;             /* The database connection */
70631   int idx = 0;             /* Index of a host parameter */
70632   int nextIndex = 1;       /* Index of next ? host parameter */
70633   int n;                   /* Length of a token prefix */
70634   int nToken;              /* Length of the parameter token */
70635   int i;                   /* Loop counter */
70636   Mem *pVar;               /* Value of a host parameter */
70637   StrAccum out;            /* Accumulate the output here */
70638   char zBase[100];         /* Initial working space */
70639 
70640   db = p->db;
70641   sqlite3StrAccumInit(&out, db, zBase, sizeof(zBase),
70642                       db->aLimit[SQLITE_LIMIT_LENGTH]);
70643   if( db->nVdbeExec>1 ){
70644     while( *zRawSql ){
70645       const char *zStart = zRawSql;
70646       while( *(zRawSql++)!='\n' && *zRawSql );
70647       sqlite3StrAccumAppend(&out, "-- ", 3);
70648       assert( (zRawSql - zStart) > 0 );
70649       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
70650     }
70651   }else if( p->nVar==0 ){
70652     sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
70653   }else{
70654     while( zRawSql[0] ){
70655       n = findNextHostParameter(zRawSql, &nToken);
70656       assert( n>0 );
70657       sqlite3StrAccumAppend(&out, zRawSql, n);
70658       zRawSql += n;
70659       assert( zRawSql[0] || nToken==0 );
70660       if( nToken==0 ) break;
70661       if( zRawSql[0]=='?' ){
70662         if( nToken>1 ){
70663           assert( sqlite3Isdigit(zRawSql[1]) );
70664           sqlite3GetInt32(&zRawSql[1], &idx);
70665         }else{
70666           idx = nextIndex;
70667         }
70668       }else{
70669         assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
70670                 zRawSql[0]=='@' || zRawSql[0]=='#' );
70671         testcase( zRawSql[0]==':' );
70672         testcase( zRawSql[0]=='$' );
70673         testcase( zRawSql[0]=='@' );
70674         testcase( zRawSql[0]=='#' );
70675         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
70676         assert( idx>0 );
70677       }
70678       zRawSql += nToken;
70679       nextIndex = idx + 1;
70680       assert( idx>0 && idx<=p->nVar );
70681       pVar = &p->aVar[idx-1];
70682       if( pVar->flags & MEM_Null ){
70683         sqlite3StrAccumAppend(&out, "NULL", 4);
70684       }else if( pVar->flags & MEM_Int ){
70685         sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
70686       }else if( pVar->flags & MEM_Real ){
70687         sqlite3XPrintf(&out, 0, "%!.15g", pVar->u.r);
70688       }else if( pVar->flags & MEM_Str ){
70689         int nOut;  /* Number of bytes of the string text to include in output */
70690 #ifndef SQLITE_OMIT_UTF16
70691         u8 enc = ENC(db);
70692         Mem utf8;
70693         if( enc!=SQLITE_UTF8 ){
70694           memset(&utf8, 0, sizeof(utf8));
70695           utf8.db = db;
70696           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
70697           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
70698           pVar = &utf8;
70699         }
70700 #endif
70701         nOut = pVar->n;
70702 #ifdef SQLITE_TRACE_SIZE_LIMIT
70703         if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
70704           nOut = SQLITE_TRACE_SIZE_LIMIT;
70705           while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
70706         }
70707 #endif
70708         sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
70709 #ifdef SQLITE_TRACE_SIZE_LIMIT
70710         if( nOut<pVar->n ){
70711           sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
70712         }
70713 #endif
70714 #ifndef SQLITE_OMIT_UTF16
70715         if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
70716 #endif
70717       }else if( pVar->flags & MEM_Zero ){
70718         sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
70719       }else{
70720         int nOut;  /* Number of bytes of the blob to include in output */
70721         assert( pVar->flags & MEM_Blob );
70722         sqlite3StrAccumAppend(&out, "x'", 2);
70723         nOut = pVar->n;
70724 #ifdef SQLITE_TRACE_SIZE_LIMIT
70725         if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
70726 #endif
70727         for(i=0; i<nOut; i++){
70728           sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
70729         }
70730         sqlite3StrAccumAppend(&out, "'", 1);
70731 #ifdef SQLITE_TRACE_SIZE_LIMIT
70732         if( nOut<pVar->n ){
70733           sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
70734         }
70735 #endif
70736       }
70737     }
70738   }
70739   return sqlite3StrAccumFinish(&out);
70740 }
70741 
70742 #endif /* #ifndef SQLITE_OMIT_TRACE */
70743 
70744 /************** End of vdbetrace.c *******************************************/
70745 /************** Begin file vdbe.c ********************************************/
70746 /*
70747 ** 2001 September 15
70748 **
70749 ** The author disclaims copyright to this source code.  In place of
70750 ** a legal notice, here is a blessing:
70751 **
70752 **    May you do good and not evil.
70753 **    May you find forgiveness for yourself and forgive others.
70754 **    May you share freely, never taking more than you give.
70755 **
70756 *************************************************************************
70757 ** The code in this file implements the function that runs the
70758 ** bytecode of a prepared statement.
70759 **
70760 ** Various scripts scan this source file in order to generate HTML
70761 ** documentation, headers files, or other derived files.  The formatting
70762 ** of the code in this file is, therefore, important.  See other comments
70763 ** in this file for details.  If in doubt, do not deviate from existing
70764 ** commenting and indentation practices when changing or adding code.
70765 */
70766 
70767 /*
70768 ** Invoke this macro on memory cells just prior to changing the
70769 ** value of the cell.  This macro verifies that shallow copies are
70770 ** not misused.  A shallow copy of a string or blob just copies a
70771 ** pointer to the string or blob, not the content.  If the original
70772 ** is changed while the copy is still in use, the string or blob might
70773 ** be changed out from under the copy.  This macro verifies that nothing
70774 ** like that ever happens.
70775 */
70776 #ifdef SQLITE_DEBUG
70777 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
70778 #else
70779 # define memAboutToChange(P,M)
70780 #endif
70781 
70782 /*
70783 ** The following global variable is incremented every time a cursor
70784 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
70785 ** procedures use this information to make sure that indices are
70786 ** working correctly.  This variable has no function other than to
70787 ** help verify the correct operation of the library.
70788 */
70789 #ifdef SQLITE_TEST
70790 SQLITE_API int sqlite3_search_count = 0;
70791 #endif
70792 
70793 /*
70794 ** When this global variable is positive, it gets decremented once before
70795 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
70796 ** field of the sqlite3 structure is set in order to simulate an interrupt.
70797 **
70798 ** This facility is used for testing purposes only.  It does not function
70799 ** in an ordinary build.
70800 */
70801 #ifdef SQLITE_TEST
70802 SQLITE_API int sqlite3_interrupt_count = 0;
70803 #endif
70804 
70805 /*
70806 ** The next global variable is incremented each type the OP_Sort opcode
70807 ** is executed.  The test procedures use this information to make sure that
70808 ** sorting is occurring or not occurring at appropriate times.   This variable
70809 ** has no function other than to help verify the correct operation of the
70810 ** library.
70811 */
70812 #ifdef SQLITE_TEST
70813 SQLITE_API int sqlite3_sort_count = 0;
70814 #endif
70815 
70816 /*
70817 ** The next global variable records the size of the largest MEM_Blob
70818 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
70819 ** use this information to make sure that the zero-blob functionality
70820 ** is working correctly.   This variable has no function other than to
70821 ** help verify the correct operation of the library.
70822 */
70823 #ifdef SQLITE_TEST
70824 SQLITE_API int sqlite3_max_blobsize = 0;
70825 static void updateMaxBlobsize(Mem *p){
70826   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
70827     sqlite3_max_blobsize = p->n;
70828   }
70829 }
70830 #endif
70831 
70832 /*
70833 ** The next global variable is incremented each time the OP_Found opcode
70834 ** is executed. This is used to test whether or not the foreign key
70835 ** operation implemented using OP_FkIsZero is working. This variable
70836 ** has no function other than to help verify the correct operation of the
70837 ** library.
70838 */
70839 #ifdef SQLITE_TEST
70840 SQLITE_API int sqlite3_found_count = 0;
70841 #endif
70842 
70843 /*
70844 ** Test a register to see if it exceeds the current maximum blob size.
70845 ** If it does, record the new maximum blob size.
70846 */
70847 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
70848 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
70849 #else
70850 # define UPDATE_MAX_BLOBSIZE(P)
70851 #endif
70852 
70853 /*
70854 ** Invoke the VDBE coverage callback, if that callback is defined.  This
70855 ** feature is used for test suite validation only and does not appear an
70856 ** production builds.
70857 **
70858 ** M is an integer, 2 or 3, that indices how many different ways the
70859 ** branch can go.  It is usually 2.  "I" is the direction the branch
70860 ** goes.  0 means falls through.  1 means branch is taken.  2 means the
70861 ** second alternative branch is taken.
70862 **
70863 ** iSrcLine is the source code line (from the __LINE__ macro) that
70864 ** generated the VDBE instruction.  This instrumentation assumes that all
70865 ** source code is in a single file (the amalgamation).  Special values 1
70866 ** and 2 for the iSrcLine parameter mean that this particular branch is
70867 ** always taken or never taken, respectively.
70868 */
70869 #if !defined(SQLITE_VDBE_COVERAGE)
70870 # define VdbeBranchTaken(I,M)
70871 #else
70872 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
70873   static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
70874     if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
70875       M = iSrcLine;
70876       /* Assert the truth of VdbeCoverageAlwaysTaken() and
70877       ** VdbeCoverageNeverTaken() */
70878       assert( (M & I)==I );
70879     }else{
70880       if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
70881       sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
70882                                       iSrcLine,I,M);
70883     }
70884   }
70885 #endif
70886 
70887 /*
70888 ** Convert the given register into a string if it isn't one
70889 ** already. Return non-zero if a malloc() fails.
70890 */
70891 #define Stringify(P, enc) \
70892    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
70893      { goto no_mem; }
70894 
70895 /*
70896 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
70897 ** a pointer to a dynamically allocated string where some other entity
70898 ** is responsible for deallocating that string.  Because the register
70899 ** does not control the string, it might be deleted without the register
70900 ** knowing it.
70901 **
70902 ** This routine converts an ephemeral string into a dynamically allocated
70903 ** string that the register itself controls.  In other words, it
70904 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
70905 */
70906 #define Deephemeralize(P) \
70907    if( ((P)->flags&MEM_Ephem)!=0 \
70908        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
70909 
70910 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
70911 #define isSorter(x) ((x)->pSorter!=0)
70912 
70913 /*
70914 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
70915 ** if we run out of memory.
70916 */
70917 static VdbeCursor *allocateCursor(
70918   Vdbe *p,              /* The virtual machine */
70919   int iCur,             /* Index of the new VdbeCursor */
70920   int nField,           /* Number of fields in the table or index */
70921   int iDb,              /* Database the cursor belongs to, or -1 */
70922   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
70923 ){
70924   /* Find the memory cell that will be used to store the blob of memory
70925   ** required for this VdbeCursor structure. It is convenient to use a
70926   ** vdbe memory cell to manage the memory allocation required for a
70927   ** VdbeCursor structure for the following reasons:
70928   **
70929   **   * Sometimes cursor numbers are used for a couple of different
70930   **     purposes in a vdbe program. The different uses might require
70931   **     different sized allocations. Memory cells provide growable
70932   **     allocations.
70933   **
70934   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
70935   **     be freed lazily via the sqlite3_release_memory() API. This
70936   **     minimizes the number of malloc calls made by the system.
70937   **
70938   ** Memory cells for cursors are allocated at the top of the address
70939   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
70940   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
70941   */
70942   Mem *pMem = &p->aMem[p->nMem-iCur];
70943 
70944   int nByte;
70945   VdbeCursor *pCx = 0;
70946   nByte =
70947       ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
70948       (isBtreeCursor?sqlite3BtreeCursorSize():0);
70949 
70950   assert( iCur<p->nCursor );
70951   if( p->apCsr[iCur] ){
70952     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
70953     p->apCsr[iCur] = 0;
70954   }
70955   if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
70956     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
70957     memset(pCx, 0, sizeof(VdbeCursor));
70958     pCx->iDb = iDb;
70959     pCx->nField = nField;
70960     pCx->aOffset = &pCx->aType[nField];
70961     if( isBtreeCursor ){
70962       pCx->pCursor = (BtCursor*)
70963           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
70964       sqlite3BtreeCursorZero(pCx->pCursor);
70965     }
70966   }
70967   return pCx;
70968 }
70969 
70970 /*
70971 ** Try to convert a value into a numeric representation if we can
70972 ** do so without loss of information.  In other words, if the string
70973 ** looks like a number, convert it into a number.  If it does not
70974 ** look like a number, leave it alone.
70975 **
70976 ** If the bTryForInt flag is true, then extra effort is made to give
70977 ** an integer representation.  Strings that look like floating point
70978 ** values but which have no fractional component (example: '48.00')
70979 ** will have a MEM_Int representation when bTryForInt is true.
70980 **
70981 ** If bTryForInt is false, then if the input string contains a decimal
70982 ** point or exponential notation, the result is only MEM_Real, even
70983 ** if there is an exact integer representation of the quantity.
70984 */
70985 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
70986   double rValue;
70987   i64 iValue;
70988   u8 enc = pRec->enc;
70989   assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
70990   if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
70991   if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
70992     pRec->u.i = iValue;
70993     pRec->flags |= MEM_Int;
70994   }else{
70995     pRec->u.r = rValue;
70996     pRec->flags |= MEM_Real;
70997     if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
70998   }
70999 }
71000 
71001 /*
71002 ** Processing is determine by the affinity parameter:
71003 **
71004 ** SQLITE_AFF_INTEGER:
71005 ** SQLITE_AFF_REAL:
71006 ** SQLITE_AFF_NUMERIC:
71007 **    Try to convert pRec to an integer representation or a
71008 **    floating-point representation if an integer representation
71009 **    is not possible.  Note that the integer representation is
71010 **    always preferred, even if the affinity is REAL, because
71011 **    an integer representation is more space efficient on disk.
71012 **
71013 ** SQLITE_AFF_TEXT:
71014 **    Convert pRec to a text representation.
71015 **
71016 ** SQLITE_AFF_NONE:
71017 **    No-op.  pRec is unchanged.
71018 */
71019 static void applyAffinity(
71020   Mem *pRec,          /* The value to apply affinity to */
71021   char affinity,      /* The affinity to be applied */
71022   u8 enc              /* Use this text encoding */
71023 ){
71024   if( affinity>=SQLITE_AFF_NUMERIC ){
71025     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
71026              || affinity==SQLITE_AFF_NUMERIC );
71027     if( (pRec->flags & MEM_Int)==0 ){
71028       if( (pRec->flags & MEM_Real)==0 ){
71029         if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
71030       }else{
71031         sqlite3VdbeIntegerAffinity(pRec);
71032       }
71033     }
71034   }else if( affinity==SQLITE_AFF_TEXT ){
71035     /* Only attempt the conversion to TEXT if there is an integer or real
71036     ** representation (blob and NULL do not get converted) but no string
71037     ** representation.
71038     */
71039     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
71040       sqlite3VdbeMemStringify(pRec, enc, 1);
71041     }
71042     pRec->flags &= ~(MEM_Real|MEM_Int);
71043   }
71044 }
71045 
71046 /*
71047 ** Try to convert the type of a function argument or a result column
71048 ** into a numeric representation.  Use either INTEGER or REAL whichever
71049 ** is appropriate.  But only do the conversion if it is possible without
71050 ** loss of information and return the revised type of the argument.
71051 */
71052 SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value *pVal){
71053   int eType = sqlite3_value_type(pVal);
71054   if( eType==SQLITE_TEXT ){
71055     Mem *pMem = (Mem*)pVal;
71056     applyNumericAffinity(pMem, 0);
71057     eType = sqlite3_value_type(pVal);
71058   }
71059   return eType;
71060 }
71061 
71062 /*
71063 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
71064 ** not the internal Mem* type.
71065 */
71066 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
71067   sqlite3_value *pVal,
71068   u8 affinity,
71069   u8 enc
71070 ){
71071   applyAffinity((Mem *)pVal, affinity, enc);
71072 }
71073 
71074 /*
71075 ** pMem currently only holds a string type (or maybe a BLOB that we can
71076 ** interpret as a string if we want to).  Compute its corresponding
71077 ** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields
71078 ** accordingly.
71079 */
71080 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
71081   assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
71082   assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
71083   if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
71084     return 0;
71085   }
71086   if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
71087     return MEM_Int;
71088   }
71089   return MEM_Real;
71090 }
71091 
71092 /*
71093 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
71094 ** none.
71095 **
71096 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
71097 ** But it does set pMem->u.r and pMem->u.i appropriately.
71098 */
71099 static u16 numericType(Mem *pMem){
71100   if( pMem->flags & (MEM_Int|MEM_Real) ){
71101     return pMem->flags & (MEM_Int|MEM_Real);
71102   }
71103   if( pMem->flags & (MEM_Str|MEM_Blob) ){
71104     return computeNumericType(pMem);
71105   }
71106   return 0;
71107 }
71108 
71109 #ifdef SQLITE_DEBUG
71110 /*
71111 ** Write a nice string representation of the contents of cell pMem
71112 ** into buffer zBuf, length nBuf.
71113 */
71114 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
71115   char *zCsr = zBuf;
71116   int f = pMem->flags;
71117 
71118   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
71119 
71120   if( f&MEM_Blob ){
71121     int i;
71122     char c;
71123     if( f & MEM_Dyn ){
71124       c = 'z';
71125       assert( (f & (MEM_Static|MEM_Ephem))==0 );
71126     }else if( f & MEM_Static ){
71127       c = 't';
71128       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
71129     }else if( f & MEM_Ephem ){
71130       c = 'e';
71131       assert( (f & (MEM_Static|MEM_Dyn))==0 );
71132     }else{
71133       c = 's';
71134     }
71135 
71136     sqlite3_snprintf(100, zCsr, "%c", c);
71137     zCsr += sqlite3Strlen30(zCsr);
71138     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
71139     zCsr += sqlite3Strlen30(zCsr);
71140     for(i=0; i<16 && i<pMem->n; i++){
71141       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
71142       zCsr += sqlite3Strlen30(zCsr);
71143     }
71144     for(i=0; i<16 && i<pMem->n; i++){
71145       char z = pMem->z[i];
71146       if( z<32 || z>126 ) *zCsr++ = '.';
71147       else *zCsr++ = z;
71148     }
71149 
71150     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
71151     zCsr += sqlite3Strlen30(zCsr);
71152     if( f & MEM_Zero ){
71153       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
71154       zCsr += sqlite3Strlen30(zCsr);
71155     }
71156     *zCsr = '\0';
71157   }else if( f & MEM_Str ){
71158     int j, k;
71159     zBuf[0] = ' ';
71160     if( f & MEM_Dyn ){
71161       zBuf[1] = 'z';
71162       assert( (f & (MEM_Static|MEM_Ephem))==0 );
71163     }else if( f & MEM_Static ){
71164       zBuf[1] = 't';
71165       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
71166     }else if( f & MEM_Ephem ){
71167       zBuf[1] = 'e';
71168       assert( (f & (MEM_Static|MEM_Dyn))==0 );
71169     }else{
71170       zBuf[1] = 's';
71171     }
71172     k = 2;
71173     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
71174     k += sqlite3Strlen30(&zBuf[k]);
71175     zBuf[k++] = '[';
71176     for(j=0; j<15 && j<pMem->n; j++){
71177       u8 c = pMem->z[j];
71178       if( c>=0x20 && c<0x7f ){
71179         zBuf[k++] = c;
71180       }else{
71181         zBuf[k++] = '.';
71182       }
71183     }
71184     zBuf[k++] = ']';
71185     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
71186     k += sqlite3Strlen30(&zBuf[k]);
71187     zBuf[k++] = 0;
71188   }
71189 }
71190 #endif
71191 
71192 #ifdef SQLITE_DEBUG
71193 /*
71194 ** Print the value of a register for tracing purposes:
71195 */
71196 static void memTracePrint(Mem *p){
71197   if( p->flags & MEM_Undefined ){
71198     printf(" undefined");
71199   }else if( p->flags & MEM_Null ){
71200     printf(" NULL");
71201   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
71202     printf(" si:%lld", p->u.i);
71203   }else if( p->flags & MEM_Int ){
71204     printf(" i:%lld", p->u.i);
71205 #ifndef SQLITE_OMIT_FLOATING_POINT
71206   }else if( p->flags & MEM_Real ){
71207     printf(" r:%g", p->u.r);
71208 #endif
71209   }else if( p->flags & MEM_RowSet ){
71210     printf(" (rowset)");
71211   }else{
71212     char zBuf[200];
71213     sqlite3VdbeMemPrettyPrint(p, zBuf);
71214     printf(" %s", zBuf);
71215   }
71216 }
71217 static void registerTrace(int iReg, Mem *p){
71218   printf("REG[%d] = ", iReg);
71219   memTracePrint(p);
71220   printf("\n");
71221 }
71222 #endif
71223 
71224 #ifdef SQLITE_DEBUG
71225 #  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
71226 #else
71227 #  define REGISTER_TRACE(R,M)
71228 #endif
71229 
71230 
71231 #ifdef VDBE_PROFILE
71232 
71233 /*
71234 ** hwtime.h contains inline assembler code for implementing
71235 ** high-performance timing routines.
71236 */
71237 /************** Include hwtime.h in the middle of vdbe.c *********************/
71238 /************** Begin file hwtime.h ******************************************/
71239 /*
71240 ** 2008 May 27
71241 **
71242 ** The author disclaims copyright to this source code.  In place of
71243 ** a legal notice, here is a blessing:
71244 **
71245 **    May you do good and not evil.
71246 **    May you find forgiveness for yourself and forgive others.
71247 **    May you share freely, never taking more than you give.
71248 **
71249 ******************************************************************************
71250 **
71251 ** This file contains inline asm code for retrieving "high-performance"
71252 ** counters for x86 class CPUs.
71253 */
71254 #ifndef _HWTIME_H_
71255 #define _HWTIME_H_
71256 
71257 /*
71258 ** The following routine only works on pentium-class (or newer) processors.
71259 ** It uses the RDTSC opcode to read the cycle count value out of the
71260 ** processor and returns that value.  This can be used for high-res
71261 ** profiling.
71262 */
71263 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
71264       (defined(i386) || defined(__i386__) || defined(_M_IX86))
71265 
71266   #if defined(__GNUC__)
71267 
71268   __inline__ sqlite_uint64 sqlite3Hwtime(void){
71269      unsigned int lo, hi;
71270      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
71271      return (sqlite_uint64)hi << 32 | lo;
71272   }
71273 
71274   #elif defined(_MSC_VER)
71275 
71276   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
71277      __asm {
71278         rdtsc
71279         ret       ; return value at EDX:EAX
71280      }
71281   }
71282 
71283   #endif
71284 
71285 #elif (defined(__GNUC__) && defined(__x86_64__))
71286 
71287   __inline__ sqlite_uint64 sqlite3Hwtime(void){
71288       unsigned long val;
71289       __asm__ __volatile__ ("rdtsc" : "=A" (val));
71290       return val;
71291   }
71292 
71293 #elif (defined(__GNUC__) && defined(__ppc__))
71294 
71295   __inline__ sqlite_uint64 sqlite3Hwtime(void){
71296       unsigned long long retval;
71297       unsigned long junk;
71298       __asm__ __volatile__ ("\n\
71299           1:      mftbu   %1\n\
71300                   mftb    %L0\n\
71301                   mftbu   %0\n\
71302                   cmpw    %0,%1\n\
71303                   bne     1b"
71304                   : "=r" (retval), "=r" (junk));
71305       return retval;
71306   }
71307 
71308 #else
71309 
71310   #error Need implementation of sqlite3Hwtime() for your platform.
71311 
71312   /*
71313   ** To compile without implementing sqlite3Hwtime() for your platform,
71314   ** you can remove the above #error and use the following
71315   ** stub function.  You will lose timing support for many
71316   ** of the debugging and testing utilities, but it should at
71317   ** least compile and run.
71318   */
71319 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
71320 
71321 #endif
71322 
71323 #endif /* !defined(_HWTIME_H_) */
71324 
71325 /************** End of hwtime.h **********************************************/
71326 /************** Continuing where we left off in vdbe.c ***********************/
71327 
71328 #endif
71329 
71330 #ifndef NDEBUG
71331 /*
71332 ** This function is only called from within an assert() expression. It
71333 ** checks that the sqlite3.nTransaction variable is correctly set to
71334 ** the number of non-transaction savepoints currently in the
71335 ** linked list starting at sqlite3.pSavepoint.
71336 **
71337 ** Usage:
71338 **
71339 **     assert( checkSavepointCount(db) );
71340 */
71341 static int checkSavepointCount(sqlite3 *db){
71342   int n = 0;
71343   Savepoint *p;
71344   for(p=db->pSavepoint; p; p=p->pNext) n++;
71345   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
71346   return 1;
71347 }
71348 #endif
71349 
71350 /*
71351 ** Return the register of pOp->p2 after first preparing it to be
71352 ** overwritten with an integer value.
71353 */
71354 static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
71355   Mem *pOut;
71356   assert( pOp->p2>0 );
71357   assert( pOp->p2<=(p->nMem-p->nCursor) );
71358   pOut = &p->aMem[pOp->p2];
71359   memAboutToChange(p, pOut);
71360   if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
71361   pOut->flags = MEM_Int;
71362   return pOut;
71363 }
71364 
71365 
71366 /*
71367 ** Execute as much of a VDBE program as we can.
71368 ** This is the core of sqlite3_step().
71369 */
71370 SQLITE_PRIVATE int sqlite3VdbeExec(
71371   Vdbe *p                    /* The VDBE */
71372 ){
71373   Op *aOp = p->aOp;          /* Copy of p->aOp */
71374   Op *pOp = aOp;             /* Current operation */
71375 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
71376   Op *pOrigOp;               /* Value of pOp at the top of the loop */
71377 #endif
71378   int rc = SQLITE_OK;        /* Value to return */
71379   sqlite3 *db = p->db;       /* The database */
71380   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
71381   u8 encoding = ENC(db);     /* The database encoding */
71382   int iCompare = 0;          /* Result of last OP_Compare operation */
71383   unsigned nVmStep = 0;      /* Number of virtual machine steps */
71384 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
71385   unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
71386 #endif
71387   Mem *aMem = p->aMem;       /* Copy of p->aMem */
71388   Mem *pIn1 = 0;             /* 1st input operand */
71389   Mem *pIn2 = 0;             /* 2nd input operand */
71390   Mem *pIn3 = 0;             /* 3rd input operand */
71391   Mem *pOut = 0;             /* Output operand */
71392   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
71393   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
71394 #ifdef VDBE_PROFILE
71395   u64 start;                 /* CPU clock count at start of opcode */
71396 #endif
71397   /*** INSERT STACK UNION HERE ***/
71398 
71399   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
71400   sqlite3VdbeEnter(p);
71401   if( p->rc==SQLITE_NOMEM ){
71402     /* This happens if a malloc() inside a call to sqlite3_column_text() or
71403     ** sqlite3_column_text16() failed.  */
71404     goto no_mem;
71405   }
71406   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
71407   assert( p->bIsReader || p->readOnly!=0 );
71408   p->rc = SQLITE_OK;
71409   p->iCurrentTime = 0;
71410   assert( p->explain==0 );
71411   p->pResultSet = 0;
71412   db->busyHandler.nBusy = 0;
71413   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
71414   sqlite3VdbeIOTraceSql(p);
71415 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
71416   if( db->xProgress ){
71417     assert( 0 < db->nProgressOps );
71418     nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
71419     if( nProgressLimit==0 ){
71420       nProgressLimit = db->nProgressOps;
71421     }else{
71422       nProgressLimit %= (unsigned)db->nProgressOps;
71423     }
71424   }
71425 #endif
71426 #ifdef SQLITE_DEBUG
71427   sqlite3BeginBenignMalloc();
71428   if( p->pc==0
71429    && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
71430   ){
71431     int i;
71432     int once = 1;
71433     sqlite3VdbePrintSql(p);
71434     if( p->db->flags & SQLITE_VdbeListing ){
71435       printf("VDBE Program Listing:\n");
71436       for(i=0; i<p->nOp; i++){
71437         sqlite3VdbePrintOp(stdout, i, &aOp[i]);
71438       }
71439     }
71440     if( p->db->flags & SQLITE_VdbeEQP ){
71441       for(i=0; i<p->nOp; i++){
71442         if( aOp[i].opcode==OP_Explain ){
71443           if( once ) printf("VDBE Query Plan:\n");
71444           printf("%s\n", aOp[i].p4.z);
71445           once = 0;
71446         }
71447       }
71448     }
71449     if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
71450   }
71451   sqlite3EndBenignMalloc();
71452 #endif
71453   for(pOp=&aOp[p->pc]; rc==SQLITE_OK; pOp++){
71454     assert( pOp>=aOp && pOp<&aOp[p->nOp]);
71455     if( db->mallocFailed ) goto no_mem;
71456 #ifdef VDBE_PROFILE
71457     start = sqlite3Hwtime();
71458 #endif
71459     nVmStep++;
71460 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
71461     if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
71462 #endif
71463 
71464     /* Only allow tracing if SQLITE_DEBUG is defined.
71465     */
71466 #ifdef SQLITE_DEBUG
71467     if( db->flags & SQLITE_VdbeTrace ){
71468       sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
71469     }
71470 #endif
71471 
71472 
71473     /* Check to see if we need to simulate an interrupt.  This only happens
71474     ** if we have a special test build.
71475     */
71476 #ifdef SQLITE_TEST
71477     if( sqlite3_interrupt_count>0 ){
71478       sqlite3_interrupt_count--;
71479       if( sqlite3_interrupt_count==0 ){
71480         sqlite3_interrupt(db);
71481       }
71482     }
71483 #endif
71484 
71485     /* Sanity checking on other operands */
71486 #ifdef SQLITE_DEBUG
71487     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
71488     if( (pOp->opflags & OPFLG_IN1)!=0 ){
71489       assert( pOp->p1>0 );
71490       assert( pOp->p1<=(p->nMem-p->nCursor) );
71491       assert( memIsValid(&aMem[pOp->p1]) );
71492       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
71493       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
71494     }
71495     if( (pOp->opflags & OPFLG_IN2)!=0 ){
71496       assert( pOp->p2>0 );
71497       assert( pOp->p2<=(p->nMem-p->nCursor) );
71498       assert( memIsValid(&aMem[pOp->p2]) );
71499       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
71500       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
71501     }
71502     if( (pOp->opflags & OPFLG_IN3)!=0 ){
71503       assert( pOp->p3>0 );
71504       assert( pOp->p3<=(p->nMem-p->nCursor) );
71505       assert( memIsValid(&aMem[pOp->p3]) );
71506       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
71507       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
71508     }
71509     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
71510       assert( pOp->p2>0 );
71511       assert( pOp->p2<=(p->nMem-p->nCursor) );
71512       memAboutToChange(p, &aMem[pOp->p2]);
71513     }
71514     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
71515       assert( pOp->p3>0 );
71516       assert( pOp->p3<=(p->nMem-p->nCursor) );
71517       memAboutToChange(p, &aMem[pOp->p3]);
71518     }
71519 #endif
71520 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
71521     pOrigOp = pOp;
71522 #endif
71523 
71524     switch( pOp->opcode ){
71525 
71526 /*****************************************************************************
71527 ** What follows is a massive switch statement where each case implements a
71528 ** separate instruction in the virtual machine.  If we follow the usual
71529 ** indentation conventions, each case should be indented by 6 spaces.  But
71530 ** that is a lot of wasted space on the left margin.  So the code within
71531 ** the switch statement will break with convention and be flush-left. Another
71532 ** big comment (similar to this one) will mark the point in the code where
71533 ** we transition back to normal indentation.
71534 **
71535 ** The formatting of each case is important.  The makefile for SQLite
71536 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
71537 ** file looking for lines that begin with "case OP_".  The opcodes.h files
71538 ** will be filled with #defines that give unique integer values to each
71539 ** opcode and the opcodes.c file is filled with an array of strings where
71540 ** each string is the symbolic name for the corresponding opcode.  If the
71541 ** case statement is followed by a comment of the form "/# same as ... #/"
71542 ** that comment is used to determine the particular value of the opcode.
71543 **
71544 ** Other keywords in the comment that follows each case are used to
71545 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
71546 ** Keywords include: in1, in2, in3, out2, out3.  See
71547 ** the mkopcodeh.awk script for additional information.
71548 **
71549 ** Documentation about VDBE opcodes is generated by scanning this file
71550 ** for lines of that contain "Opcode:".  That line and all subsequent
71551 ** comment lines are used in the generation of the opcode.html documentation
71552 ** file.
71553 **
71554 ** SUMMARY:
71555 **
71556 **     Formatting is important to scripts that scan this file.
71557 **     Do not deviate from the formatting style currently in use.
71558 **
71559 *****************************************************************************/
71560 
71561 /* Opcode:  Goto * P2 * * *
71562 **
71563 ** An unconditional jump to address P2.
71564 ** The next instruction executed will be
71565 ** the one at index P2 from the beginning of
71566 ** the program.
71567 **
71568 ** The P1 parameter is not actually used by this opcode.  However, it
71569 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
71570 ** that this Goto is the bottom of a loop and that the lines from P2 down
71571 ** to the current line should be indented for EXPLAIN output.
71572 */
71573 case OP_Goto: {             /* jump */
71574 jump_to_p2_and_check_for_interrupt:
71575   pOp = &aOp[pOp->p2 - 1];
71576 
71577   /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
71578   ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
71579   ** completion.  Check to see if sqlite3_interrupt() has been called
71580   ** or if the progress callback needs to be invoked.
71581   **
71582   ** This code uses unstructured "goto" statements and does not look clean.
71583   ** But that is not due to sloppy coding habits. The code is written this
71584   ** way for performance, to avoid having to run the interrupt and progress
71585   ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
71586   ** faster according to "valgrind --tool=cachegrind" */
71587 check_for_interrupt:
71588   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
71589 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
71590   /* Call the progress callback if it is configured and the required number
71591   ** of VDBE ops have been executed (either since this invocation of
71592   ** sqlite3VdbeExec() or since last time the progress callback was called).
71593   ** If the progress callback returns non-zero, exit the virtual machine with
71594   ** a return code SQLITE_ABORT.
71595   */
71596   if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
71597     assert( db->nProgressOps!=0 );
71598     nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
71599     if( db->xProgress(db->pProgressArg) ){
71600       rc = SQLITE_INTERRUPT;
71601       goto vdbe_error_halt;
71602     }
71603   }
71604 #endif
71605 
71606   break;
71607 }
71608 
71609 /* Opcode:  Gosub P1 P2 * * *
71610 **
71611 ** Write the current address onto register P1
71612 ** and then jump to address P2.
71613 */
71614 case OP_Gosub: {            /* jump */
71615   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
71616   pIn1 = &aMem[pOp->p1];
71617   assert( VdbeMemDynamic(pIn1)==0 );
71618   memAboutToChange(p, pIn1);
71619   pIn1->flags = MEM_Int;
71620   pIn1->u.i = (int)(pOp-aOp);
71621   REGISTER_TRACE(pOp->p1, pIn1);
71622 
71623   /* Most jump operations do a goto to this spot in order to update
71624   ** the pOp pointer. */
71625 jump_to_p2:
71626   pOp = &aOp[pOp->p2 - 1];
71627   break;
71628 }
71629 
71630 /* Opcode:  Return P1 * * * *
71631 **
71632 ** Jump to the next instruction after the address in register P1.  After
71633 ** the jump, register P1 becomes undefined.
71634 */
71635 case OP_Return: {           /* in1 */
71636   pIn1 = &aMem[pOp->p1];
71637   assert( pIn1->flags==MEM_Int );
71638   pOp = &aOp[pIn1->u.i];
71639   pIn1->flags = MEM_Undefined;
71640   break;
71641 }
71642 
71643 /* Opcode: InitCoroutine P1 P2 P3 * *
71644 **
71645 ** Set up register P1 so that it will Yield to the coroutine
71646 ** located at address P3.
71647 **
71648 ** If P2!=0 then the coroutine implementation immediately follows
71649 ** this opcode.  So jump over the coroutine implementation to
71650 ** address P2.
71651 **
71652 ** See also: EndCoroutine
71653 */
71654 case OP_InitCoroutine: {     /* jump */
71655   assert( pOp->p1>0 &&  pOp->p1<=(p->nMem-p->nCursor) );
71656   assert( pOp->p2>=0 && pOp->p2<p->nOp );
71657   assert( pOp->p3>=0 && pOp->p3<p->nOp );
71658   pOut = &aMem[pOp->p1];
71659   assert( !VdbeMemDynamic(pOut) );
71660   pOut->u.i = pOp->p3 - 1;
71661   pOut->flags = MEM_Int;
71662   if( pOp->p2 ) goto jump_to_p2;
71663   break;
71664 }
71665 
71666 /* Opcode:  EndCoroutine P1 * * * *
71667 **
71668 ** The instruction at the address in register P1 is a Yield.
71669 ** Jump to the P2 parameter of that Yield.
71670 ** After the jump, register P1 becomes undefined.
71671 **
71672 ** See also: InitCoroutine
71673 */
71674 case OP_EndCoroutine: {           /* in1 */
71675   VdbeOp *pCaller;
71676   pIn1 = &aMem[pOp->p1];
71677   assert( pIn1->flags==MEM_Int );
71678   assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
71679   pCaller = &aOp[pIn1->u.i];
71680   assert( pCaller->opcode==OP_Yield );
71681   assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
71682   pOp = &aOp[pCaller->p2 - 1];
71683   pIn1->flags = MEM_Undefined;
71684   break;
71685 }
71686 
71687 /* Opcode:  Yield P1 P2 * * *
71688 **
71689 ** Swap the program counter with the value in register P1.  This
71690 ** has the effect of yielding to a coroutine.
71691 **
71692 ** If the coroutine that is launched by this instruction ends with
71693 ** Yield or Return then continue to the next instruction.  But if
71694 ** the coroutine launched by this instruction ends with
71695 ** EndCoroutine, then jump to P2 rather than continuing with the
71696 ** next instruction.
71697 **
71698 ** See also: InitCoroutine
71699 */
71700 case OP_Yield: {            /* in1, jump */
71701   int pcDest;
71702   pIn1 = &aMem[pOp->p1];
71703   assert( VdbeMemDynamic(pIn1)==0 );
71704   pIn1->flags = MEM_Int;
71705   pcDest = (int)pIn1->u.i;
71706   pIn1->u.i = (int)(pOp - aOp);
71707   REGISTER_TRACE(pOp->p1, pIn1);
71708   pOp = &aOp[pcDest];
71709   break;
71710 }
71711 
71712 /* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
71713 ** Synopsis:  if r[P3]=null halt
71714 **
71715 ** Check the value in register P3.  If it is NULL then Halt using
71716 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
71717 ** value in register P3 is not NULL, then this routine is a no-op.
71718 ** The P5 parameter should be 1.
71719 */
71720 case OP_HaltIfNull: {      /* in3 */
71721   pIn3 = &aMem[pOp->p3];
71722   if( (pIn3->flags & MEM_Null)==0 ) break;
71723   /* Fall through into OP_Halt */
71724 }
71725 
71726 /* Opcode:  Halt P1 P2 * P4 P5
71727 **
71728 ** Exit immediately.  All open cursors, etc are closed
71729 ** automatically.
71730 **
71731 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
71732 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
71733 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
71734 ** whether or not to rollback the current transaction.  Do not rollback
71735 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
71736 ** then back out all changes that have occurred during this execution of the
71737 ** VDBE, but do not rollback the transaction.
71738 **
71739 ** If P4 is not null then it is an error message string.
71740 **
71741 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
71742 **
71743 **    0:  (no change)
71744 **    1:  NOT NULL contraint failed: P4
71745 **    2:  UNIQUE constraint failed: P4
71746 **    3:  CHECK constraint failed: P4
71747 **    4:  FOREIGN KEY constraint failed: P4
71748 **
71749 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
71750 ** omitted.
71751 **
71752 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
71753 ** every program.  So a jump past the last instruction of the program
71754 ** is the same as executing Halt.
71755 */
71756 case OP_Halt: {
71757   const char *zType;
71758   const char *zLogFmt;
71759   VdbeFrame *pFrame;
71760   int pcx;
71761 
71762   pcx = (int)(pOp - aOp);
71763   if( pOp->p1==SQLITE_OK && p->pFrame ){
71764     /* Halt the sub-program. Return control to the parent frame. */
71765     pFrame = p->pFrame;
71766     p->pFrame = pFrame->pParent;
71767     p->nFrame--;
71768     sqlite3VdbeSetChanges(db, p->nChange);
71769     pcx = sqlite3VdbeFrameRestore(pFrame);
71770     lastRowid = db->lastRowid;
71771     if( pOp->p2==OE_Ignore ){
71772       /* Instruction pcx is the OP_Program that invoked the sub-program
71773       ** currently being halted. If the p2 instruction of this OP_Halt
71774       ** instruction is set to OE_Ignore, then the sub-program is throwing
71775       ** an IGNORE exception. In this case jump to the address specified
71776       ** as the p2 of the calling OP_Program.  */
71777       pcx = p->aOp[pcx].p2-1;
71778     }
71779     aOp = p->aOp;
71780     aMem = p->aMem;
71781     pOp = &aOp[pcx];
71782     break;
71783   }
71784   p->rc = pOp->p1;
71785   p->errorAction = (u8)pOp->p2;
71786   p->pc = pcx;
71787   if( p->rc ){
71788     if( pOp->p5 ){
71789       static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
71790                                              "FOREIGN KEY" };
71791       assert( pOp->p5>=1 && pOp->p5<=4 );
71792       testcase( pOp->p5==1 );
71793       testcase( pOp->p5==2 );
71794       testcase( pOp->p5==3 );
71795       testcase( pOp->p5==4 );
71796       zType = azType[pOp->p5-1];
71797     }else{
71798       zType = 0;
71799     }
71800     assert( zType!=0 || pOp->p4.z!=0 );
71801     zLogFmt = "abort at %d in [%s]: %s";
71802     if( zType && pOp->p4.z ){
71803       sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s",
71804                        zType, pOp->p4.z);
71805     }else if( pOp->p4.z ){
71806       sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
71807     }else{
71808       sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType);
71809     }
71810     sqlite3_log(pOp->p1, zLogFmt, pcx, p->zSql, p->zErrMsg);
71811   }
71812   rc = sqlite3VdbeHalt(p);
71813   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
71814   if( rc==SQLITE_BUSY ){
71815     p->rc = rc = SQLITE_BUSY;
71816   }else{
71817     assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
71818     assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
71819     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
71820   }
71821   goto vdbe_return;
71822 }
71823 
71824 /* Opcode: Integer P1 P2 * * *
71825 ** Synopsis: r[P2]=P1
71826 **
71827 ** The 32-bit integer value P1 is written into register P2.
71828 */
71829 case OP_Integer: {         /* out2 */
71830   pOut = out2Prerelease(p, pOp);
71831   pOut->u.i = pOp->p1;
71832   break;
71833 }
71834 
71835 /* Opcode: Int64 * P2 * P4 *
71836 ** Synopsis: r[P2]=P4
71837 **
71838 ** P4 is a pointer to a 64-bit integer value.
71839 ** Write that value into register P2.
71840 */
71841 case OP_Int64: {           /* out2 */
71842   pOut = out2Prerelease(p, pOp);
71843   assert( pOp->p4.pI64!=0 );
71844   pOut->u.i = *pOp->p4.pI64;
71845   break;
71846 }
71847 
71848 #ifndef SQLITE_OMIT_FLOATING_POINT
71849 /* Opcode: Real * P2 * P4 *
71850 ** Synopsis: r[P2]=P4
71851 **
71852 ** P4 is a pointer to a 64-bit floating point value.
71853 ** Write that value into register P2.
71854 */
71855 case OP_Real: {            /* same as TK_FLOAT, out2 */
71856   pOut = out2Prerelease(p, pOp);
71857   pOut->flags = MEM_Real;
71858   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
71859   pOut->u.r = *pOp->p4.pReal;
71860   break;
71861 }
71862 #endif
71863 
71864 /* Opcode: String8 * P2 * P4 *
71865 ** Synopsis: r[P2]='P4'
71866 **
71867 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
71868 ** into a String opcode before it is executed for the first time.  During
71869 ** this transformation, the length of string P4 is computed and stored
71870 ** as the P1 parameter.
71871 */
71872 case OP_String8: {         /* same as TK_STRING, out2 */
71873   assert( pOp->p4.z!=0 );
71874   pOut = out2Prerelease(p, pOp);
71875   pOp->opcode = OP_String;
71876   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
71877 
71878 #ifndef SQLITE_OMIT_UTF16
71879   if( encoding!=SQLITE_UTF8 ){
71880     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
71881     if( rc==SQLITE_TOOBIG ) goto too_big;
71882     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
71883     assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
71884     assert( VdbeMemDynamic(pOut)==0 );
71885     pOut->szMalloc = 0;
71886     pOut->flags |= MEM_Static;
71887     if( pOp->p4type==P4_DYNAMIC ){
71888       sqlite3DbFree(db, pOp->p4.z);
71889     }
71890     pOp->p4type = P4_DYNAMIC;
71891     pOp->p4.z = pOut->z;
71892     pOp->p1 = pOut->n;
71893   }
71894 #endif
71895   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71896     goto too_big;
71897   }
71898   /* Fall through to the next case, OP_String */
71899 }
71900 
71901 /* Opcode: String P1 P2 P3 P4 P5
71902 ** Synopsis: r[P2]='P4' (len=P1)
71903 **
71904 ** The string value P4 of length P1 (bytes) is stored in register P2.
71905 **
71906 ** If P5!=0 and the content of register P3 is greater than zero, then
71907 ** the datatype of the register P2 is converted to BLOB.  The content is
71908 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
71909 ** of a string, as if it had been CAST.
71910 */
71911 case OP_String: {          /* out2 */
71912   assert( pOp->p4.z!=0 );
71913   pOut = out2Prerelease(p, pOp);
71914   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
71915   pOut->z = pOp->p4.z;
71916   pOut->n = pOp->p1;
71917   pOut->enc = encoding;
71918   UPDATE_MAX_BLOBSIZE(pOut);
71919   if( pOp->p5 ){
71920     assert( pOp->p3>0 );
71921     assert( pOp->p3<=(p->nMem-p->nCursor) );
71922     pIn3 = &aMem[pOp->p3];
71923     assert( pIn3->flags & MEM_Int );
71924     if( pIn3->u.i ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
71925   }
71926   break;
71927 }
71928 
71929 /* Opcode: Null P1 P2 P3 * *
71930 ** Synopsis:  r[P2..P3]=NULL
71931 **
71932 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
71933 ** NULL into register P3 and every register in between P2 and P3.  If P3
71934 ** is less than P2 (typically P3 is zero) then only register P2 is
71935 ** set to NULL.
71936 **
71937 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
71938 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
71939 ** OP_Ne or OP_Eq.
71940 */
71941 case OP_Null: {           /* out2 */
71942   int cnt;
71943   u16 nullFlag;
71944   pOut = out2Prerelease(p, pOp);
71945   cnt = pOp->p3-pOp->p2;
71946   assert( pOp->p3<=(p->nMem-p->nCursor) );
71947   pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
71948   while( cnt>0 ){
71949     pOut++;
71950     memAboutToChange(p, pOut);
71951     sqlite3VdbeMemSetNull(pOut);
71952     pOut->flags = nullFlag;
71953     cnt--;
71954   }
71955   break;
71956 }
71957 
71958 /* Opcode: SoftNull P1 * * * *
71959 ** Synopsis:  r[P1]=NULL
71960 **
71961 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
71962 ** instruction, but do not free any string or blob memory associated with
71963 ** the register, so that if the value was a string or blob that was
71964 ** previously copied using OP_SCopy, the copies will continue to be valid.
71965 */
71966 case OP_SoftNull: {
71967   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
71968   pOut = &aMem[pOp->p1];
71969   pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
71970   break;
71971 }
71972 
71973 /* Opcode: Blob P1 P2 * P4 *
71974 ** Synopsis: r[P2]=P4 (len=P1)
71975 **
71976 ** P4 points to a blob of data P1 bytes long.  Store this
71977 ** blob in register P2.
71978 */
71979 case OP_Blob: {                /* out2 */
71980   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
71981   pOut = out2Prerelease(p, pOp);
71982   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
71983   pOut->enc = encoding;
71984   UPDATE_MAX_BLOBSIZE(pOut);
71985   break;
71986 }
71987 
71988 /* Opcode: Variable P1 P2 * P4 *
71989 ** Synopsis: r[P2]=parameter(P1,P4)
71990 **
71991 ** Transfer the values of bound parameter P1 into register P2
71992 **
71993 ** If the parameter is named, then its name appears in P4.
71994 ** The P4 value is used by sqlite3_bind_parameter_name().
71995 */
71996 case OP_Variable: {            /* out2 */
71997   Mem *pVar;       /* Value being transferred */
71998 
71999   assert( pOp->p1>0 && pOp->p1<=p->nVar );
72000   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
72001   pVar = &p->aVar[pOp->p1 - 1];
72002   if( sqlite3VdbeMemTooBig(pVar) ){
72003     goto too_big;
72004   }
72005   pOut = out2Prerelease(p, pOp);
72006   sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
72007   UPDATE_MAX_BLOBSIZE(pOut);
72008   break;
72009 }
72010 
72011 /* Opcode: Move P1 P2 P3 * *
72012 ** Synopsis:  r[P2@P3]=r[P1@P3]
72013 **
72014 ** Move the P3 values in register P1..P1+P3-1 over into
72015 ** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
72016 ** left holding a NULL.  It is an error for register ranges
72017 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
72018 ** for P3 to be less than 1.
72019 */
72020 case OP_Move: {
72021   int n;           /* Number of registers left to copy */
72022   int p1;          /* Register to copy from */
72023   int p2;          /* Register to copy to */
72024 
72025   n = pOp->p3;
72026   p1 = pOp->p1;
72027   p2 = pOp->p2;
72028   assert( n>0 && p1>0 && p2>0 );
72029   assert( p1+n<=p2 || p2+n<=p1 );
72030 
72031   pIn1 = &aMem[p1];
72032   pOut = &aMem[p2];
72033   do{
72034     assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
72035     assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
72036     assert( memIsValid(pIn1) );
72037     memAboutToChange(p, pOut);
72038     sqlite3VdbeMemMove(pOut, pIn1);
72039 #ifdef SQLITE_DEBUG
72040     if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
72041       pOut->pScopyFrom += pOp->p2 - p1;
72042     }
72043 #endif
72044     Deephemeralize(pOut);
72045     REGISTER_TRACE(p2++, pOut);
72046     pIn1++;
72047     pOut++;
72048   }while( --n );
72049   break;
72050 }
72051 
72052 /* Opcode: Copy P1 P2 P3 * *
72053 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
72054 **
72055 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
72056 **
72057 ** This instruction makes a deep copy of the value.  A duplicate
72058 ** is made of any string or blob constant.  See also OP_SCopy.
72059 */
72060 case OP_Copy: {
72061   int n;
72062 
72063   n = pOp->p3;
72064   pIn1 = &aMem[pOp->p1];
72065   pOut = &aMem[pOp->p2];
72066   assert( pOut!=pIn1 );
72067   while( 1 ){
72068     sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
72069     Deephemeralize(pOut);
72070 #ifdef SQLITE_DEBUG
72071     pOut->pScopyFrom = 0;
72072 #endif
72073     REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
72074     if( (n--)==0 ) break;
72075     pOut++;
72076     pIn1++;
72077   }
72078   break;
72079 }
72080 
72081 /* Opcode: SCopy P1 P2 * * *
72082 ** Synopsis: r[P2]=r[P1]
72083 **
72084 ** Make a shallow copy of register P1 into register P2.
72085 **
72086 ** This instruction makes a shallow copy of the value.  If the value
72087 ** is a string or blob, then the copy is only a pointer to the
72088 ** original and hence if the original changes so will the copy.
72089 ** Worse, if the original is deallocated, the copy becomes invalid.
72090 ** Thus the program must guarantee that the original will not change
72091 ** during the lifetime of the copy.  Use OP_Copy to make a complete
72092 ** copy.
72093 */
72094 case OP_SCopy: {            /* out2 */
72095   pIn1 = &aMem[pOp->p1];
72096   pOut = &aMem[pOp->p2];
72097   assert( pOut!=pIn1 );
72098   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
72099 #ifdef SQLITE_DEBUG
72100   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
72101 #endif
72102   break;
72103 }
72104 
72105 /* Opcode: ResultRow P1 P2 * * *
72106 ** Synopsis:  output=r[P1@P2]
72107 **
72108 ** The registers P1 through P1+P2-1 contain a single row of
72109 ** results. This opcode causes the sqlite3_step() call to terminate
72110 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
72111 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
72112 ** the result row.
72113 */
72114 case OP_ResultRow: {
72115   Mem *pMem;
72116   int i;
72117   assert( p->nResColumn==pOp->p2 );
72118   assert( pOp->p1>0 );
72119   assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
72120 
72121 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
72122   /* Run the progress counter just before returning.
72123   */
72124   if( db->xProgress!=0
72125    && nVmStep>=nProgressLimit
72126    && db->xProgress(db->pProgressArg)!=0
72127   ){
72128     rc = SQLITE_INTERRUPT;
72129     goto vdbe_error_halt;
72130   }
72131 #endif
72132 
72133   /* If this statement has violated immediate foreign key constraints, do
72134   ** not return the number of rows modified. And do not RELEASE the statement
72135   ** transaction. It needs to be rolled back.  */
72136   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
72137     assert( db->flags&SQLITE_CountRows );
72138     assert( p->usesStmtJournal );
72139     break;
72140   }
72141 
72142   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
72143   ** DML statements invoke this opcode to return the number of rows
72144   ** modified to the user. This is the only way that a VM that
72145   ** opens a statement transaction may invoke this opcode.
72146   **
72147   ** In case this is such a statement, close any statement transaction
72148   ** opened by this VM before returning control to the user. This is to
72149   ** ensure that statement-transactions are always nested, not overlapping.
72150   ** If the open statement-transaction is not closed here, then the user
72151   ** may step another VM that opens its own statement transaction. This
72152   ** may lead to overlapping statement transactions.
72153   **
72154   ** The statement transaction is never a top-level transaction.  Hence
72155   ** the RELEASE call below can never fail.
72156   */
72157   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
72158   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
72159   if( NEVER(rc!=SQLITE_OK) ){
72160     break;
72161   }
72162 
72163   /* Invalidate all ephemeral cursor row caches */
72164   p->cacheCtr = (p->cacheCtr + 2)|1;
72165 
72166   /* Make sure the results of the current row are \000 terminated
72167   ** and have an assigned type.  The results are de-ephemeralized as
72168   ** a side effect.
72169   */
72170   pMem = p->pResultSet = &aMem[pOp->p1];
72171   for(i=0; i<pOp->p2; i++){
72172     assert( memIsValid(&pMem[i]) );
72173     Deephemeralize(&pMem[i]);
72174     assert( (pMem[i].flags & MEM_Ephem)==0
72175             || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
72176     sqlite3VdbeMemNulTerminate(&pMem[i]);
72177     REGISTER_TRACE(pOp->p1+i, &pMem[i]);
72178   }
72179   if( db->mallocFailed ) goto no_mem;
72180 
72181   /* Return SQLITE_ROW
72182   */
72183   p->pc = (int)(pOp - aOp) + 1;
72184   rc = SQLITE_ROW;
72185   goto vdbe_return;
72186 }
72187 
72188 /* Opcode: Concat P1 P2 P3 * *
72189 ** Synopsis: r[P3]=r[P2]+r[P1]
72190 **
72191 ** Add the text in register P1 onto the end of the text in
72192 ** register P2 and store the result in register P3.
72193 ** If either the P1 or P2 text are NULL then store NULL in P3.
72194 **
72195 **   P3 = P2 || P1
72196 **
72197 ** It is illegal for P1 and P3 to be the same register. Sometimes,
72198 ** if P3 is the same register as P2, the implementation is able
72199 ** to avoid a memcpy().
72200 */
72201 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
72202   i64 nByte;
72203 
72204   pIn1 = &aMem[pOp->p1];
72205   pIn2 = &aMem[pOp->p2];
72206   pOut = &aMem[pOp->p3];
72207   assert( pIn1!=pOut );
72208   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
72209     sqlite3VdbeMemSetNull(pOut);
72210     break;
72211   }
72212   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
72213   Stringify(pIn1, encoding);
72214   Stringify(pIn2, encoding);
72215   nByte = pIn1->n + pIn2->n;
72216   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
72217     goto too_big;
72218   }
72219   if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
72220     goto no_mem;
72221   }
72222   MemSetTypeFlag(pOut, MEM_Str);
72223   if( pOut!=pIn2 ){
72224     memcpy(pOut->z, pIn2->z, pIn2->n);
72225   }
72226   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
72227   pOut->z[nByte]=0;
72228   pOut->z[nByte+1] = 0;
72229   pOut->flags |= MEM_Term;
72230   pOut->n = (int)nByte;
72231   pOut->enc = encoding;
72232   UPDATE_MAX_BLOBSIZE(pOut);
72233   break;
72234 }
72235 
72236 /* Opcode: Add P1 P2 P3 * *
72237 ** Synopsis:  r[P3]=r[P1]+r[P2]
72238 **
72239 ** Add the value in register P1 to the value in register P2
72240 ** and store the result in register P3.
72241 ** If either input is NULL, the result is NULL.
72242 */
72243 /* Opcode: Multiply P1 P2 P3 * *
72244 ** Synopsis:  r[P3]=r[P1]*r[P2]
72245 **
72246 **
72247 ** Multiply the value in register P1 by the value in register P2
72248 ** and store the result in register P3.
72249 ** If either input is NULL, the result is NULL.
72250 */
72251 /* Opcode: Subtract P1 P2 P3 * *
72252 ** Synopsis:  r[P3]=r[P2]-r[P1]
72253 **
72254 ** Subtract the value in register P1 from the value in register P2
72255 ** and store the result in register P3.
72256 ** If either input is NULL, the result is NULL.
72257 */
72258 /* Opcode: Divide P1 P2 P3 * *
72259 ** Synopsis:  r[P3]=r[P2]/r[P1]
72260 **
72261 ** Divide the value in register P1 by the value in register P2
72262 ** and store the result in register P3 (P3=P2/P1). If the value in
72263 ** register P1 is zero, then the result is NULL. If either input is
72264 ** NULL, the result is NULL.
72265 */
72266 /* Opcode: Remainder P1 P2 P3 * *
72267 ** Synopsis:  r[P3]=r[P2]%r[P1]
72268 **
72269 ** Compute the remainder after integer register P2 is divided by
72270 ** register P1 and store the result in register P3.
72271 ** If the value in register P1 is zero the result is NULL.
72272 ** If either operand is NULL, the result is NULL.
72273 */
72274 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
72275 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
72276 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
72277 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
72278 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
72279   char bIntint;   /* Started out as two integer operands */
72280   u16 flags;      /* Combined MEM_* flags from both inputs */
72281   u16 type1;      /* Numeric type of left operand */
72282   u16 type2;      /* Numeric type of right operand */
72283   i64 iA;         /* Integer value of left operand */
72284   i64 iB;         /* Integer value of right operand */
72285   double rA;      /* Real value of left operand */
72286   double rB;      /* Real value of right operand */
72287 
72288   pIn1 = &aMem[pOp->p1];
72289   type1 = numericType(pIn1);
72290   pIn2 = &aMem[pOp->p2];
72291   type2 = numericType(pIn2);
72292   pOut = &aMem[pOp->p3];
72293   flags = pIn1->flags | pIn2->flags;
72294   if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
72295   if( (type1 & type2 & MEM_Int)!=0 ){
72296     iA = pIn1->u.i;
72297     iB = pIn2->u.i;
72298     bIntint = 1;
72299     switch( pOp->opcode ){
72300       case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
72301       case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
72302       case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
72303       case OP_Divide: {
72304         if( iA==0 ) goto arithmetic_result_is_null;
72305         if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
72306         iB /= iA;
72307         break;
72308       }
72309       default: {
72310         if( iA==0 ) goto arithmetic_result_is_null;
72311         if( iA==-1 ) iA = 1;
72312         iB %= iA;
72313         break;
72314       }
72315     }
72316     pOut->u.i = iB;
72317     MemSetTypeFlag(pOut, MEM_Int);
72318   }else{
72319     bIntint = 0;
72320 fp_math:
72321     rA = sqlite3VdbeRealValue(pIn1);
72322     rB = sqlite3VdbeRealValue(pIn2);
72323     switch( pOp->opcode ){
72324       case OP_Add:         rB += rA;       break;
72325       case OP_Subtract:    rB -= rA;       break;
72326       case OP_Multiply:    rB *= rA;       break;
72327       case OP_Divide: {
72328         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
72329         if( rA==(double)0 ) goto arithmetic_result_is_null;
72330         rB /= rA;
72331         break;
72332       }
72333       default: {
72334         iA = (i64)rA;
72335         iB = (i64)rB;
72336         if( iA==0 ) goto arithmetic_result_is_null;
72337         if( iA==-1 ) iA = 1;
72338         rB = (double)(iB % iA);
72339         break;
72340       }
72341     }
72342 #ifdef SQLITE_OMIT_FLOATING_POINT
72343     pOut->u.i = rB;
72344     MemSetTypeFlag(pOut, MEM_Int);
72345 #else
72346     if( sqlite3IsNaN(rB) ){
72347       goto arithmetic_result_is_null;
72348     }
72349     pOut->u.r = rB;
72350     MemSetTypeFlag(pOut, MEM_Real);
72351     if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
72352       sqlite3VdbeIntegerAffinity(pOut);
72353     }
72354 #endif
72355   }
72356   break;
72357 
72358 arithmetic_result_is_null:
72359   sqlite3VdbeMemSetNull(pOut);
72360   break;
72361 }
72362 
72363 /* Opcode: CollSeq P1 * * P4
72364 **
72365 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
72366 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
72367 ** be returned. This is used by the built-in min(), max() and nullif()
72368 ** functions.
72369 **
72370 ** If P1 is not zero, then it is a register that a subsequent min() or
72371 ** max() aggregate will set to 1 if the current row is not the minimum or
72372 ** maximum.  The P1 register is initialized to 0 by this instruction.
72373 **
72374 ** The interface used by the implementation of the aforementioned functions
72375 ** to retrieve the collation sequence set by this opcode is not available
72376 ** publicly.  Only built-in functions have access to this feature.
72377 */
72378 case OP_CollSeq: {
72379   assert( pOp->p4type==P4_COLLSEQ );
72380   if( pOp->p1 ){
72381     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
72382   }
72383   break;
72384 }
72385 
72386 /* Opcode: Function P1 P2 P3 P4 P5
72387 ** Synopsis: r[P3]=func(r[P2@P5])
72388 **
72389 ** Invoke a user function (P4 is a pointer to a Function structure that
72390 ** defines the function) with P5 arguments taken from register P2 and
72391 ** successors.  The result of the function is stored in register P3.
72392 ** Register P3 must not be one of the function inputs.
72393 **
72394 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
72395 ** function was determined to be constant at compile time. If the first
72396 ** argument was constant then bit 0 of P1 is set. This is used to determine
72397 ** whether meta data associated with a user function argument using the
72398 ** sqlite3_set_auxdata() API may be safely retained until the next
72399 ** invocation of this opcode.
72400 **
72401 ** See also: AggStep and AggFinal
72402 */
72403 case OP_Function: {
72404   int i;
72405   Mem *pArg;
72406   sqlite3_context ctx;
72407   sqlite3_value **apVal;
72408   int n;
72409 
72410   n = pOp->p5;
72411   apVal = p->apArg;
72412   assert( apVal || n==0 );
72413   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
72414   ctx.pOut = &aMem[pOp->p3];
72415   memAboutToChange(p, ctx.pOut);
72416 
72417   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
72418   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
72419   pArg = &aMem[pOp->p2];
72420   for(i=0; i<n; i++, pArg++){
72421     assert( memIsValid(pArg) );
72422     apVal[i] = pArg;
72423     Deephemeralize(pArg);
72424     REGISTER_TRACE(pOp->p2+i, pArg);
72425   }
72426 
72427   assert( pOp->p4type==P4_FUNCDEF );
72428   ctx.pFunc = pOp->p4.pFunc;
72429   ctx.iOp = (int)(pOp - aOp);
72430   ctx.pVdbe = p;
72431   MemSetTypeFlag(ctx.pOut, MEM_Null);
72432   ctx.fErrorOrAux = 0;
72433   db->lastRowid = lastRowid;
72434   (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
72435   lastRowid = db->lastRowid;  /* Remember rowid changes made by xFunc */
72436 
72437   /* If the function returned an error, throw an exception */
72438   if( ctx.fErrorOrAux ){
72439     if( ctx.isError ){
72440       sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(ctx.pOut));
72441       rc = ctx.isError;
72442     }
72443     sqlite3VdbeDeleteAuxData(p, (int)(pOp - aOp), pOp->p1);
72444   }
72445 
72446   /* Copy the result of the function into register P3 */
72447   sqlite3VdbeChangeEncoding(ctx.pOut, encoding);
72448   if( sqlite3VdbeMemTooBig(ctx.pOut) ){
72449     goto too_big;
72450   }
72451 
72452   REGISTER_TRACE(pOp->p3, ctx.pOut);
72453   UPDATE_MAX_BLOBSIZE(ctx.pOut);
72454   break;
72455 }
72456 
72457 /* Opcode: BitAnd P1 P2 P3 * *
72458 ** Synopsis:  r[P3]=r[P1]&r[P2]
72459 **
72460 ** Take the bit-wise AND of the values in register P1 and P2 and
72461 ** store the result in register P3.
72462 ** If either input is NULL, the result is NULL.
72463 */
72464 /* Opcode: BitOr P1 P2 P3 * *
72465 ** Synopsis:  r[P3]=r[P1]|r[P2]
72466 **
72467 ** Take the bit-wise OR of the values in register P1 and P2 and
72468 ** store the result in register P3.
72469 ** If either input is NULL, the result is NULL.
72470 */
72471 /* Opcode: ShiftLeft P1 P2 P3 * *
72472 ** Synopsis:  r[P3]=r[P2]<<r[P1]
72473 **
72474 ** Shift the integer value in register P2 to the left by the
72475 ** number of bits specified by the integer in register P1.
72476 ** Store the result in register P3.
72477 ** If either input is NULL, the result is NULL.
72478 */
72479 /* Opcode: ShiftRight P1 P2 P3 * *
72480 ** Synopsis:  r[P3]=r[P2]>>r[P1]
72481 **
72482 ** Shift the integer value in register P2 to the right by the
72483 ** number of bits specified by the integer in register P1.
72484 ** Store the result in register P3.
72485 ** If either input is NULL, the result is NULL.
72486 */
72487 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
72488 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
72489 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
72490 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
72491   i64 iA;
72492   u64 uA;
72493   i64 iB;
72494   u8 op;
72495 
72496   pIn1 = &aMem[pOp->p1];
72497   pIn2 = &aMem[pOp->p2];
72498   pOut = &aMem[pOp->p3];
72499   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
72500     sqlite3VdbeMemSetNull(pOut);
72501     break;
72502   }
72503   iA = sqlite3VdbeIntValue(pIn2);
72504   iB = sqlite3VdbeIntValue(pIn1);
72505   op = pOp->opcode;
72506   if( op==OP_BitAnd ){
72507     iA &= iB;
72508   }else if( op==OP_BitOr ){
72509     iA |= iB;
72510   }else if( iB!=0 ){
72511     assert( op==OP_ShiftRight || op==OP_ShiftLeft );
72512 
72513     /* If shifting by a negative amount, shift in the other direction */
72514     if( iB<0 ){
72515       assert( OP_ShiftRight==OP_ShiftLeft+1 );
72516       op = 2*OP_ShiftLeft + 1 - op;
72517       iB = iB>(-64) ? -iB : 64;
72518     }
72519 
72520     if( iB>=64 ){
72521       iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
72522     }else{
72523       memcpy(&uA, &iA, sizeof(uA));
72524       if( op==OP_ShiftLeft ){
72525         uA <<= iB;
72526       }else{
72527         uA >>= iB;
72528         /* Sign-extend on a right shift of a negative number */
72529         if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
72530       }
72531       memcpy(&iA, &uA, sizeof(iA));
72532     }
72533   }
72534   pOut->u.i = iA;
72535   MemSetTypeFlag(pOut, MEM_Int);
72536   break;
72537 }
72538 
72539 /* Opcode: AddImm  P1 P2 * * *
72540 ** Synopsis:  r[P1]=r[P1]+P2
72541 **
72542 ** Add the constant P2 to the value in register P1.
72543 ** The result is always an integer.
72544 **
72545 ** To force any register to be an integer, just add 0.
72546 */
72547 case OP_AddImm: {            /* in1 */
72548   pIn1 = &aMem[pOp->p1];
72549   memAboutToChange(p, pIn1);
72550   sqlite3VdbeMemIntegerify(pIn1);
72551   pIn1->u.i += pOp->p2;
72552   break;
72553 }
72554 
72555 /* Opcode: MustBeInt P1 P2 * * *
72556 **
72557 ** Force the value in register P1 to be an integer.  If the value
72558 ** in P1 is not an integer and cannot be converted into an integer
72559 ** without data loss, then jump immediately to P2, or if P2==0
72560 ** raise an SQLITE_MISMATCH exception.
72561 */
72562 case OP_MustBeInt: {            /* jump, in1 */
72563   pIn1 = &aMem[pOp->p1];
72564   if( (pIn1->flags & MEM_Int)==0 ){
72565     applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
72566     VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
72567     if( (pIn1->flags & MEM_Int)==0 ){
72568       if( pOp->p2==0 ){
72569         rc = SQLITE_MISMATCH;
72570         goto abort_due_to_error;
72571       }else{
72572         goto jump_to_p2;
72573       }
72574     }
72575   }
72576   MemSetTypeFlag(pIn1, MEM_Int);
72577   break;
72578 }
72579 
72580 #ifndef SQLITE_OMIT_FLOATING_POINT
72581 /* Opcode: RealAffinity P1 * * * *
72582 **
72583 ** If register P1 holds an integer convert it to a real value.
72584 **
72585 ** This opcode is used when extracting information from a column that
72586 ** has REAL affinity.  Such column values may still be stored as
72587 ** integers, for space efficiency, but after extraction we want them
72588 ** to have only a real value.
72589 */
72590 case OP_RealAffinity: {                  /* in1 */
72591   pIn1 = &aMem[pOp->p1];
72592   if( pIn1->flags & MEM_Int ){
72593     sqlite3VdbeMemRealify(pIn1);
72594   }
72595   break;
72596 }
72597 #endif
72598 
72599 #ifndef SQLITE_OMIT_CAST
72600 /* Opcode: Cast P1 P2 * * *
72601 ** Synopsis: affinity(r[P1])
72602 **
72603 ** Force the value in register P1 to be the type defined by P2.
72604 **
72605 ** <ul>
72606 ** <li value="97"> TEXT
72607 ** <li value="98"> BLOB
72608 ** <li value="99"> NUMERIC
72609 ** <li value="100"> INTEGER
72610 ** <li value="101"> REAL
72611 ** </ul>
72612 **
72613 ** A NULL value is not changed by this routine.  It remains NULL.
72614 */
72615 case OP_Cast: {                  /* in1 */
72616   assert( pOp->p2>=SQLITE_AFF_NONE && pOp->p2<=SQLITE_AFF_REAL );
72617   testcase( pOp->p2==SQLITE_AFF_TEXT );
72618   testcase( pOp->p2==SQLITE_AFF_NONE );
72619   testcase( pOp->p2==SQLITE_AFF_NUMERIC );
72620   testcase( pOp->p2==SQLITE_AFF_INTEGER );
72621   testcase( pOp->p2==SQLITE_AFF_REAL );
72622   pIn1 = &aMem[pOp->p1];
72623   memAboutToChange(p, pIn1);
72624   rc = ExpandBlob(pIn1);
72625   sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
72626   UPDATE_MAX_BLOBSIZE(pIn1);
72627   break;
72628 }
72629 #endif /* SQLITE_OMIT_CAST */
72630 
72631 /* Opcode: Lt P1 P2 P3 P4 P5
72632 ** Synopsis: if r[P1]<r[P3] goto P2
72633 **
72634 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
72635 ** jump to address P2.
72636 **
72637 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
72638 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
72639 ** bit is clear then fall through if either operand is NULL.
72640 **
72641 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
72642 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
72643 ** to coerce both inputs according to this affinity before the
72644 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
72645 ** affinity is used. Note that the affinity conversions are stored
72646 ** back into the input registers P1 and P3.  So this opcode can cause
72647 ** persistent changes to registers P1 and P3.
72648 **
72649 ** Once any conversions have taken place, and neither value is NULL,
72650 ** the values are compared. If both values are blobs then memcmp() is
72651 ** used to determine the results of the comparison.  If both values
72652 ** are text, then the appropriate collating function specified in
72653 ** P4 is  used to do the comparison.  If P4 is not specified then
72654 ** memcmp() is used to compare text string.  If both values are
72655 ** numeric, then a numeric comparison is used. If the two values
72656 ** are of different types, then numbers are considered less than
72657 ** strings and strings are considered less than blobs.
72658 **
72659 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
72660 ** store a boolean result (either 0, or 1, or NULL) in register P2.
72661 **
72662 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
72663 ** equal to one another, provided that they do not have their MEM_Cleared
72664 ** bit set.
72665 */
72666 /* Opcode: Ne P1 P2 P3 P4 P5
72667 ** Synopsis: if r[P1]!=r[P3] goto P2
72668 **
72669 ** This works just like the Lt opcode except that the jump is taken if
72670 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
72671 ** additional information.
72672 **
72673 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
72674 ** true or false and is never NULL.  If both operands are NULL then the result
72675 ** of comparison is false.  If either operand is NULL then the result is true.
72676 ** If neither operand is NULL the result is the same as it would be if
72677 ** the SQLITE_NULLEQ flag were omitted from P5.
72678 */
72679 /* Opcode: Eq P1 P2 P3 P4 P5
72680 ** Synopsis: if r[P1]==r[P3] goto P2
72681 **
72682 ** This works just like the Lt opcode except that the jump is taken if
72683 ** the operands in registers P1 and P3 are equal.
72684 ** See the Lt opcode for additional information.
72685 **
72686 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
72687 ** true or false and is never NULL.  If both operands are NULL then the result
72688 ** of comparison is true.  If either operand is NULL then the result is false.
72689 ** If neither operand is NULL the result is the same as it would be if
72690 ** the SQLITE_NULLEQ flag were omitted from P5.
72691 */
72692 /* Opcode: Le P1 P2 P3 P4 P5
72693 ** Synopsis: if r[P1]<=r[P3] goto P2
72694 **
72695 ** This works just like the Lt opcode except that the jump is taken if
72696 ** the content of register P3 is less than or equal to the content of
72697 ** register P1.  See the Lt opcode for additional information.
72698 */
72699 /* Opcode: Gt P1 P2 P3 P4 P5
72700 ** Synopsis: if r[P1]>r[P3] goto P2
72701 **
72702 ** This works just like the Lt opcode except that the jump is taken if
72703 ** the content of register P3 is greater than the content of
72704 ** register P1.  See the Lt opcode for additional information.
72705 */
72706 /* Opcode: Ge P1 P2 P3 P4 P5
72707 ** Synopsis: if r[P1]>=r[P3] goto P2
72708 **
72709 ** This works just like the Lt opcode except that the jump is taken if
72710 ** the content of register P3 is greater than or equal to the content of
72711 ** register P1.  See the Lt opcode for additional information.
72712 */
72713 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
72714 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
72715 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
72716 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
72717 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
72718 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
72719   int res;            /* Result of the comparison of pIn1 against pIn3 */
72720   char affinity;      /* Affinity to use for comparison */
72721   u16 flags1;         /* Copy of initial value of pIn1->flags */
72722   u16 flags3;         /* Copy of initial value of pIn3->flags */
72723 
72724   pIn1 = &aMem[pOp->p1];
72725   pIn3 = &aMem[pOp->p3];
72726   flags1 = pIn1->flags;
72727   flags3 = pIn3->flags;
72728   if( (flags1 | flags3)&MEM_Null ){
72729     /* One or both operands are NULL */
72730     if( pOp->p5 & SQLITE_NULLEQ ){
72731       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
72732       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
72733       ** or not both operands are null.
72734       */
72735       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
72736       assert( (flags1 & MEM_Cleared)==0 );
72737       assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
72738       if( (flags1&MEM_Null)!=0
72739        && (flags3&MEM_Null)!=0
72740        && (flags3&MEM_Cleared)==0
72741       ){
72742         res = 0;  /* Results are equal */
72743       }else{
72744         res = 1;  /* Results are not equal */
72745       }
72746     }else{
72747       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
72748       ** then the result is always NULL.
72749       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
72750       */
72751       if( pOp->p5 & SQLITE_STOREP2 ){
72752         pOut = &aMem[pOp->p2];
72753         MemSetTypeFlag(pOut, MEM_Null);
72754         REGISTER_TRACE(pOp->p2, pOut);
72755       }else{
72756         VdbeBranchTaken(2,3);
72757         if( pOp->p5 & SQLITE_JUMPIFNULL ){
72758           goto jump_to_p2;
72759         }
72760       }
72761       break;
72762     }
72763   }else{
72764     /* Neither operand is NULL.  Do a comparison. */
72765     affinity = pOp->p5 & SQLITE_AFF_MASK;
72766     if( affinity>=SQLITE_AFF_NUMERIC ){
72767       if( (pIn1->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
72768         applyNumericAffinity(pIn1,0);
72769       }
72770       if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
72771         applyNumericAffinity(pIn3,0);
72772       }
72773     }else if( affinity==SQLITE_AFF_TEXT ){
72774       if( (pIn1->flags & MEM_Str)==0 && (pIn1->flags & (MEM_Int|MEM_Real))!=0 ){
72775         testcase( pIn1->flags & MEM_Int );
72776         testcase( pIn1->flags & MEM_Real );
72777         sqlite3VdbeMemStringify(pIn1, encoding, 1);
72778         testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
72779         flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
72780       }
72781       if( (pIn3->flags & MEM_Str)==0 && (pIn3->flags & (MEM_Int|MEM_Real))!=0 ){
72782         testcase( pIn3->flags & MEM_Int );
72783         testcase( pIn3->flags & MEM_Real );
72784         sqlite3VdbeMemStringify(pIn3, encoding, 1);
72785         testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
72786         flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
72787       }
72788     }
72789     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
72790     if( pIn1->flags & MEM_Zero ){
72791       sqlite3VdbeMemExpandBlob(pIn1);
72792       flags1 &= ~MEM_Zero;
72793     }
72794     if( pIn3->flags & MEM_Zero ){
72795       sqlite3VdbeMemExpandBlob(pIn3);
72796       flags3 &= ~MEM_Zero;
72797     }
72798     if( db->mallocFailed ) goto no_mem;
72799     res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
72800   }
72801   switch( pOp->opcode ){
72802     case OP_Eq:    res = res==0;     break;
72803     case OP_Ne:    res = res!=0;     break;
72804     case OP_Lt:    res = res<0;      break;
72805     case OP_Le:    res = res<=0;     break;
72806     case OP_Gt:    res = res>0;      break;
72807     default:       res = res>=0;     break;
72808   }
72809 
72810   /* Undo any changes made by applyAffinity() to the input registers. */
72811   assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
72812   pIn1->flags = flags1;
72813   assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
72814   pIn3->flags = flags3;
72815 
72816   if( pOp->p5 & SQLITE_STOREP2 ){
72817     pOut = &aMem[pOp->p2];
72818     memAboutToChange(p, pOut);
72819     MemSetTypeFlag(pOut, MEM_Int);
72820     pOut->u.i = res;
72821     REGISTER_TRACE(pOp->p2, pOut);
72822   }else{
72823     VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
72824     if( res ){
72825       goto jump_to_p2;
72826     }
72827   }
72828   break;
72829 }
72830 
72831 /* Opcode: Permutation * * * P4 *
72832 **
72833 ** Set the permutation used by the OP_Compare operator to be the array
72834 ** of integers in P4.
72835 **
72836 ** The permutation is only valid until the next OP_Compare that has
72837 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
72838 ** occur immediately prior to the OP_Compare.
72839 */
72840 case OP_Permutation: {
72841   assert( pOp->p4type==P4_INTARRAY );
72842   assert( pOp->p4.ai );
72843   aPermute = pOp->p4.ai;
72844   break;
72845 }
72846 
72847 /* Opcode: Compare P1 P2 P3 P4 P5
72848 ** Synopsis: r[P1@P3] <-> r[P2@P3]
72849 **
72850 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
72851 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
72852 ** the comparison for use by the next OP_Jump instruct.
72853 **
72854 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
72855 ** determined by the most recent OP_Permutation operator.  If the
72856 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
72857 ** order.
72858 **
72859 ** P4 is a KeyInfo structure that defines collating sequences and sort
72860 ** orders for the comparison.  The permutation applies to registers
72861 ** only.  The KeyInfo elements are used sequentially.
72862 **
72863 ** The comparison is a sort comparison, so NULLs compare equal,
72864 ** NULLs are less than numbers, numbers are less than strings,
72865 ** and strings are less than blobs.
72866 */
72867 case OP_Compare: {
72868   int n;
72869   int i;
72870   int p1;
72871   int p2;
72872   const KeyInfo *pKeyInfo;
72873   int idx;
72874   CollSeq *pColl;    /* Collating sequence to use on this term */
72875   int bRev;          /* True for DESCENDING sort order */
72876 
72877   if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
72878   n = pOp->p3;
72879   pKeyInfo = pOp->p4.pKeyInfo;
72880   assert( n>0 );
72881   assert( pKeyInfo!=0 );
72882   p1 = pOp->p1;
72883   p2 = pOp->p2;
72884 #if SQLITE_DEBUG
72885   if( aPermute ){
72886     int k, mx = 0;
72887     for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
72888     assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
72889     assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
72890   }else{
72891     assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
72892     assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
72893   }
72894 #endif /* SQLITE_DEBUG */
72895   for(i=0; i<n; i++){
72896     idx = aPermute ? aPermute[i] : i;
72897     assert( memIsValid(&aMem[p1+idx]) );
72898     assert( memIsValid(&aMem[p2+idx]) );
72899     REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
72900     REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
72901     assert( i<pKeyInfo->nField );
72902     pColl = pKeyInfo->aColl[i];
72903     bRev = pKeyInfo->aSortOrder[i];
72904     iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
72905     if( iCompare ){
72906       if( bRev ) iCompare = -iCompare;
72907       break;
72908     }
72909   }
72910   aPermute = 0;
72911   break;
72912 }
72913 
72914 /* Opcode: Jump P1 P2 P3 * *
72915 **
72916 ** Jump to the instruction at address P1, P2, or P3 depending on whether
72917 ** in the most recent OP_Compare instruction the P1 vector was less than
72918 ** equal to, or greater than the P2 vector, respectively.
72919 */
72920 case OP_Jump: {             /* jump */
72921   if( iCompare<0 ){
72922     VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
72923   }else if( iCompare==0 ){
72924     VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
72925   }else{
72926     VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
72927   }
72928   break;
72929 }
72930 
72931 /* Opcode: And P1 P2 P3 * *
72932 ** Synopsis: r[P3]=(r[P1] && r[P2])
72933 **
72934 ** Take the logical AND of the values in registers P1 and P2 and
72935 ** write the result into register P3.
72936 **
72937 ** If either P1 or P2 is 0 (false) then the result is 0 even if
72938 ** the other input is NULL.  A NULL and true or two NULLs give
72939 ** a NULL output.
72940 */
72941 /* Opcode: Or P1 P2 P3 * *
72942 ** Synopsis: r[P3]=(r[P1] || r[P2])
72943 **
72944 ** Take the logical OR of the values in register P1 and P2 and
72945 ** store the answer in register P3.
72946 **
72947 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
72948 ** even if the other input is NULL.  A NULL and false or two NULLs
72949 ** give a NULL output.
72950 */
72951 case OP_And:              /* same as TK_AND, in1, in2, out3 */
72952 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
72953   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
72954   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
72955 
72956   pIn1 = &aMem[pOp->p1];
72957   if( pIn1->flags & MEM_Null ){
72958     v1 = 2;
72959   }else{
72960     v1 = sqlite3VdbeIntValue(pIn1)!=0;
72961   }
72962   pIn2 = &aMem[pOp->p2];
72963   if( pIn2->flags & MEM_Null ){
72964     v2 = 2;
72965   }else{
72966     v2 = sqlite3VdbeIntValue(pIn2)!=0;
72967   }
72968   if( pOp->opcode==OP_And ){
72969     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
72970     v1 = and_logic[v1*3+v2];
72971   }else{
72972     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
72973     v1 = or_logic[v1*3+v2];
72974   }
72975   pOut = &aMem[pOp->p3];
72976   if( v1==2 ){
72977     MemSetTypeFlag(pOut, MEM_Null);
72978   }else{
72979     pOut->u.i = v1;
72980     MemSetTypeFlag(pOut, MEM_Int);
72981   }
72982   break;
72983 }
72984 
72985 /* Opcode: Not P1 P2 * * *
72986 ** Synopsis: r[P2]= !r[P1]
72987 **
72988 ** Interpret the value in register P1 as a boolean value.  Store the
72989 ** boolean complement in register P2.  If the value in register P1 is
72990 ** NULL, then a NULL is stored in P2.
72991 */
72992 case OP_Not: {                /* same as TK_NOT, in1, out2 */
72993   pIn1 = &aMem[pOp->p1];
72994   pOut = &aMem[pOp->p2];
72995   sqlite3VdbeMemSetNull(pOut);
72996   if( (pIn1->flags & MEM_Null)==0 ){
72997     pOut->flags = MEM_Int;
72998     pOut->u.i = !sqlite3VdbeIntValue(pIn1);
72999   }
73000   break;
73001 }
73002 
73003 /* Opcode: BitNot P1 P2 * * *
73004 ** Synopsis: r[P1]= ~r[P1]
73005 **
73006 ** Interpret the content of register P1 as an integer.  Store the
73007 ** ones-complement of the P1 value into register P2.  If P1 holds
73008 ** a NULL then store a NULL in P2.
73009 */
73010 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
73011   pIn1 = &aMem[pOp->p1];
73012   pOut = &aMem[pOp->p2];
73013   sqlite3VdbeMemSetNull(pOut);
73014   if( (pIn1->flags & MEM_Null)==0 ){
73015     pOut->flags = MEM_Int;
73016     pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
73017   }
73018   break;
73019 }
73020 
73021 /* Opcode: Once P1 P2 * * *
73022 **
73023 ** Check the "once" flag number P1. If it is set, jump to instruction P2.
73024 ** Otherwise, set the flag and fall through to the next instruction.
73025 ** In other words, this opcode causes all following opcodes up through P2
73026 ** (but not including P2) to run just once and to be skipped on subsequent
73027 ** times through the loop.
73028 **
73029 ** All "once" flags are initially cleared whenever a prepared statement
73030 ** first begins to run.
73031 */
73032 case OP_Once: {             /* jump */
73033   assert( pOp->p1<p->nOnceFlag );
73034   VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
73035   if( p->aOnceFlag[pOp->p1] ){
73036     goto jump_to_p2;
73037   }else{
73038     p->aOnceFlag[pOp->p1] = 1;
73039   }
73040   break;
73041 }
73042 
73043 /* Opcode: If P1 P2 P3 * *
73044 **
73045 ** Jump to P2 if the value in register P1 is true.  The value
73046 ** is considered true if it is numeric and non-zero.  If the value
73047 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
73048 */
73049 /* Opcode: IfNot P1 P2 P3 * *
73050 **
73051 ** Jump to P2 if the value in register P1 is False.  The value
73052 ** is considered false if it has a numeric value of zero.  If the value
73053 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
73054 */
73055 case OP_If:                 /* jump, in1 */
73056 case OP_IfNot: {            /* jump, in1 */
73057   int c;
73058   pIn1 = &aMem[pOp->p1];
73059   if( pIn1->flags & MEM_Null ){
73060     c = pOp->p3;
73061   }else{
73062 #ifdef SQLITE_OMIT_FLOATING_POINT
73063     c = sqlite3VdbeIntValue(pIn1)!=0;
73064 #else
73065     c = sqlite3VdbeRealValue(pIn1)!=0.0;
73066 #endif
73067     if( pOp->opcode==OP_IfNot ) c = !c;
73068   }
73069   VdbeBranchTaken(c!=0, 2);
73070   if( c ){
73071     goto jump_to_p2;
73072   }
73073   break;
73074 }
73075 
73076 /* Opcode: IsNull P1 P2 * * *
73077 ** Synopsis:  if r[P1]==NULL goto P2
73078 **
73079 ** Jump to P2 if the value in register P1 is NULL.
73080 */
73081 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
73082   pIn1 = &aMem[pOp->p1];
73083   VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
73084   if( (pIn1->flags & MEM_Null)!=0 ){
73085     goto jump_to_p2;
73086   }
73087   break;
73088 }
73089 
73090 /* Opcode: NotNull P1 P2 * * *
73091 ** Synopsis: if r[P1]!=NULL goto P2
73092 **
73093 ** Jump to P2 if the value in register P1 is not NULL.
73094 */
73095 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
73096   pIn1 = &aMem[pOp->p1];
73097   VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
73098   if( (pIn1->flags & MEM_Null)==0 ){
73099     goto jump_to_p2;
73100   }
73101   break;
73102 }
73103 
73104 /* Opcode: Column P1 P2 P3 P4 P5
73105 ** Synopsis:  r[P3]=PX
73106 **
73107 ** Interpret the data that cursor P1 points to as a structure built using
73108 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
73109 ** information about the format of the data.)  Extract the P2-th column
73110 ** from this record.  If there are less that (P2+1)
73111 ** values in the record, extract a NULL.
73112 **
73113 ** The value extracted is stored in register P3.
73114 **
73115 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
73116 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
73117 ** the result.
73118 **
73119 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
73120 ** then the cache of the cursor is reset prior to extracting the column.
73121 ** The first OP_Column against a pseudo-table after the value of the content
73122 ** register has changed should have this bit set.
73123 **
73124 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
73125 ** the result is guaranteed to only be used as the argument of a length()
73126 ** or typeof() function, respectively.  The loading of large blobs can be
73127 ** skipped for length() and all content loading can be skipped for typeof().
73128 */
73129 case OP_Column: {
73130   i64 payloadSize64; /* Number of bytes in the record */
73131   int p2;            /* column number to retrieve */
73132   VdbeCursor *pC;    /* The VDBE cursor */
73133   BtCursor *pCrsr;   /* The BTree cursor */
73134   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
73135   int len;           /* The length of the serialized data for the column */
73136   int i;             /* Loop counter */
73137   Mem *pDest;        /* Where to write the extracted value */
73138   Mem sMem;          /* For storing the record being decoded */
73139   const u8 *zData;   /* Part of the record being decoded */
73140   const u8 *zHdr;    /* Next unparsed byte of the header */
73141   const u8 *zEndHdr; /* Pointer to first byte after the header */
73142   u32 offset;        /* Offset into the data */
73143   u32 szField;       /* Number of bytes in the content of a field */
73144   u32 avail;         /* Number of bytes of available data */
73145   u32 t;             /* A type code from the record header */
73146   u16 fx;            /* pDest->flags value */
73147   Mem *pReg;         /* PseudoTable input register */
73148 
73149   p2 = pOp->p2;
73150   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
73151   pDest = &aMem[pOp->p3];
73152   memAboutToChange(p, pDest);
73153   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
73154   pC = p->apCsr[pOp->p1];
73155   assert( pC!=0 );
73156   assert( p2<pC->nField );
73157   aOffset = pC->aOffset;
73158 #ifndef SQLITE_OMIT_VIRTUALTABLE
73159   assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
73160 #endif
73161   pCrsr = pC->pCursor;
73162   assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
73163   assert( pCrsr!=0 || pC->nullRow );          /* pC->nullRow on PseudoTables */
73164 
73165   /* If the cursor cache is stale, bring it up-to-date */
73166   rc = sqlite3VdbeCursorMoveto(pC);
73167   if( rc ) goto abort_due_to_error;
73168   if( pC->cacheStatus!=p->cacheCtr ){
73169     if( pC->nullRow ){
73170       if( pCrsr==0 ){
73171         assert( pC->pseudoTableReg>0 );
73172         pReg = &aMem[pC->pseudoTableReg];
73173         assert( pReg->flags & MEM_Blob );
73174         assert( memIsValid(pReg) );
73175         pC->payloadSize = pC->szRow = avail = pReg->n;
73176         pC->aRow = (u8*)pReg->z;
73177       }else{
73178         sqlite3VdbeMemSetNull(pDest);
73179         goto op_column_out;
73180       }
73181     }else{
73182       assert( pCrsr );
73183       if( pC->isTable==0 ){
73184         assert( sqlite3BtreeCursorIsValid(pCrsr) );
73185         VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
73186         assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
73187         /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
73188         ** payload size, so it is impossible for payloadSize64 to be
73189         ** larger than 32 bits. */
73190         assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
73191         pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
73192         pC->payloadSize = (u32)payloadSize64;
73193       }else{
73194         assert( sqlite3BtreeCursorIsValid(pCrsr) );
73195         VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
73196         assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
73197         pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
73198       }
73199       assert( avail<=65536 );  /* Maximum page size is 64KiB */
73200       if( pC->payloadSize <= (u32)avail ){
73201         pC->szRow = pC->payloadSize;
73202       }else{
73203         pC->szRow = avail;
73204       }
73205       if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
73206         goto too_big;
73207       }
73208     }
73209     pC->cacheStatus = p->cacheCtr;
73210     pC->iHdrOffset = getVarint32(pC->aRow, offset);
73211     pC->nHdrParsed = 0;
73212     aOffset[0] = offset;
73213 
73214     /* Make sure a corrupt database has not given us an oversize header.
73215     ** Do this now to avoid an oversize memory allocation.
73216     **
73217     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
73218     ** types use so much data space that there can only be 4096 and 32 of
73219     ** them, respectively.  So the maximum header length results from a
73220     ** 3-byte type for each of the maximum of 32768 columns plus three
73221     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
73222     */
73223     if( offset > 98307 || offset > pC->payloadSize ){
73224       rc = SQLITE_CORRUPT_BKPT;
73225       goto op_column_error;
73226     }
73227 
73228     if( avail<offset ){
73229       /* pC->aRow does not have to hold the entire row, but it does at least
73230       ** need to cover the header of the record.  If pC->aRow does not contain
73231       ** the complete header, then set it to zero, forcing the header to be
73232       ** dynamically allocated. */
73233       pC->aRow = 0;
73234       pC->szRow = 0;
73235     }
73236 
73237     /* The following goto is an optimization.  It can be omitted and
73238     ** everything will still work.  But OP_Column is measurably faster
73239     ** by skipping the subsequent conditional, which is always true.
73240     */
73241     assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
73242     goto op_column_read_header;
73243   }
73244 
73245   /* Make sure at least the first p2+1 entries of the header have been
73246   ** parsed and valid information is in aOffset[] and pC->aType[].
73247   */
73248   if( pC->nHdrParsed<=p2 ){
73249     /* If there is more header available for parsing in the record, try
73250     ** to extract additional fields up through the p2+1-th field
73251     */
73252     op_column_read_header:
73253     if( pC->iHdrOffset<aOffset[0] ){
73254       /* Make sure zData points to enough of the record to cover the header. */
73255       if( pC->aRow==0 ){
73256         memset(&sMem, 0, sizeof(sMem));
73257         rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
73258                                      !pC->isTable, &sMem);
73259         if( rc!=SQLITE_OK ){
73260           goto op_column_error;
73261         }
73262         zData = (u8*)sMem.z;
73263       }else{
73264         zData = pC->aRow;
73265       }
73266 
73267       /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
73268       i = pC->nHdrParsed;
73269       offset = aOffset[i];
73270       zHdr = zData + pC->iHdrOffset;
73271       zEndHdr = zData + aOffset[0];
73272       assert( i<=p2 && zHdr<zEndHdr );
73273       do{
73274         if( zHdr[0]<0x80 ){
73275           t = zHdr[0];
73276           zHdr++;
73277         }else{
73278           zHdr += sqlite3GetVarint32(zHdr, &t);
73279         }
73280         pC->aType[i] = t;
73281         szField = sqlite3VdbeSerialTypeLen(t);
73282         offset += szField;
73283         if( offset<szField ){  /* True if offset overflows */
73284           zHdr = &zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
73285           break;
73286         }
73287         i++;
73288         aOffset[i] = offset;
73289       }while( i<=p2 && zHdr<zEndHdr );
73290       pC->nHdrParsed = i;
73291       pC->iHdrOffset = (u32)(zHdr - zData);
73292       if( pC->aRow==0 ){
73293         sqlite3VdbeMemRelease(&sMem);
73294         sMem.flags = MEM_Null;
73295       }
73296 
73297       /* The record is corrupt if any of the following are true:
73298       ** (1) the bytes of the header extend past the declared header size
73299       **          (zHdr>zEndHdr)
73300       ** (2) the entire header was used but not all data was used
73301       **          (zHdr==zEndHdr && offset!=pC->payloadSize)
73302       ** (3) the end of the data extends beyond the end of the record.
73303       **          (offset > pC->payloadSize)
73304       */
73305       if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset!=pC->payloadSize))
73306        || (offset > pC->payloadSize)
73307       ){
73308         rc = SQLITE_CORRUPT_BKPT;
73309         goto op_column_error;
73310       }
73311     }
73312 
73313     /* If after trying to extract new entries from the header, nHdrParsed is
73314     ** still not up to p2, that means that the record has fewer than p2
73315     ** columns.  So the result will be either the default value or a NULL.
73316     */
73317     if( pC->nHdrParsed<=p2 ){
73318       if( pOp->p4type==P4_MEM ){
73319         sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
73320       }else{
73321         sqlite3VdbeMemSetNull(pDest);
73322       }
73323       goto op_column_out;
73324     }
73325   }
73326 
73327   /* Extract the content for the p2+1-th column.  Control can only
73328   ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
73329   ** all valid.
73330   */
73331   assert( p2<pC->nHdrParsed );
73332   assert( rc==SQLITE_OK );
73333   assert( sqlite3VdbeCheckMemInvariants(pDest) );
73334   if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
73335   t = pC->aType[p2];
73336   if( pC->szRow>=aOffset[p2+1] ){
73337     /* This is the common case where the desired content fits on the original
73338     ** page - where the content is not on an overflow page */
73339     sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], t, pDest);
73340   }else{
73341     /* This branch happens only when content is on overflow pages */
73342     if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
73343           && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
73344      || (len = sqlite3VdbeSerialTypeLen(t))==0
73345     ){
73346       /* Content is irrelevant for
73347       **    1. the typeof() function,
73348       **    2. the length(X) function if X is a blob, and
73349       **    3. if the content length is zero.
73350       ** So we might as well use bogus content rather than reading
73351       ** content from disk.  NULL will work for the value for strings
73352       ** and blobs and whatever is in the payloadSize64 variable
73353       ** will work for everything else. */
73354       sqlite3VdbeSerialGet(t<=13 ? (u8*)&payloadSize64 : 0, t, pDest);
73355     }else{
73356       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
73357                                    pDest);
73358       if( rc!=SQLITE_OK ){
73359         goto op_column_error;
73360       }
73361       sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
73362       pDest->flags &= ~MEM_Ephem;
73363     }
73364   }
73365   pDest->enc = encoding;
73366 
73367 op_column_out:
73368   /* If the column value is an ephemeral string, go ahead and persist
73369   ** that string in case the cursor moves before the column value is
73370   ** used.  The following code does the equivalent of Deephemeralize()
73371   ** but does it faster. */
73372   if( (pDest->flags & MEM_Ephem)!=0 && pDest->z ){
73373     fx = pDest->flags & (MEM_Str|MEM_Blob);
73374     assert( fx!=0 );
73375     zData = (const u8*)pDest->z;
73376     len = pDest->n;
73377     if( sqlite3VdbeMemClearAndResize(pDest, len+2) ) goto no_mem;
73378     memcpy(pDest->z, zData, len);
73379     pDest->z[len] = 0;
73380     pDest->z[len+1] = 0;
73381     pDest->flags = fx|MEM_Term;
73382   }
73383 op_column_error:
73384   UPDATE_MAX_BLOBSIZE(pDest);
73385   REGISTER_TRACE(pOp->p3, pDest);
73386   break;
73387 }
73388 
73389 /* Opcode: Affinity P1 P2 * P4 *
73390 ** Synopsis: affinity(r[P1@P2])
73391 **
73392 ** Apply affinities to a range of P2 registers starting with P1.
73393 **
73394 ** P4 is a string that is P2 characters long. The nth character of the
73395 ** string indicates the column affinity that should be used for the nth
73396 ** memory cell in the range.
73397 */
73398 case OP_Affinity: {
73399   const char *zAffinity;   /* The affinity to be applied */
73400   char cAff;               /* A single character of affinity */
73401 
73402   zAffinity = pOp->p4.z;
73403   assert( zAffinity!=0 );
73404   assert( zAffinity[pOp->p2]==0 );
73405   pIn1 = &aMem[pOp->p1];
73406   while( (cAff = *(zAffinity++))!=0 ){
73407     assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
73408     assert( memIsValid(pIn1) );
73409     applyAffinity(pIn1, cAff, encoding);
73410     pIn1++;
73411   }
73412   break;
73413 }
73414 
73415 /* Opcode: MakeRecord P1 P2 P3 P4 *
73416 ** Synopsis: r[P3]=mkrec(r[P1@P2])
73417 **
73418 ** Convert P2 registers beginning with P1 into the [record format]
73419 ** use as a data record in a database table or as a key
73420 ** in an index.  The OP_Column opcode can decode the record later.
73421 **
73422 ** P4 may be a string that is P2 characters long.  The nth character of the
73423 ** string indicates the column affinity that should be used for the nth
73424 ** field of the index key.
73425 **
73426 ** The mapping from character to affinity is given by the SQLITE_AFF_
73427 ** macros defined in sqliteInt.h.
73428 **
73429 ** If P4 is NULL then all index fields have the affinity NONE.
73430 */
73431 case OP_MakeRecord: {
73432   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
73433   Mem *pRec;             /* The new record */
73434   u64 nData;             /* Number of bytes of data space */
73435   int nHdr;              /* Number of bytes of header space */
73436   i64 nByte;             /* Data space required for this record */
73437   i64 nZero;             /* Number of zero bytes at the end of the record */
73438   int nVarint;           /* Number of bytes in a varint */
73439   u32 serial_type;       /* Type field */
73440   Mem *pData0;           /* First field to be combined into the record */
73441   Mem *pLast;            /* Last field of the record */
73442   int nField;            /* Number of fields in the record */
73443   char *zAffinity;       /* The affinity string for the record */
73444   int file_format;       /* File format to use for encoding */
73445   int i;                 /* Space used in zNewRecord[] header */
73446   int j;                 /* Space used in zNewRecord[] content */
73447   int len;               /* Length of a field */
73448 
73449   /* Assuming the record contains N fields, the record format looks
73450   ** like this:
73451   **
73452   ** ------------------------------------------------------------------------
73453   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
73454   ** ------------------------------------------------------------------------
73455   **
73456   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
73457   ** and so forth.
73458   **
73459   ** Each type field is a varint representing the serial type of the
73460   ** corresponding data element (see sqlite3VdbeSerialType()). The
73461   ** hdr-size field is also a varint which is the offset from the beginning
73462   ** of the record to data0.
73463   */
73464   nData = 0;         /* Number of bytes of data space */
73465   nHdr = 0;          /* Number of bytes of header space */
73466   nZero = 0;         /* Number of zero bytes at the end of the record */
73467   nField = pOp->p1;
73468   zAffinity = pOp->p4.z;
73469   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
73470   pData0 = &aMem[nField];
73471   nField = pOp->p2;
73472   pLast = &pData0[nField-1];
73473   file_format = p->minWriteFileFormat;
73474 
73475   /* Identify the output register */
73476   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
73477   pOut = &aMem[pOp->p3];
73478   memAboutToChange(p, pOut);
73479 
73480   /* Apply the requested affinity to all inputs
73481   */
73482   assert( pData0<=pLast );
73483   if( zAffinity ){
73484     pRec = pData0;
73485     do{
73486       applyAffinity(pRec++, *(zAffinity++), encoding);
73487       assert( zAffinity[0]==0 || pRec<=pLast );
73488     }while( zAffinity[0] );
73489   }
73490 
73491   /* Loop through the elements that will make up the record to figure
73492   ** out how much space is required for the new record.
73493   */
73494   pRec = pLast;
73495   do{
73496     assert( memIsValid(pRec) );
73497     pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format);
73498     len = sqlite3VdbeSerialTypeLen(serial_type);
73499     if( pRec->flags & MEM_Zero ){
73500       if( nData ){
73501         sqlite3VdbeMemExpandBlob(pRec);
73502       }else{
73503         nZero += pRec->u.nZero;
73504         len -= pRec->u.nZero;
73505       }
73506     }
73507     nData += len;
73508     testcase( serial_type==127 );
73509     testcase( serial_type==128 );
73510     nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
73511   }while( (--pRec)>=pData0 );
73512 
73513   /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
73514   ** which determines the total number of bytes in the header. The varint
73515   ** value is the size of the header in bytes including the size varint
73516   ** itself. */
73517   testcase( nHdr==126 );
73518   testcase( nHdr==127 );
73519   if( nHdr<=126 ){
73520     /* The common case */
73521     nHdr += 1;
73522   }else{
73523     /* Rare case of a really large header */
73524     nVarint = sqlite3VarintLen(nHdr);
73525     nHdr += nVarint;
73526     if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
73527   }
73528   nByte = nHdr+nData;
73529   if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
73530     goto too_big;
73531   }
73532 
73533   /* Make sure the output register has a buffer large enough to store
73534   ** the new record. The output register (pOp->p3) is not allowed to
73535   ** be one of the input registers (because the following call to
73536   ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
73537   */
73538   if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
73539     goto no_mem;
73540   }
73541   zNewRecord = (u8 *)pOut->z;
73542 
73543   /* Write the record */
73544   i = putVarint32(zNewRecord, nHdr);
73545   j = nHdr;
73546   assert( pData0<=pLast );
73547   pRec = pData0;
73548   do{
73549     serial_type = pRec->uTemp;
73550     /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
73551     ** additional varints, one per column. */
73552     i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
73553     /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
73554     ** immediately follow the header. */
73555     j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
73556   }while( (++pRec)<=pLast );
73557   assert( i==nHdr );
73558   assert( j==nByte );
73559 
73560   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
73561   pOut->n = (int)nByte;
73562   pOut->flags = MEM_Blob;
73563   if( nZero ){
73564     pOut->u.nZero = nZero;
73565     pOut->flags |= MEM_Zero;
73566   }
73567   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
73568   REGISTER_TRACE(pOp->p3, pOut);
73569   UPDATE_MAX_BLOBSIZE(pOut);
73570   break;
73571 }
73572 
73573 /* Opcode: Count P1 P2 * * *
73574 ** Synopsis: r[P2]=count()
73575 **
73576 ** Store the number of entries (an integer value) in the table or index
73577 ** opened by cursor P1 in register P2
73578 */
73579 #ifndef SQLITE_OMIT_BTREECOUNT
73580 case OP_Count: {         /* out2 */
73581   i64 nEntry;
73582   BtCursor *pCrsr;
73583 
73584   pCrsr = p->apCsr[pOp->p1]->pCursor;
73585   assert( pCrsr );
73586   nEntry = 0;  /* Not needed.  Only used to silence a warning. */
73587   rc = sqlite3BtreeCount(pCrsr, &nEntry);
73588   pOut = out2Prerelease(p, pOp);
73589   pOut->u.i = nEntry;
73590   break;
73591 }
73592 #endif
73593 
73594 /* Opcode: Savepoint P1 * * P4 *
73595 **
73596 ** Open, release or rollback the savepoint named by parameter P4, depending
73597 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
73598 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
73599 */
73600 case OP_Savepoint: {
73601   int p1;                         /* Value of P1 operand */
73602   char *zName;                    /* Name of savepoint */
73603   int nName;
73604   Savepoint *pNew;
73605   Savepoint *pSavepoint;
73606   Savepoint *pTmp;
73607   int iSavepoint;
73608   int ii;
73609 
73610   p1 = pOp->p1;
73611   zName = pOp->p4.z;
73612 
73613   /* Assert that the p1 parameter is valid. Also that if there is no open
73614   ** transaction, then there cannot be any savepoints.
73615   */
73616   assert( db->pSavepoint==0 || db->autoCommit==0 );
73617   assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
73618   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
73619   assert( checkSavepointCount(db) );
73620   assert( p->bIsReader );
73621 
73622   if( p1==SAVEPOINT_BEGIN ){
73623     if( db->nVdbeWrite>0 ){
73624       /* A new savepoint cannot be created if there are active write
73625       ** statements (i.e. open read/write incremental blob handles).
73626       */
73627       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
73628         "SQL statements in progress");
73629       rc = SQLITE_BUSY;
73630     }else{
73631       nName = sqlite3Strlen30(zName);
73632 
73633 #ifndef SQLITE_OMIT_VIRTUALTABLE
73634       /* This call is Ok even if this savepoint is actually a transaction
73635       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
73636       ** If this is a transaction savepoint being opened, it is guaranteed
73637       ** that the db->aVTrans[] array is empty.  */
73638       assert( db->autoCommit==0 || db->nVTrans==0 );
73639       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
73640                                 db->nStatement+db->nSavepoint);
73641       if( rc!=SQLITE_OK ) goto abort_due_to_error;
73642 #endif
73643 
73644       /* Create a new savepoint structure. */
73645       pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
73646       if( pNew ){
73647         pNew->zName = (char *)&pNew[1];
73648         memcpy(pNew->zName, zName, nName+1);
73649 
73650         /* If there is no open transaction, then mark this as a special
73651         ** "transaction savepoint". */
73652         if( db->autoCommit ){
73653           db->autoCommit = 0;
73654           db->isTransactionSavepoint = 1;
73655         }else{
73656           db->nSavepoint++;
73657         }
73658 
73659         /* Link the new savepoint into the database handle's list. */
73660         pNew->pNext = db->pSavepoint;
73661         db->pSavepoint = pNew;
73662         pNew->nDeferredCons = db->nDeferredCons;
73663         pNew->nDeferredImmCons = db->nDeferredImmCons;
73664       }
73665     }
73666   }else{
73667     iSavepoint = 0;
73668 
73669     /* Find the named savepoint. If there is no such savepoint, then an
73670     ** an error is returned to the user.  */
73671     for(
73672       pSavepoint = db->pSavepoint;
73673       pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
73674       pSavepoint = pSavepoint->pNext
73675     ){
73676       iSavepoint++;
73677     }
73678     if( !pSavepoint ){
73679       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
73680       rc = SQLITE_ERROR;
73681     }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
73682       /* It is not possible to release (commit) a savepoint if there are
73683       ** active write statements.
73684       */
73685       sqlite3SetString(&p->zErrMsg, db,
73686         "cannot release savepoint - SQL statements in progress"
73687       );
73688       rc = SQLITE_BUSY;
73689     }else{
73690 
73691       /* Determine whether or not this is a transaction savepoint. If so,
73692       ** and this is a RELEASE command, then the current transaction
73693       ** is committed.
73694       */
73695       int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
73696       if( isTransaction && p1==SAVEPOINT_RELEASE ){
73697         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
73698           goto vdbe_return;
73699         }
73700         db->autoCommit = 1;
73701         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
73702           p->pc = (int)(pOp - aOp);
73703           db->autoCommit = 0;
73704           p->rc = rc = SQLITE_BUSY;
73705           goto vdbe_return;
73706         }
73707         db->isTransactionSavepoint = 0;
73708         rc = p->rc;
73709       }else{
73710         int isSchemaChange;
73711         iSavepoint = db->nSavepoint - iSavepoint - 1;
73712         if( p1==SAVEPOINT_ROLLBACK ){
73713           isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
73714           for(ii=0; ii<db->nDb; ii++){
73715             rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
73716                                        SQLITE_ABORT_ROLLBACK,
73717                                        isSchemaChange==0);
73718             if( rc!=SQLITE_OK ) goto abort_due_to_error;
73719           }
73720         }else{
73721           isSchemaChange = 0;
73722         }
73723         for(ii=0; ii<db->nDb; ii++){
73724           rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
73725           if( rc!=SQLITE_OK ){
73726             goto abort_due_to_error;
73727           }
73728         }
73729         if( isSchemaChange ){
73730           sqlite3ExpirePreparedStatements(db);
73731           sqlite3ResetAllSchemasOfConnection(db);
73732           db->flags = (db->flags | SQLITE_InternChanges);
73733         }
73734       }
73735 
73736       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
73737       ** savepoints nested inside of the savepoint being operated on. */
73738       while( db->pSavepoint!=pSavepoint ){
73739         pTmp = db->pSavepoint;
73740         db->pSavepoint = pTmp->pNext;
73741         sqlite3DbFree(db, pTmp);
73742         db->nSavepoint--;
73743       }
73744 
73745       /* If it is a RELEASE, then destroy the savepoint being operated on
73746       ** too. If it is a ROLLBACK TO, then set the number of deferred
73747       ** constraint violations present in the database to the value stored
73748       ** when the savepoint was created.  */
73749       if( p1==SAVEPOINT_RELEASE ){
73750         assert( pSavepoint==db->pSavepoint );
73751         db->pSavepoint = pSavepoint->pNext;
73752         sqlite3DbFree(db, pSavepoint);
73753         if( !isTransaction ){
73754           db->nSavepoint--;
73755         }
73756       }else{
73757         db->nDeferredCons = pSavepoint->nDeferredCons;
73758         db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
73759       }
73760 
73761       if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
73762         rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
73763         if( rc!=SQLITE_OK ) goto abort_due_to_error;
73764       }
73765     }
73766   }
73767 
73768   break;
73769 }
73770 
73771 /* Opcode: AutoCommit P1 P2 * * *
73772 **
73773 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
73774 ** back any currently active btree transactions. If there are any active
73775 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
73776 ** there are active writing VMs or active VMs that use shared cache.
73777 **
73778 ** This instruction causes the VM to halt.
73779 */
73780 case OP_AutoCommit: {
73781   int desiredAutoCommit;
73782   int iRollback;
73783   int turnOnAC;
73784 
73785   desiredAutoCommit = pOp->p1;
73786   iRollback = pOp->p2;
73787   turnOnAC = desiredAutoCommit && !db->autoCommit;
73788   assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
73789   assert( desiredAutoCommit==1 || iRollback==0 );
73790   assert( db->nVdbeActive>0 );  /* At least this one VM is active */
73791   assert( p->bIsReader );
73792 
73793 #if 0
73794   if( turnOnAC && iRollback && db->nVdbeActive>1 ){
73795     /* If this instruction implements a ROLLBACK and other VMs are
73796     ** still running, and a transaction is active, return an error indicating
73797     ** that the other VMs must complete first.
73798     */
73799     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
73800         "SQL statements in progress");
73801     rc = SQLITE_BUSY;
73802   }else
73803 #endif
73804   if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
73805     /* If this instruction implements a COMMIT and other VMs are writing
73806     ** return an error indicating that the other VMs must complete first.
73807     */
73808     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
73809         "SQL statements in progress");
73810     rc = SQLITE_BUSY;
73811   }else if( desiredAutoCommit!=db->autoCommit ){
73812     if( iRollback ){
73813       assert( desiredAutoCommit==1 );
73814       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
73815       db->autoCommit = 1;
73816     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
73817       goto vdbe_return;
73818     }else{
73819       db->autoCommit = (u8)desiredAutoCommit;
73820       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
73821         p->pc = (int)(pOp - aOp);
73822         db->autoCommit = (u8)(1-desiredAutoCommit);
73823         p->rc = rc = SQLITE_BUSY;
73824         goto vdbe_return;
73825       }
73826     }
73827     assert( db->nStatement==0 );
73828     sqlite3CloseSavepoints(db);
73829     if( p->rc==SQLITE_OK ){
73830       rc = SQLITE_DONE;
73831     }else{
73832       rc = SQLITE_ERROR;
73833     }
73834     goto vdbe_return;
73835   }else{
73836     sqlite3SetString(&p->zErrMsg, db,
73837         (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
73838         (iRollback)?"cannot rollback - no transaction is active":
73839                    "cannot commit - no transaction is active"));
73840 
73841     rc = SQLITE_ERROR;
73842   }
73843   break;
73844 }
73845 
73846 /* Opcode: Transaction P1 P2 P3 P4 P5
73847 **
73848 ** Begin a transaction on database P1 if a transaction is not already
73849 ** active.
73850 ** If P2 is non-zero, then a write-transaction is started, or if a
73851 ** read-transaction is already active, it is upgraded to a write-transaction.
73852 ** If P2 is zero, then a read-transaction is started.
73853 **
73854 ** P1 is the index of the database file on which the transaction is
73855 ** started.  Index 0 is the main database file and index 1 is the
73856 ** file used for temporary tables.  Indices of 2 or more are used for
73857 ** attached databases.
73858 **
73859 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
73860 ** true (this flag is set if the Vdbe may modify more than one row and may
73861 ** throw an ABORT exception), a statement transaction may also be opened.
73862 ** More specifically, a statement transaction is opened iff the database
73863 ** connection is currently not in autocommit mode, or if there are other
73864 ** active statements. A statement transaction allows the changes made by this
73865 ** VDBE to be rolled back after an error without having to roll back the
73866 ** entire transaction. If no error is encountered, the statement transaction
73867 ** will automatically commit when the VDBE halts.
73868 **
73869 ** If P5!=0 then this opcode also checks the schema cookie against P3
73870 ** and the schema generation counter against P4.
73871 ** The cookie changes its value whenever the database schema changes.
73872 ** This operation is used to detect when that the cookie has changed
73873 ** and that the current process needs to reread the schema.  If the schema
73874 ** cookie in P3 differs from the schema cookie in the database header or
73875 ** if the schema generation counter in P4 differs from the current
73876 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
73877 ** halts.  The sqlite3_step() wrapper function might then reprepare the
73878 ** statement and rerun it from the beginning.
73879 */
73880 case OP_Transaction: {
73881   Btree *pBt;
73882   int iMeta;
73883   int iGen;
73884 
73885   assert( p->bIsReader );
73886   assert( p->readOnly==0 || pOp->p2==0 );
73887   assert( pOp->p1>=0 && pOp->p1<db->nDb );
73888   assert( DbMaskTest(p->btreeMask, pOp->p1) );
73889   if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
73890     rc = SQLITE_READONLY;
73891     goto abort_due_to_error;
73892   }
73893   pBt = db->aDb[pOp->p1].pBt;
73894 
73895   if( pBt ){
73896     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
73897     if( rc==SQLITE_BUSY ){
73898       p->pc = (int)(pOp - aOp);
73899       p->rc = rc = SQLITE_BUSY;
73900       goto vdbe_return;
73901     }
73902     if( rc!=SQLITE_OK ){
73903       goto abort_due_to_error;
73904     }
73905 
73906     if( pOp->p2 && p->usesStmtJournal
73907      && (db->autoCommit==0 || db->nVdbeRead>1)
73908     ){
73909       assert( sqlite3BtreeIsInTrans(pBt) );
73910       if( p->iStatement==0 ){
73911         assert( db->nStatement>=0 && db->nSavepoint>=0 );
73912         db->nStatement++;
73913         p->iStatement = db->nSavepoint + db->nStatement;
73914       }
73915 
73916       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
73917       if( rc==SQLITE_OK ){
73918         rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
73919       }
73920 
73921       /* Store the current value of the database handles deferred constraint
73922       ** counter. If the statement transaction needs to be rolled back,
73923       ** the value of this counter needs to be restored too.  */
73924       p->nStmtDefCons = db->nDeferredCons;
73925       p->nStmtDefImmCons = db->nDeferredImmCons;
73926     }
73927 
73928     /* Gather the schema version number for checking:
73929     ** IMPLEMENTATION-OF: R-32195-19465 The schema version is used by SQLite
73930     ** each time a query is executed to ensure that the internal cache of the
73931     ** schema used when compiling the SQL query matches the schema of the
73932     ** database against which the compiled query is actually executed.
73933     */
73934     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
73935     iGen = db->aDb[pOp->p1].pSchema->iGeneration;
73936   }else{
73937     iGen = iMeta = 0;
73938   }
73939   assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
73940   if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
73941     sqlite3DbFree(db, p->zErrMsg);
73942     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
73943     /* If the schema-cookie from the database file matches the cookie
73944     ** stored with the in-memory representation of the schema, do
73945     ** not reload the schema from the database file.
73946     **
73947     ** If virtual-tables are in use, this is not just an optimization.
73948     ** Often, v-tables store their data in other SQLite tables, which
73949     ** are queried from within xNext() and other v-table methods using
73950     ** prepared queries. If such a query is out-of-date, we do not want to
73951     ** discard the database schema, as the user code implementing the
73952     ** v-table would have to be ready for the sqlite3_vtab structure itself
73953     ** to be invalidated whenever sqlite3_step() is called from within
73954     ** a v-table method.
73955     */
73956     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
73957       sqlite3ResetOneSchema(db, pOp->p1);
73958     }
73959     p->expired = 1;
73960     rc = SQLITE_SCHEMA;
73961   }
73962   break;
73963 }
73964 
73965 /* Opcode: ReadCookie P1 P2 P3 * *
73966 **
73967 ** Read cookie number P3 from database P1 and write it into register P2.
73968 ** P3==1 is the schema version.  P3==2 is the database format.
73969 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
73970 ** the main database file and P1==1 is the database file used to store
73971 ** temporary tables.
73972 **
73973 ** There must be a read-lock on the database (either a transaction
73974 ** must be started or there must be an open cursor) before
73975 ** executing this instruction.
73976 */
73977 case OP_ReadCookie: {               /* out2 */
73978   int iMeta;
73979   int iDb;
73980   int iCookie;
73981 
73982   assert( p->bIsReader );
73983   iDb = pOp->p1;
73984   iCookie = pOp->p3;
73985   assert( pOp->p3<SQLITE_N_BTREE_META );
73986   assert( iDb>=0 && iDb<db->nDb );
73987   assert( db->aDb[iDb].pBt!=0 );
73988   assert( DbMaskTest(p->btreeMask, iDb) );
73989 
73990   sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
73991   pOut = out2Prerelease(p, pOp);
73992   pOut->u.i = iMeta;
73993   break;
73994 }
73995 
73996 /* Opcode: SetCookie P1 P2 P3 * *
73997 **
73998 ** Write the content of register P3 (interpreted as an integer)
73999 ** into cookie number P2 of database P1.  P2==1 is the schema version.
74000 ** P2==2 is the database format. P2==3 is the recommended pager cache
74001 ** size, and so forth.  P1==0 is the main database file and P1==1 is the
74002 ** database file used to store temporary tables.
74003 **
74004 ** A transaction must be started before executing this opcode.
74005 */
74006 case OP_SetCookie: {       /* in3 */
74007   Db *pDb;
74008   assert( pOp->p2<SQLITE_N_BTREE_META );
74009   assert( pOp->p1>=0 && pOp->p1<db->nDb );
74010   assert( DbMaskTest(p->btreeMask, pOp->p1) );
74011   assert( p->readOnly==0 );
74012   pDb = &db->aDb[pOp->p1];
74013   assert( pDb->pBt!=0 );
74014   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
74015   pIn3 = &aMem[pOp->p3];
74016   sqlite3VdbeMemIntegerify(pIn3);
74017   /* See note about index shifting on OP_ReadCookie */
74018   rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
74019   if( pOp->p2==BTREE_SCHEMA_VERSION ){
74020     /* When the schema cookie changes, record the new cookie internally */
74021     pDb->pSchema->schema_cookie = (int)pIn3->u.i;
74022     db->flags |= SQLITE_InternChanges;
74023   }else if( pOp->p2==BTREE_FILE_FORMAT ){
74024     /* Record changes in the file format */
74025     pDb->pSchema->file_format = (u8)pIn3->u.i;
74026   }
74027   if( pOp->p1==1 ){
74028     /* Invalidate all prepared statements whenever the TEMP database
74029     ** schema is changed.  Ticket #1644 */
74030     sqlite3ExpirePreparedStatements(db);
74031     p->expired = 0;
74032   }
74033   break;
74034 }
74035 
74036 /* Opcode: OpenRead P1 P2 P3 P4 P5
74037 ** Synopsis: root=P2 iDb=P3
74038 **
74039 ** Open a read-only cursor for the database table whose root page is
74040 ** P2 in a database file.  The database file is determined by P3.
74041 ** P3==0 means the main database, P3==1 means the database used for
74042 ** temporary tables, and P3>1 means used the corresponding attached
74043 ** database.  Give the new cursor an identifier of P1.  The P1
74044 ** values need not be contiguous but all P1 values should be small integers.
74045 ** It is an error for P1 to be negative.
74046 **
74047 ** If P5!=0 then use the content of register P2 as the root page, not
74048 ** the value of P2 itself.
74049 **
74050 ** There will be a read lock on the database whenever there is an
74051 ** open cursor.  If the database was unlocked prior to this instruction
74052 ** then a read lock is acquired as part of this instruction.  A read
74053 ** lock allows other processes to read the database but prohibits
74054 ** any other process from modifying the database.  The read lock is
74055 ** released when all cursors are closed.  If this instruction attempts
74056 ** to get a read lock but fails, the script terminates with an
74057 ** SQLITE_BUSY error code.
74058 **
74059 ** The P4 value may be either an integer (P4_INT32) or a pointer to
74060 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
74061 ** structure, then said structure defines the content and collating
74062 ** sequence of the index being opened. Otherwise, if P4 is an integer
74063 ** value, it is set to the number of columns in the table.
74064 **
74065 ** See also: OpenWrite, ReopenIdx
74066 */
74067 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
74068 ** Synopsis: root=P2 iDb=P3
74069 **
74070 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
74071 ** checks to see if the cursor on P1 is already open with a root page
74072 ** number of P2 and if it is this opcode becomes a no-op.  In other words,
74073 ** if the cursor is already open, do not reopen it.
74074 **
74075 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
74076 ** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
74077 ** every other ReopenIdx or OpenRead for the same cursor number.
74078 **
74079 ** See the OpenRead opcode documentation for additional information.
74080 */
74081 /* Opcode: OpenWrite P1 P2 P3 P4 P5
74082 ** Synopsis: root=P2 iDb=P3
74083 **
74084 ** Open a read/write cursor named P1 on the table or index whose root
74085 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
74086 ** root page.
74087 **
74088 ** The P4 value may be either an integer (P4_INT32) or a pointer to
74089 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
74090 ** structure, then said structure defines the content and collating
74091 ** sequence of the index being opened. Otherwise, if P4 is an integer
74092 ** value, it is set to the number of columns in the table, or to the
74093 ** largest index of any column of the table that is actually used.
74094 **
74095 ** This instruction works just like OpenRead except that it opens the cursor
74096 ** in read/write mode.  For a given table, there can be one or more read-only
74097 ** cursors or a single read/write cursor but not both.
74098 **
74099 ** See also OpenRead.
74100 */
74101 case OP_ReopenIdx: {
74102   int nField;
74103   KeyInfo *pKeyInfo;
74104   int p2;
74105   int iDb;
74106   int wrFlag;
74107   Btree *pX;
74108   VdbeCursor *pCur;
74109   Db *pDb;
74110 
74111   assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
74112   assert( pOp->p4type==P4_KEYINFO );
74113   pCur = p->apCsr[pOp->p1];
74114   if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
74115     assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
74116     goto open_cursor_set_hints;
74117   }
74118   /* If the cursor is not currently open or is open on a different
74119   ** index, then fall through into OP_OpenRead to force a reopen */
74120 case OP_OpenRead:
74121 case OP_OpenWrite:
74122 
74123   assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR|OPFLAG_SEEKEQ))==pOp->p5 );
74124   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
74125   assert( p->bIsReader );
74126   assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
74127           || p->readOnly==0 );
74128 
74129   if( p->expired ){
74130     rc = SQLITE_ABORT_ROLLBACK;
74131     break;
74132   }
74133 
74134   nField = 0;
74135   pKeyInfo = 0;
74136   p2 = pOp->p2;
74137   iDb = pOp->p3;
74138   assert( iDb>=0 && iDb<db->nDb );
74139   assert( DbMaskTest(p->btreeMask, iDb) );
74140   pDb = &db->aDb[iDb];
74141   pX = pDb->pBt;
74142   assert( pX!=0 );
74143   if( pOp->opcode==OP_OpenWrite ){
74144     wrFlag = 1;
74145     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
74146     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
74147       p->minWriteFileFormat = pDb->pSchema->file_format;
74148     }
74149   }else{
74150     wrFlag = 0;
74151   }
74152   if( pOp->p5 & OPFLAG_P2ISREG ){
74153     assert( p2>0 );
74154     assert( p2<=(p->nMem-p->nCursor) );
74155     pIn2 = &aMem[p2];
74156     assert( memIsValid(pIn2) );
74157     assert( (pIn2->flags & MEM_Int)!=0 );
74158     sqlite3VdbeMemIntegerify(pIn2);
74159     p2 = (int)pIn2->u.i;
74160     /* The p2 value always comes from a prior OP_CreateTable opcode and
74161     ** that opcode will always set the p2 value to 2 or more or else fail.
74162     ** If there were a failure, the prepared statement would have halted
74163     ** before reaching this instruction. */
74164     if( NEVER(p2<2) ) {
74165       rc = SQLITE_CORRUPT_BKPT;
74166       goto abort_due_to_error;
74167     }
74168   }
74169   if( pOp->p4type==P4_KEYINFO ){
74170     pKeyInfo = pOp->p4.pKeyInfo;
74171     assert( pKeyInfo->enc==ENC(db) );
74172     assert( pKeyInfo->db==db );
74173     nField = pKeyInfo->nField+pKeyInfo->nXField;
74174   }else if( pOp->p4type==P4_INT32 ){
74175     nField = pOp->p4.i;
74176   }
74177   assert( pOp->p1>=0 );
74178   assert( nField>=0 );
74179   testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
74180   pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
74181   if( pCur==0 ) goto no_mem;
74182   pCur->nullRow = 1;
74183   pCur->isOrdered = 1;
74184   pCur->pgnoRoot = p2;
74185   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
74186   pCur->pKeyInfo = pKeyInfo;
74187   /* Set the VdbeCursor.isTable variable. Previous versions of
74188   ** SQLite used to check if the root-page flags were sane at this point
74189   ** and report database corruption if they were not, but this check has
74190   ** since moved into the btree layer.  */
74191   pCur->isTable = pOp->p4type!=P4_KEYINFO;
74192 
74193 open_cursor_set_hints:
74194   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
74195   assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
74196   sqlite3BtreeCursorHints(pCur->pCursor,
74197                           (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
74198   break;
74199 }
74200 
74201 /* Opcode: OpenEphemeral P1 P2 * P4 P5
74202 ** Synopsis: nColumn=P2
74203 **
74204 ** Open a new cursor P1 to a transient table.
74205 ** The cursor is always opened read/write even if
74206 ** the main database is read-only.  The ephemeral
74207 ** table is deleted automatically when the cursor is closed.
74208 **
74209 ** P2 is the number of columns in the ephemeral table.
74210 ** The cursor points to a BTree table if P4==0 and to a BTree index
74211 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
74212 ** that defines the format of keys in the index.
74213 **
74214 ** The P5 parameter can be a mask of the BTREE_* flags defined
74215 ** in btree.h.  These flags control aspects of the operation of
74216 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
74217 ** added automatically.
74218 */
74219 /* Opcode: OpenAutoindex P1 P2 * P4 *
74220 ** Synopsis: nColumn=P2
74221 **
74222 ** This opcode works the same as OP_OpenEphemeral.  It has a
74223 ** different name to distinguish its use.  Tables created using
74224 ** by this opcode will be used for automatically created transient
74225 ** indices in joins.
74226 */
74227 case OP_OpenAutoindex:
74228 case OP_OpenEphemeral: {
74229   VdbeCursor *pCx;
74230   KeyInfo *pKeyInfo;
74231 
74232   static const int vfsFlags =
74233       SQLITE_OPEN_READWRITE |
74234       SQLITE_OPEN_CREATE |
74235       SQLITE_OPEN_EXCLUSIVE |
74236       SQLITE_OPEN_DELETEONCLOSE |
74237       SQLITE_OPEN_TRANSIENT_DB;
74238   assert( pOp->p1>=0 );
74239   assert( pOp->p2>=0 );
74240   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
74241   if( pCx==0 ) goto no_mem;
74242   pCx->nullRow = 1;
74243   pCx->isEphemeral = 1;
74244   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
74245                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
74246   if( rc==SQLITE_OK ){
74247     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
74248   }
74249   if( rc==SQLITE_OK ){
74250     /* If a transient index is required, create it by calling
74251     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
74252     ** opening it. If a transient table is required, just use the
74253     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
74254     */
74255     if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
74256       int pgno;
74257       assert( pOp->p4type==P4_KEYINFO );
74258       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
74259       if( rc==SQLITE_OK ){
74260         assert( pgno==MASTER_ROOT+1 );
74261         assert( pKeyInfo->db==db );
74262         assert( pKeyInfo->enc==ENC(db) );
74263         pCx->pKeyInfo = pKeyInfo;
74264         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
74265       }
74266       pCx->isTable = 0;
74267     }else{
74268       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
74269       pCx->isTable = 1;
74270     }
74271   }
74272   pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
74273   break;
74274 }
74275 
74276 /* Opcode: SorterOpen P1 P2 P3 P4 *
74277 **
74278 ** This opcode works like OP_OpenEphemeral except that it opens
74279 ** a transient index that is specifically designed to sort large
74280 ** tables using an external merge-sort algorithm.
74281 **
74282 ** If argument P3 is non-zero, then it indicates that the sorter may
74283 ** assume that a stable sort considering the first P3 fields of each
74284 ** key is sufficient to produce the required results.
74285 */
74286 case OP_SorterOpen: {
74287   VdbeCursor *pCx;
74288 
74289   assert( pOp->p1>=0 );
74290   assert( pOp->p2>=0 );
74291   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
74292   if( pCx==0 ) goto no_mem;
74293   pCx->pKeyInfo = pOp->p4.pKeyInfo;
74294   assert( pCx->pKeyInfo->db==db );
74295   assert( pCx->pKeyInfo->enc==ENC(db) );
74296   rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
74297   break;
74298 }
74299 
74300 /* Opcode: SequenceTest P1 P2 * * *
74301 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
74302 **
74303 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
74304 ** to P2. Regardless of whether or not the jump is taken, increment the
74305 ** the sequence value.
74306 */
74307 case OP_SequenceTest: {
74308   VdbeCursor *pC;
74309   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74310   pC = p->apCsr[pOp->p1];
74311   assert( pC->pSorter );
74312   if( (pC->seqCount++)==0 ){
74313     goto jump_to_p2;
74314   }
74315   break;
74316 }
74317 
74318 /* Opcode: OpenPseudo P1 P2 P3 * *
74319 ** Synopsis: P3 columns in r[P2]
74320 **
74321 ** Open a new cursor that points to a fake table that contains a single
74322 ** row of data.  The content of that one row is the content of memory
74323 ** register P2.  In other words, cursor P1 becomes an alias for the
74324 ** MEM_Blob content contained in register P2.
74325 **
74326 ** A pseudo-table created by this opcode is used to hold a single
74327 ** row output from the sorter so that the row can be decomposed into
74328 ** individual columns using the OP_Column opcode.  The OP_Column opcode
74329 ** is the only cursor opcode that works with a pseudo-table.
74330 **
74331 ** P3 is the number of fields in the records that will be stored by
74332 ** the pseudo-table.
74333 */
74334 case OP_OpenPseudo: {
74335   VdbeCursor *pCx;
74336 
74337   assert( pOp->p1>=0 );
74338   assert( pOp->p3>=0 );
74339   pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
74340   if( pCx==0 ) goto no_mem;
74341   pCx->nullRow = 1;
74342   pCx->pseudoTableReg = pOp->p2;
74343   pCx->isTable = 1;
74344   assert( pOp->p5==0 );
74345   break;
74346 }
74347 
74348 /* Opcode: Close P1 * * * *
74349 **
74350 ** Close a cursor previously opened as P1.  If P1 is not
74351 ** currently open, this instruction is a no-op.
74352 */
74353 case OP_Close: {
74354   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74355   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
74356   p->apCsr[pOp->p1] = 0;
74357   break;
74358 }
74359 
74360 /* Opcode: SeekGE P1 P2 P3 P4 *
74361 ** Synopsis: key=r[P3@P4]
74362 **
74363 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
74364 ** use the value in register P3 as the key.  If cursor P1 refers
74365 ** to an SQL index, then P3 is the first in an array of P4 registers
74366 ** that are used as an unpacked index key.
74367 **
74368 ** Reposition cursor P1 so that  it points to the smallest entry that
74369 ** is greater than or equal to the key value. If there are no records
74370 ** greater than or equal to the key and P2 is not zero, then jump to P2.
74371 **
74372 ** This opcode leaves the cursor configured to move in forward order,
74373 ** from the beginning toward the end.  In other words, the cursor is
74374 ** configured to use Next, not Prev.
74375 **
74376 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
74377 */
74378 /* Opcode: SeekGT P1 P2 P3 P4 *
74379 ** Synopsis: key=r[P3@P4]
74380 **
74381 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
74382 ** use the value in register P3 as a key. If cursor P1 refers
74383 ** to an SQL index, then P3 is the first in an array of P4 registers
74384 ** that are used as an unpacked index key.
74385 **
74386 ** Reposition cursor P1 so that  it points to the smallest entry that
74387 ** is greater than the key value. If there are no records greater than
74388 ** the key and P2 is not zero, then jump to P2.
74389 **
74390 ** This opcode leaves the cursor configured to move in forward order,
74391 ** from the beginning toward the end.  In other words, the cursor is
74392 ** configured to use Next, not Prev.
74393 **
74394 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
74395 */
74396 /* Opcode: SeekLT P1 P2 P3 P4 *
74397 ** Synopsis: key=r[P3@P4]
74398 **
74399 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
74400 ** use the value in register P3 as a key. If cursor P1 refers
74401 ** to an SQL index, then P3 is the first in an array of P4 registers
74402 ** that are used as an unpacked index key.
74403 **
74404 ** Reposition cursor P1 so that  it points to the largest entry that
74405 ** is less than the key value. If there are no records less than
74406 ** the key and P2 is not zero, then jump to P2.
74407 **
74408 ** This opcode leaves the cursor configured to move in reverse order,
74409 ** from the end toward the beginning.  In other words, the cursor is
74410 ** configured to use Prev, not Next.
74411 **
74412 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
74413 */
74414 /* Opcode: SeekLE P1 P2 P3 P4 *
74415 ** Synopsis: key=r[P3@P4]
74416 **
74417 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
74418 ** use the value in register P3 as a key. If cursor P1 refers
74419 ** to an SQL index, then P3 is the first in an array of P4 registers
74420 ** that are used as an unpacked index key.
74421 **
74422 ** Reposition cursor P1 so that it points to the largest entry that
74423 ** is less than or equal to the key value. If there are no records
74424 ** less than or equal to the key and P2 is not zero, then jump to P2.
74425 **
74426 ** This opcode leaves the cursor configured to move in reverse order,
74427 ** from the end toward the beginning.  In other words, the cursor is
74428 ** configured to use Prev, not Next.
74429 **
74430 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
74431 */
74432 case OP_SeekLT:         /* jump, in3 */
74433 case OP_SeekLE:         /* jump, in3 */
74434 case OP_SeekGE:         /* jump, in3 */
74435 case OP_SeekGT: {       /* jump, in3 */
74436   int res;
74437   int oc;
74438   VdbeCursor *pC;
74439   UnpackedRecord r;
74440   int nField;
74441   i64 iKey;      /* The rowid we are to seek to */
74442 
74443   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74444   assert( pOp->p2!=0 );
74445   pC = p->apCsr[pOp->p1];
74446   assert( pC!=0 );
74447   assert( pC->pseudoTableReg==0 );
74448   assert( OP_SeekLE == OP_SeekLT+1 );
74449   assert( OP_SeekGE == OP_SeekLT+2 );
74450   assert( OP_SeekGT == OP_SeekLT+3 );
74451   assert( pC->isOrdered );
74452   assert( pC->pCursor!=0 );
74453   oc = pOp->opcode;
74454   pC->nullRow = 0;
74455 #ifdef SQLITE_DEBUG
74456   pC->seekOp = pOp->opcode;
74457 #endif
74458 
74459   /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
74460   ** OP_SeekLE opcodes are allowed, and these must be immediately followed
74461   ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
74462   */
74463 #ifdef SQLITE_DEBUG
74464   if( sqlite3BtreeCursorHasHint(pC->pCursor, BTREE_SEEK_EQ) ){
74465     assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
74466     assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
74467     assert( pOp[1].p1==pOp[0].p1 );
74468     assert( pOp[1].p2==pOp[0].p2 );
74469     assert( pOp[1].p3==pOp[0].p3 );
74470     assert( pOp[1].p4.i==pOp[0].p4.i );
74471   }
74472 #endif
74473 
74474   if( pC->isTable ){
74475     /* The input value in P3 might be of any type: integer, real, string,
74476     ** blob, or NULL.  But it needs to be an integer before we can do
74477     ** the seek, so convert it. */
74478     pIn3 = &aMem[pOp->p3];
74479     if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
74480       applyNumericAffinity(pIn3, 0);
74481     }
74482     iKey = sqlite3VdbeIntValue(pIn3);
74483 
74484     /* If the P3 value could not be converted into an integer without
74485     ** loss of information, then special processing is required... */
74486     if( (pIn3->flags & MEM_Int)==0 ){
74487       if( (pIn3->flags & MEM_Real)==0 ){
74488         /* If the P3 value cannot be converted into any kind of a number,
74489         ** then the seek is not possible, so jump to P2 */
74490         VdbeBranchTaken(1,2); goto jump_to_p2;
74491         break;
74492       }
74493 
74494       /* If the approximation iKey is larger than the actual real search
74495       ** term, substitute >= for > and < for <=. e.g. if the search term
74496       ** is 4.9 and the integer approximation 5:
74497       **
74498       **        (x >  4.9)    ->     (x >= 5)
74499       **        (x <= 4.9)    ->     (x <  5)
74500       */
74501       if( pIn3->u.r<(double)iKey ){
74502         assert( OP_SeekGE==(OP_SeekGT-1) );
74503         assert( OP_SeekLT==(OP_SeekLE-1) );
74504         assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
74505         if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
74506       }
74507 
74508       /* If the approximation iKey is smaller than the actual real search
74509       ** term, substitute <= for < and > for >=.  */
74510       else if( pIn3->u.r>(double)iKey ){
74511         assert( OP_SeekLE==(OP_SeekLT+1) );
74512         assert( OP_SeekGT==(OP_SeekGE+1) );
74513         assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
74514         if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
74515       }
74516     }
74517     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
74518     pC->movetoTarget = iKey;  /* Used by OP_Delete */
74519     if( rc!=SQLITE_OK ){
74520       goto abort_due_to_error;
74521     }
74522   }else{
74523     nField = pOp->p4.i;
74524     assert( pOp->p4type==P4_INT32 );
74525     assert( nField>0 );
74526     r.pKeyInfo = pC->pKeyInfo;
74527     r.nField = (u16)nField;
74528 
74529     /* The next line of code computes as follows, only faster:
74530     **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
74531     **     r.default_rc = -1;
74532     **   }else{
74533     **     r.default_rc = +1;
74534     **   }
74535     */
74536     r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
74537     assert( oc!=OP_SeekGT || r.default_rc==-1 );
74538     assert( oc!=OP_SeekLE || r.default_rc==-1 );
74539     assert( oc!=OP_SeekGE || r.default_rc==+1 );
74540     assert( oc!=OP_SeekLT || r.default_rc==+1 );
74541 
74542     r.aMem = &aMem[pOp->p3];
74543 #ifdef SQLITE_DEBUG
74544     { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
74545 #endif
74546     ExpandBlob(r.aMem);
74547     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
74548     if( rc!=SQLITE_OK ){
74549       goto abort_due_to_error;
74550     }
74551   }
74552   pC->deferredMoveto = 0;
74553   pC->cacheStatus = CACHE_STALE;
74554 #ifdef SQLITE_TEST
74555   sqlite3_search_count++;
74556 #endif
74557   if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
74558     if( res<0 || (res==0 && oc==OP_SeekGT) ){
74559       res = 0;
74560       rc = sqlite3BtreeNext(pC->pCursor, &res);
74561       if( rc!=SQLITE_OK ) goto abort_due_to_error;
74562     }else{
74563       res = 0;
74564     }
74565   }else{
74566     assert( oc==OP_SeekLT || oc==OP_SeekLE );
74567     if( res>0 || (res==0 && oc==OP_SeekLT) ){
74568       res = 0;
74569       rc = sqlite3BtreePrevious(pC->pCursor, &res);
74570       if( rc!=SQLITE_OK ) goto abort_due_to_error;
74571     }else{
74572       /* res might be negative because the table is empty.  Check to
74573       ** see if this is the case.
74574       */
74575       res = sqlite3BtreeEof(pC->pCursor);
74576     }
74577   }
74578   assert( pOp->p2>0 );
74579   VdbeBranchTaken(res!=0,2);
74580   if( res ){
74581     goto jump_to_p2;
74582   }
74583   break;
74584 }
74585 
74586 /* Opcode: Seek P1 P2 * * *
74587 ** Synopsis:  intkey=r[P2]
74588 **
74589 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
74590 ** for P1 to move so that it points to the rowid given by P2.
74591 **
74592 ** This is actually a deferred seek.  Nothing actually happens until
74593 ** the cursor is used to read a record.  That way, if no reads
74594 ** occur, no unnecessary I/O happens.
74595 */
74596 case OP_Seek: {    /* in2 */
74597   VdbeCursor *pC;
74598 
74599   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74600   pC = p->apCsr[pOp->p1];
74601   assert( pC!=0 );
74602   assert( pC->pCursor!=0 );
74603   assert( pC->isTable );
74604   pC->nullRow = 0;
74605   pIn2 = &aMem[pOp->p2];
74606   pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
74607   pC->deferredMoveto = 1;
74608   break;
74609 }
74610 
74611 
74612 /* Opcode: Found P1 P2 P3 P4 *
74613 ** Synopsis: key=r[P3@P4]
74614 **
74615 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
74616 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
74617 ** record.
74618 **
74619 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
74620 ** is a prefix of any entry in P1 then a jump is made to P2 and
74621 ** P1 is left pointing at the matching entry.
74622 **
74623 ** This operation leaves the cursor in a state where it can be
74624 ** advanced in the forward direction.  The Next instruction will work,
74625 ** but not the Prev instruction.
74626 **
74627 ** See also: NotFound, NoConflict, NotExists. SeekGe
74628 */
74629 /* Opcode: NotFound P1 P2 P3 P4 *
74630 ** Synopsis: key=r[P3@P4]
74631 **
74632 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
74633 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
74634 ** record.
74635 **
74636 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
74637 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
74638 ** does contain an entry whose prefix matches the P3/P4 record then control
74639 ** falls through to the next instruction and P1 is left pointing at the
74640 ** matching entry.
74641 **
74642 ** This operation leaves the cursor in a state where it cannot be
74643 ** advanced in either direction.  In other words, the Next and Prev
74644 ** opcodes do not work after this operation.
74645 **
74646 ** See also: Found, NotExists, NoConflict
74647 */
74648 /* Opcode: NoConflict P1 P2 P3 P4 *
74649 ** Synopsis: key=r[P3@P4]
74650 **
74651 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
74652 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
74653 ** record.
74654 **
74655 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
74656 ** contains any NULL value, jump immediately to P2.  If all terms of the
74657 ** record are not-NULL then a check is done to determine if any row in the
74658 ** P1 index btree has a matching key prefix.  If there are no matches, jump
74659 ** immediately to P2.  If there is a match, fall through and leave the P1
74660 ** cursor pointing to the matching row.
74661 **
74662 ** This opcode is similar to OP_NotFound with the exceptions that the
74663 ** branch is always taken if any part of the search key input is NULL.
74664 **
74665 ** This operation leaves the cursor in a state where it cannot be
74666 ** advanced in either direction.  In other words, the Next and Prev
74667 ** opcodes do not work after this operation.
74668 **
74669 ** See also: NotFound, Found, NotExists
74670 */
74671 case OP_NoConflict:     /* jump, in3 */
74672 case OP_NotFound:       /* jump, in3 */
74673 case OP_Found: {        /* jump, in3 */
74674   int alreadyExists;
74675   int takeJump;
74676   int ii;
74677   VdbeCursor *pC;
74678   int res;
74679   char *pFree;
74680   UnpackedRecord *pIdxKey;
74681   UnpackedRecord r;
74682   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
74683 
74684 #ifdef SQLITE_TEST
74685   if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
74686 #endif
74687 
74688   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74689   assert( pOp->p4type==P4_INT32 );
74690   pC = p->apCsr[pOp->p1];
74691   assert( pC!=0 );
74692 #ifdef SQLITE_DEBUG
74693   pC->seekOp = pOp->opcode;
74694 #endif
74695   pIn3 = &aMem[pOp->p3];
74696   assert( pC->pCursor!=0 );
74697   assert( pC->isTable==0 );
74698   pFree = 0;
74699   if( pOp->p4.i>0 ){
74700     r.pKeyInfo = pC->pKeyInfo;
74701     r.nField = (u16)pOp->p4.i;
74702     r.aMem = pIn3;
74703     for(ii=0; ii<r.nField; ii++){
74704       assert( memIsValid(&r.aMem[ii]) );
74705       ExpandBlob(&r.aMem[ii]);
74706 #ifdef SQLITE_DEBUG
74707       if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
74708 #endif
74709     }
74710     pIdxKey = &r;
74711   }else{
74712     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
74713         pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
74714     );
74715     if( pIdxKey==0 ) goto no_mem;
74716     assert( pIn3->flags & MEM_Blob );
74717     ExpandBlob(pIn3);
74718     sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
74719   }
74720   pIdxKey->default_rc = 0;
74721   takeJump = 0;
74722   if( pOp->opcode==OP_NoConflict ){
74723     /* For the OP_NoConflict opcode, take the jump if any of the
74724     ** input fields are NULL, since any key with a NULL will not
74725     ** conflict */
74726     for(ii=0; ii<pIdxKey->nField; ii++){
74727       if( pIdxKey->aMem[ii].flags & MEM_Null ){
74728         takeJump = 1;
74729         break;
74730       }
74731     }
74732   }
74733   rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
74734   sqlite3DbFree(db, pFree);
74735   if( rc!=SQLITE_OK ){
74736     break;
74737   }
74738   pC->seekResult = res;
74739   alreadyExists = (res==0);
74740   pC->nullRow = 1-alreadyExists;
74741   pC->deferredMoveto = 0;
74742   pC->cacheStatus = CACHE_STALE;
74743   if( pOp->opcode==OP_Found ){
74744     VdbeBranchTaken(alreadyExists!=0,2);
74745     if( alreadyExists ) goto jump_to_p2;
74746   }else{
74747     VdbeBranchTaken(takeJump||alreadyExists==0,2);
74748     if( takeJump || !alreadyExists ) goto jump_to_p2;
74749   }
74750   break;
74751 }
74752 
74753 /* Opcode: NotExists P1 P2 P3 * *
74754 ** Synopsis: intkey=r[P3]
74755 **
74756 ** P1 is the index of a cursor open on an SQL table btree (with integer
74757 ** keys).  P3 is an integer rowid.  If P1 does not contain a record with
74758 ** rowid P3 then jump immediately to P2.  If P1 does contain a record
74759 ** with rowid P3 then leave the cursor pointing at that record and fall
74760 ** through to the next instruction.
74761 **
74762 ** The OP_NotFound opcode performs the same operation on index btrees
74763 ** (with arbitrary multi-value keys).
74764 **
74765 ** This opcode leaves the cursor in a state where it cannot be advanced
74766 ** in either direction.  In other words, the Next and Prev opcodes will
74767 ** not work following this opcode.
74768 **
74769 ** See also: Found, NotFound, NoConflict
74770 */
74771 case OP_NotExists: {        /* jump, in3 */
74772   VdbeCursor *pC;
74773   BtCursor *pCrsr;
74774   int res;
74775   u64 iKey;
74776 
74777   pIn3 = &aMem[pOp->p3];
74778   assert( pIn3->flags & MEM_Int );
74779   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74780   pC = p->apCsr[pOp->p1];
74781   assert( pC!=0 );
74782 #ifdef SQLITE_DEBUG
74783   pC->seekOp = 0;
74784 #endif
74785   assert( pC->isTable );
74786   assert( pC->pseudoTableReg==0 );
74787   pCrsr = pC->pCursor;
74788   assert( pCrsr!=0 );
74789   res = 0;
74790   iKey = pIn3->u.i;
74791   rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
74792   pC->movetoTarget = iKey;  /* Used by OP_Delete */
74793   pC->nullRow = 0;
74794   pC->cacheStatus = CACHE_STALE;
74795   pC->deferredMoveto = 0;
74796   VdbeBranchTaken(res!=0,2);
74797   pC->seekResult = res;
74798   if( res!=0 ) goto jump_to_p2;
74799   break;
74800 }
74801 
74802 /* Opcode: Sequence P1 P2 * * *
74803 ** Synopsis: r[P2]=cursor[P1].ctr++
74804 **
74805 ** Find the next available sequence number for cursor P1.
74806 ** Write the sequence number into register P2.
74807 ** The sequence number on the cursor is incremented after this
74808 ** instruction.
74809 */
74810 case OP_Sequence: {           /* out2 */
74811   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74812   assert( p->apCsr[pOp->p1]!=0 );
74813   pOut = out2Prerelease(p, pOp);
74814   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
74815   break;
74816 }
74817 
74818 
74819 /* Opcode: NewRowid P1 P2 P3 * *
74820 ** Synopsis: r[P2]=rowid
74821 **
74822 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
74823 ** The record number is not previously used as a key in the database
74824 ** table that cursor P1 points to.  The new record number is written
74825 ** written to register P2.
74826 **
74827 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
74828 ** the largest previously generated record number. No new record numbers are
74829 ** allowed to be less than this value. When this value reaches its maximum,
74830 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
74831 ** generated record number. This P3 mechanism is used to help implement the
74832 ** AUTOINCREMENT feature.
74833 */
74834 case OP_NewRowid: {           /* out2 */
74835   i64 v;                 /* The new rowid */
74836   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
74837   int res;               /* Result of an sqlite3BtreeLast() */
74838   int cnt;               /* Counter to limit the number of searches */
74839   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
74840   VdbeFrame *pFrame;     /* Root frame of VDBE */
74841 
74842   v = 0;
74843   res = 0;
74844   pOut = out2Prerelease(p, pOp);
74845   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74846   pC = p->apCsr[pOp->p1];
74847   assert( pC!=0 );
74848   if( NEVER(pC->pCursor==0) ){
74849     /* The zero initialization above is all that is needed */
74850   }else{
74851     /* The next rowid or record number (different terms for the same
74852     ** thing) is obtained in a two-step algorithm.
74853     **
74854     ** First we attempt to find the largest existing rowid and add one
74855     ** to that.  But if the largest existing rowid is already the maximum
74856     ** positive integer, we have to fall through to the second
74857     ** probabilistic algorithm
74858     **
74859     ** The second algorithm is to select a rowid at random and see if
74860     ** it already exists in the table.  If it does not exist, we have
74861     ** succeeded.  If the random rowid does exist, we select a new one
74862     ** and try again, up to 100 times.
74863     */
74864     assert( pC->isTable );
74865 
74866 #ifdef SQLITE_32BIT_ROWID
74867 #   define MAX_ROWID 0x7fffffff
74868 #else
74869     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
74870     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
74871     ** to provide the constant while making all compilers happy.
74872     */
74873 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
74874 #endif
74875 
74876     if( !pC->useRandomRowid ){
74877       rc = sqlite3BtreeLast(pC->pCursor, &res);
74878       if( rc!=SQLITE_OK ){
74879         goto abort_due_to_error;
74880       }
74881       if( res ){
74882         v = 1;   /* IMP: R-61914-48074 */
74883       }else{
74884         assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
74885         rc = sqlite3BtreeKeySize(pC->pCursor, &v);
74886         assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
74887         if( v>=MAX_ROWID ){
74888           pC->useRandomRowid = 1;
74889         }else{
74890           v++;   /* IMP: R-29538-34987 */
74891         }
74892       }
74893     }
74894 
74895 #ifndef SQLITE_OMIT_AUTOINCREMENT
74896     if( pOp->p3 ){
74897       /* Assert that P3 is a valid memory cell. */
74898       assert( pOp->p3>0 );
74899       if( p->pFrame ){
74900         for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
74901         /* Assert that P3 is a valid memory cell. */
74902         assert( pOp->p3<=pFrame->nMem );
74903         pMem = &pFrame->aMem[pOp->p3];
74904       }else{
74905         /* Assert that P3 is a valid memory cell. */
74906         assert( pOp->p3<=(p->nMem-p->nCursor) );
74907         pMem = &aMem[pOp->p3];
74908         memAboutToChange(p, pMem);
74909       }
74910       assert( memIsValid(pMem) );
74911 
74912       REGISTER_TRACE(pOp->p3, pMem);
74913       sqlite3VdbeMemIntegerify(pMem);
74914       assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
74915       if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
74916         rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
74917         goto abort_due_to_error;
74918       }
74919       if( v<pMem->u.i+1 ){
74920         v = pMem->u.i + 1;
74921       }
74922       pMem->u.i = v;
74923     }
74924 #endif
74925     if( pC->useRandomRowid ){
74926       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
74927       ** largest possible integer (9223372036854775807) then the database
74928       ** engine starts picking positive candidate ROWIDs at random until
74929       ** it finds one that is not previously used. */
74930       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
74931                              ** an AUTOINCREMENT table. */
74932       cnt = 0;
74933       do{
74934         sqlite3_randomness(sizeof(v), &v);
74935         v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
74936       }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
74937                                                  0, &res))==SQLITE_OK)
74938             && (res==0)
74939             && (++cnt<100));
74940       if( rc==SQLITE_OK && res==0 ){
74941         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
74942         goto abort_due_to_error;
74943       }
74944       assert( v>0 );  /* EV: R-40812-03570 */
74945     }
74946     pC->deferredMoveto = 0;
74947     pC->cacheStatus = CACHE_STALE;
74948   }
74949   pOut->u.i = v;
74950   break;
74951 }
74952 
74953 /* Opcode: Insert P1 P2 P3 P4 P5
74954 ** Synopsis: intkey=r[P3] data=r[P2]
74955 **
74956 ** Write an entry into the table of cursor P1.  A new entry is
74957 ** created if it doesn't already exist or the data for an existing
74958 ** entry is overwritten.  The data is the value MEM_Blob stored in register
74959 ** number P2. The key is stored in register P3. The key must
74960 ** be a MEM_Int.
74961 **
74962 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
74963 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
74964 ** then rowid is stored for subsequent return by the
74965 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
74966 **
74967 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
74968 ** the last seek operation (OP_NotExists) was a success, then this
74969 ** operation will not attempt to find the appropriate row before doing
74970 ** the insert but will instead overwrite the row that the cursor is
74971 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
74972 ** has already positioned the cursor correctly.  This is an optimization
74973 ** that boosts performance by avoiding redundant seeks.
74974 **
74975 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
74976 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
74977 ** is part of an INSERT operation.  The difference is only important to
74978 ** the update hook.
74979 **
74980 ** Parameter P4 may point to a string containing the table-name, or
74981 ** may be NULL. If it is not NULL, then the update-hook
74982 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
74983 **
74984 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
74985 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
74986 ** and register P2 becomes ephemeral.  If the cursor is changed, the
74987 ** value of register P2 will then change.  Make sure this does not
74988 ** cause any problems.)
74989 **
74990 ** This instruction only works on tables.  The equivalent instruction
74991 ** for indices is OP_IdxInsert.
74992 */
74993 /* Opcode: InsertInt P1 P2 P3 P4 P5
74994 ** Synopsis:  intkey=P3 data=r[P2]
74995 **
74996 ** This works exactly like OP_Insert except that the key is the
74997 ** integer value P3, not the value of the integer stored in register P3.
74998 */
74999 case OP_Insert:
75000 case OP_InsertInt: {
75001   Mem *pData;       /* MEM cell holding data for the record to be inserted */
75002   Mem *pKey;        /* MEM cell holding key  for the record */
75003   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
75004   VdbeCursor *pC;   /* Cursor to table into which insert is written */
75005   int nZero;        /* Number of zero-bytes to append */
75006   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
75007   const char *zDb;  /* database name - used by the update hook */
75008   const char *zTbl; /* Table name - used by the opdate hook */
75009   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
75010 
75011   pData = &aMem[pOp->p2];
75012   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75013   assert( memIsValid(pData) );
75014   pC = p->apCsr[pOp->p1];
75015   assert( pC!=0 );
75016   assert( pC->pCursor!=0 );
75017   assert( pC->pseudoTableReg==0 );
75018   assert( pC->isTable );
75019   REGISTER_TRACE(pOp->p2, pData);
75020 
75021   if( pOp->opcode==OP_Insert ){
75022     pKey = &aMem[pOp->p3];
75023     assert( pKey->flags & MEM_Int );
75024     assert( memIsValid(pKey) );
75025     REGISTER_TRACE(pOp->p3, pKey);
75026     iKey = pKey->u.i;
75027   }else{
75028     assert( pOp->opcode==OP_InsertInt );
75029     iKey = pOp->p3;
75030   }
75031 
75032   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
75033   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
75034   if( pData->flags & MEM_Null ){
75035     pData->z = 0;
75036     pData->n = 0;
75037   }else{
75038     assert( pData->flags & (MEM_Blob|MEM_Str) );
75039   }
75040   seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
75041   if( pData->flags & MEM_Zero ){
75042     nZero = pData->u.nZero;
75043   }else{
75044     nZero = 0;
75045   }
75046   rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
75047                           pData->z, pData->n, nZero,
75048                           (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
75049   );
75050   pC->deferredMoveto = 0;
75051   pC->cacheStatus = CACHE_STALE;
75052 
75053   /* Invoke the update-hook if required. */
75054   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
75055     zDb = db->aDb[pC->iDb].zName;
75056     zTbl = pOp->p4.z;
75057     op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
75058     assert( pC->isTable );
75059     db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
75060     assert( pC->iDb>=0 );
75061   }
75062   break;
75063 }
75064 
75065 /* Opcode: Delete P1 P2 * P4 *
75066 **
75067 ** Delete the record at which the P1 cursor is currently pointing.
75068 **
75069 ** The cursor will be left pointing at either the next or the previous
75070 ** record in the table. If it is left pointing at the next record, then
75071 ** the next Next instruction will be a no-op.  Hence it is OK to delete
75072 ** a record from within a Next loop.
75073 **
75074 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
75075 ** incremented (otherwise not).
75076 **
75077 ** P1 must not be pseudo-table.  It has to be a real table with
75078 ** multiple rows.
75079 **
75080 ** If P4 is not NULL, then it is the name of the table that P1 is
75081 ** pointing to.  The update hook will be invoked, if it exists.
75082 ** If P4 is not NULL then the P1 cursor must have been positioned
75083 ** using OP_NotFound prior to invoking this opcode.
75084 */
75085 case OP_Delete: {
75086   VdbeCursor *pC;
75087 
75088   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75089   pC = p->apCsr[pOp->p1];
75090   assert( pC!=0 );
75091   assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
75092   assert( pC->deferredMoveto==0 );
75093 
75094 #ifdef SQLITE_DEBUG
75095   /* The seek operation that positioned the cursor prior to OP_Delete will
75096   ** have also set the pC->movetoTarget field to the rowid of the row that
75097   ** is being deleted */
75098   if( pOp->p4.z && pC->isTable ){
75099     i64 iKey = 0;
75100     sqlite3BtreeKeySize(pC->pCursor, &iKey);
75101     assert( pC->movetoTarget==iKey );
75102   }
75103 #endif
75104 
75105   rc = sqlite3BtreeDelete(pC->pCursor);
75106   pC->cacheStatus = CACHE_STALE;
75107 
75108   /* Invoke the update-hook if required. */
75109   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
75110     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
75111                         db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
75112     assert( pC->iDb>=0 );
75113   }
75114   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
75115   break;
75116 }
75117 /* Opcode: ResetCount * * * * *
75118 **
75119 ** The value of the change counter is copied to the database handle
75120 ** change counter (returned by subsequent calls to sqlite3_changes()).
75121 ** Then the VMs internal change counter resets to 0.
75122 ** This is used by trigger programs.
75123 */
75124 case OP_ResetCount: {
75125   sqlite3VdbeSetChanges(db, p->nChange);
75126   p->nChange = 0;
75127   break;
75128 }
75129 
75130 /* Opcode: SorterCompare P1 P2 P3 P4
75131 ** Synopsis:  if key(P1)!=trim(r[P3],P4) goto P2
75132 **
75133 ** P1 is a sorter cursor. This instruction compares a prefix of the
75134 ** record blob in register P3 against a prefix of the entry that
75135 ** the sorter cursor currently points to.  Only the first P4 fields
75136 ** of r[P3] and the sorter record are compared.
75137 **
75138 ** If either P3 or the sorter contains a NULL in one of their significant
75139 ** fields (not counting the P4 fields at the end which are ignored) then
75140 ** the comparison is assumed to be equal.
75141 **
75142 ** Fall through to next instruction if the two records compare equal to
75143 ** each other.  Jump to P2 if they are different.
75144 */
75145 case OP_SorterCompare: {
75146   VdbeCursor *pC;
75147   int res;
75148   int nKeyCol;
75149 
75150   pC = p->apCsr[pOp->p1];
75151   assert( isSorter(pC) );
75152   assert( pOp->p4type==P4_INT32 );
75153   pIn3 = &aMem[pOp->p3];
75154   nKeyCol = pOp->p4.i;
75155   res = 0;
75156   rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
75157   VdbeBranchTaken(res!=0,2);
75158   if( res ) goto jump_to_p2;
75159   break;
75160 };
75161 
75162 /* Opcode: SorterData P1 P2 P3 * *
75163 ** Synopsis: r[P2]=data
75164 **
75165 ** Write into register P2 the current sorter data for sorter cursor P1.
75166 ** Then clear the column header cache on cursor P3.
75167 **
75168 ** This opcode is normally use to move a record out of the sorter and into
75169 ** a register that is the source for a pseudo-table cursor created using
75170 ** OpenPseudo.  That pseudo-table cursor is the one that is identified by
75171 ** parameter P3.  Clearing the P3 column cache as part of this opcode saves
75172 ** us from having to issue a separate NullRow instruction to clear that cache.
75173 */
75174 case OP_SorterData: {
75175   VdbeCursor *pC;
75176 
75177   pOut = &aMem[pOp->p2];
75178   pC = p->apCsr[pOp->p1];
75179   assert( isSorter(pC) );
75180   rc = sqlite3VdbeSorterRowkey(pC, pOut);
75181   assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
75182   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75183   p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
75184   break;
75185 }
75186 
75187 /* Opcode: RowData P1 P2 * * *
75188 ** Synopsis: r[P2]=data
75189 **
75190 ** Write into register P2 the complete row data for cursor P1.
75191 ** There is no interpretation of the data.
75192 ** It is just copied onto the P2 register exactly as
75193 ** it is found in the database file.
75194 **
75195 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
75196 ** of a real table, not a pseudo-table.
75197 */
75198 /* Opcode: RowKey P1 P2 * * *
75199 ** Synopsis: r[P2]=key
75200 **
75201 ** Write into register P2 the complete row key for cursor P1.
75202 ** There is no interpretation of the data.
75203 ** The key is copied onto the P2 register exactly as
75204 ** it is found in the database file.
75205 **
75206 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
75207 ** of a real table, not a pseudo-table.
75208 */
75209 case OP_RowKey:
75210 case OP_RowData: {
75211   VdbeCursor *pC;
75212   BtCursor *pCrsr;
75213   u32 n;
75214   i64 n64;
75215 
75216   pOut = &aMem[pOp->p2];
75217   memAboutToChange(p, pOut);
75218 
75219   /* Note that RowKey and RowData are really exactly the same instruction */
75220   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75221   pC = p->apCsr[pOp->p1];
75222   assert( isSorter(pC)==0 );
75223   assert( pC->isTable || pOp->opcode!=OP_RowData );
75224   assert( pC->isTable==0 || pOp->opcode==OP_RowData );
75225   assert( pC!=0 );
75226   assert( pC->nullRow==0 );
75227   assert( pC->pseudoTableReg==0 );
75228   assert( pC->pCursor!=0 );
75229   pCrsr = pC->pCursor;
75230 
75231   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
75232   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
75233   ** the cursor.  If this where not the case, on of the following assert()s
75234   ** would fail.  Should this ever change (because of changes in the code
75235   ** generator) then the fix would be to insert a call to
75236   ** sqlite3VdbeCursorMoveto().
75237   */
75238   assert( pC->deferredMoveto==0 );
75239   assert( sqlite3BtreeCursorIsValid(pCrsr) );
75240 #if 0  /* Not required due to the previous to assert() statements */
75241   rc = sqlite3VdbeCursorMoveto(pC);
75242   if( rc!=SQLITE_OK ) goto abort_due_to_error;
75243 #endif
75244 
75245   if( pC->isTable==0 ){
75246     assert( !pC->isTable );
75247     VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
75248     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
75249     if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
75250       goto too_big;
75251     }
75252     n = (u32)n64;
75253   }else{
75254     VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
75255     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
75256     if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
75257       goto too_big;
75258     }
75259   }
75260   testcase( n==0 );
75261   if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
75262     goto no_mem;
75263   }
75264   pOut->n = n;
75265   MemSetTypeFlag(pOut, MEM_Blob);
75266   if( pC->isTable==0 ){
75267     rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
75268   }else{
75269     rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
75270   }
75271   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
75272   UPDATE_MAX_BLOBSIZE(pOut);
75273   REGISTER_TRACE(pOp->p2, pOut);
75274   break;
75275 }
75276 
75277 /* Opcode: Rowid P1 P2 * * *
75278 ** Synopsis: r[P2]=rowid
75279 **
75280 ** Store in register P2 an integer which is the key of the table entry that
75281 ** P1 is currently point to.
75282 **
75283 ** P1 can be either an ordinary table or a virtual table.  There used to
75284 ** be a separate OP_VRowid opcode for use with virtual tables, but this
75285 ** one opcode now works for both table types.
75286 */
75287 case OP_Rowid: {                 /* out2 */
75288   VdbeCursor *pC;
75289   i64 v;
75290   sqlite3_vtab *pVtab;
75291   const sqlite3_module *pModule;
75292 
75293   pOut = out2Prerelease(p, pOp);
75294   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75295   pC = p->apCsr[pOp->p1];
75296   assert( pC!=0 );
75297   assert( pC->pseudoTableReg==0 || pC->nullRow );
75298   if( pC->nullRow ){
75299     pOut->flags = MEM_Null;
75300     break;
75301   }else if( pC->deferredMoveto ){
75302     v = pC->movetoTarget;
75303 #ifndef SQLITE_OMIT_VIRTUALTABLE
75304   }else if( pC->pVtabCursor ){
75305     pVtab = pC->pVtabCursor->pVtab;
75306     pModule = pVtab->pModule;
75307     assert( pModule->xRowid );
75308     rc = pModule->xRowid(pC->pVtabCursor, &v);
75309     sqlite3VtabImportErrmsg(p, pVtab);
75310 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75311   }else{
75312     assert( pC->pCursor!=0 );
75313     rc = sqlite3VdbeCursorRestore(pC);
75314     if( rc ) goto abort_due_to_error;
75315     if( pC->nullRow ){
75316       pOut->flags = MEM_Null;
75317       break;
75318     }
75319     rc = sqlite3BtreeKeySize(pC->pCursor, &v);
75320     assert( rc==SQLITE_OK );  /* Always so because of CursorRestore() above */
75321   }
75322   pOut->u.i = v;
75323   break;
75324 }
75325 
75326 /* Opcode: NullRow P1 * * * *
75327 **
75328 ** Move the cursor P1 to a null row.  Any OP_Column operations
75329 ** that occur while the cursor is on the null row will always
75330 ** write a NULL.
75331 */
75332 case OP_NullRow: {
75333   VdbeCursor *pC;
75334 
75335   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75336   pC = p->apCsr[pOp->p1];
75337   assert( pC!=0 );
75338   pC->nullRow = 1;
75339   pC->cacheStatus = CACHE_STALE;
75340   if( pC->pCursor ){
75341     sqlite3BtreeClearCursor(pC->pCursor);
75342   }
75343   break;
75344 }
75345 
75346 /* Opcode: Last P1 P2 P3 * *
75347 **
75348 ** The next use of the Rowid or Column or Prev instruction for P1
75349 ** will refer to the last entry in the database table or index.
75350 ** If the table or index is empty and P2>0, then jump immediately to P2.
75351 ** If P2 is 0 or if the table or index is not empty, fall through
75352 ** to the following instruction.
75353 **
75354 ** This opcode leaves the cursor configured to move in reverse order,
75355 ** from the end toward the beginning.  In other words, the cursor is
75356 ** configured to use Prev, not Next.
75357 */
75358 case OP_Last: {        /* jump */
75359   VdbeCursor *pC;
75360   BtCursor *pCrsr;
75361   int res;
75362 
75363   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75364   pC = p->apCsr[pOp->p1];
75365   assert( pC!=0 );
75366   pCrsr = pC->pCursor;
75367   res = 0;
75368   assert( pCrsr!=0 );
75369   rc = sqlite3BtreeLast(pCrsr, &res);
75370   pC->nullRow = (u8)res;
75371   pC->deferredMoveto = 0;
75372   pC->cacheStatus = CACHE_STALE;
75373   pC->seekResult = pOp->p3;
75374 #ifdef SQLITE_DEBUG
75375   pC->seekOp = OP_Last;
75376 #endif
75377   if( pOp->p2>0 ){
75378     VdbeBranchTaken(res!=0,2);
75379     if( res ) goto jump_to_p2;
75380   }
75381   break;
75382 }
75383 
75384 
75385 /* Opcode: Sort P1 P2 * * *
75386 **
75387 ** This opcode does exactly the same thing as OP_Rewind except that
75388 ** it increments an undocumented global variable used for testing.
75389 **
75390 ** Sorting is accomplished by writing records into a sorting index,
75391 ** then rewinding that index and playing it back from beginning to
75392 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
75393 ** rewinding so that the global variable will be incremented and
75394 ** regression tests can determine whether or not the optimizer is
75395 ** correctly optimizing out sorts.
75396 */
75397 case OP_SorterSort:    /* jump */
75398 case OP_Sort: {        /* jump */
75399 #ifdef SQLITE_TEST
75400   sqlite3_sort_count++;
75401   sqlite3_search_count--;
75402 #endif
75403   p->aCounter[SQLITE_STMTSTATUS_SORT]++;
75404   /* Fall through into OP_Rewind */
75405 }
75406 /* Opcode: Rewind P1 P2 * * *
75407 **
75408 ** The next use of the Rowid or Column or Next instruction for P1
75409 ** will refer to the first entry in the database table or index.
75410 ** If the table or index is empty, jump immediately to P2.
75411 ** If the table or index is not empty, fall through to the following
75412 ** instruction.
75413 **
75414 ** This opcode leaves the cursor configured to move in forward order,
75415 ** from the beginning toward the end.  In other words, the cursor is
75416 ** configured to use Next, not Prev.
75417 */
75418 case OP_Rewind: {        /* jump */
75419   VdbeCursor *pC;
75420   BtCursor *pCrsr;
75421   int res;
75422 
75423   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75424   pC = p->apCsr[pOp->p1];
75425   assert( pC!=0 );
75426   assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
75427   res = 1;
75428 #ifdef SQLITE_DEBUG
75429   pC->seekOp = OP_Rewind;
75430 #endif
75431   if( isSorter(pC) ){
75432     rc = sqlite3VdbeSorterRewind(pC, &res);
75433   }else{
75434     pCrsr = pC->pCursor;
75435     assert( pCrsr );
75436     rc = sqlite3BtreeFirst(pCrsr, &res);
75437     pC->deferredMoveto = 0;
75438     pC->cacheStatus = CACHE_STALE;
75439   }
75440   pC->nullRow = (u8)res;
75441   assert( pOp->p2>0 && pOp->p2<p->nOp );
75442   VdbeBranchTaken(res!=0,2);
75443   if( res ) goto jump_to_p2;
75444   break;
75445 }
75446 
75447 /* Opcode: Next P1 P2 P3 P4 P5
75448 **
75449 ** Advance cursor P1 so that it points to the next key/data pair in its
75450 ** table or index.  If there are no more key/value pairs then fall through
75451 ** to the following instruction.  But if the cursor advance was successful,
75452 ** jump immediately to P2.
75453 **
75454 ** The Next opcode is only valid following an SeekGT, SeekGE, or
75455 ** OP_Rewind opcode used to position the cursor.  Next is not allowed
75456 ** to follow SeekLT, SeekLE, or OP_Last.
75457 **
75458 ** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
75459 ** been opened prior to this opcode or the program will segfault.
75460 **
75461 ** The P3 value is a hint to the btree implementation. If P3==1, that
75462 ** means P1 is an SQL index and that this instruction could have been
75463 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
75464 ** always either 0 or 1.
75465 **
75466 ** P4 is always of type P4_ADVANCE. The function pointer points to
75467 ** sqlite3BtreeNext().
75468 **
75469 ** If P5 is positive and the jump is taken, then event counter
75470 ** number P5-1 in the prepared statement is incremented.
75471 **
75472 ** See also: Prev, NextIfOpen
75473 */
75474 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
75475 **
75476 ** This opcode works just like Next except that if cursor P1 is not
75477 ** open it behaves a no-op.
75478 */
75479 /* Opcode: Prev P1 P2 P3 P4 P5
75480 **
75481 ** Back up cursor P1 so that it points to the previous key/data pair in its
75482 ** table or index.  If there is no previous key/value pairs then fall through
75483 ** to the following instruction.  But if the cursor backup was successful,
75484 ** jump immediately to P2.
75485 **
75486 **
75487 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
75488 ** OP_Last opcode used to position the cursor.  Prev is not allowed
75489 ** to follow SeekGT, SeekGE, or OP_Rewind.
75490 **
75491 ** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
75492 ** not open then the behavior is undefined.
75493 **
75494 ** The P3 value is a hint to the btree implementation. If P3==1, that
75495 ** means P1 is an SQL index and that this instruction could have been
75496 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
75497 ** always either 0 or 1.
75498 **
75499 ** P4 is always of type P4_ADVANCE. The function pointer points to
75500 ** sqlite3BtreePrevious().
75501 **
75502 ** If P5 is positive and the jump is taken, then event counter
75503 ** number P5-1 in the prepared statement is incremented.
75504 */
75505 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
75506 **
75507 ** This opcode works just like Prev except that if cursor P1 is not
75508 ** open it behaves a no-op.
75509 */
75510 case OP_SorterNext: {  /* jump */
75511   VdbeCursor *pC;
75512   int res;
75513 
75514   pC = p->apCsr[pOp->p1];
75515   assert( isSorter(pC) );
75516   res = 0;
75517   rc = sqlite3VdbeSorterNext(db, pC, &res);
75518   goto next_tail;
75519 case OP_PrevIfOpen:    /* jump */
75520 case OP_NextIfOpen:    /* jump */
75521   if( p->apCsr[pOp->p1]==0 ) break;
75522   /* Fall through */
75523 case OP_Prev:          /* jump */
75524 case OP_Next:          /* jump */
75525   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75526   assert( pOp->p5<ArraySize(p->aCounter) );
75527   pC = p->apCsr[pOp->p1];
75528   res = pOp->p3;
75529   assert( pC!=0 );
75530   assert( pC->deferredMoveto==0 );
75531   assert( pC->pCursor );
75532   assert( res==0 || (res==1 && pC->isTable==0) );
75533   testcase( res==1 );
75534   assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
75535   assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
75536   assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
75537   assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
75538 
75539   /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
75540   ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
75541   assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
75542        || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
75543        || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
75544   assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
75545        || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
75546        || pC->seekOp==OP_Last );
75547 
75548   rc = pOp->p4.xAdvance(pC->pCursor, &res);
75549 next_tail:
75550   pC->cacheStatus = CACHE_STALE;
75551   VdbeBranchTaken(res==0,2);
75552   if( res==0 ){
75553     pC->nullRow = 0;
75554     p->aCounter[pOp->p5]++;
75555 #ifdef SQLITE_TEST
75556     sqlite3_search_count++;
75557 #endif
75558     goto jump_to_p2_and_check_for_interrupt;
75559   }else{
75560     pC->nullRow = 1;
75561   }
75562   goto check_for_interrupt;
75563 }
75564 
75565 /* Opcode: IdxInsert P1 P2 P3 * P5
75566 ** Synopsis: key=r[P2]
75567 **
75568 ** Register P2 holds an SQL index key made using the
75569 ** MakeRecord instructions.  This opcode writes that key
75570 ** into the index P1.  Data for the entry is nil.
75571 **
75572 ** P3 is a flag that provides a hint to the b-tree layer that this
75573 ** insert is likely to be an append.
75574 **
75575 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
75576 ** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
75577 ** then the change counter is unchanged.
75578 **
75579 ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
75580 ** just done a seek to the spot where the new entry is to be inserted.
75581 ** This flag avoids doing an extra seek.
75582 **
75583 ** This instruction only works for indices.  The equivalent instruction
75584 ** for tables is OP_Insert.
75585 */
75586 case OP_SorterInsert:       /* in2 */
75587 case OP_IdxInsert: {        /* in2 */
75588   VdbeCursor *pC;
75589   BtCursor *pCrsr;
75590   int nKey;
75591   const char *zKey;
75592 
75593   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75594   pC = p->apCsr[pOp->p1];
75595   assert( pC!=0 );
75596   assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
75597   pIn2 = &aMem[pOp->p2];
75598   assert( pIn2->flags & MEM_Blob );
75599   pCrsr = pC->pCursor;
75600   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
75601   assert( pCrsr!=0 );
75602   assert( pC->isTable==0 );
75603   rc = ExpandBlob(pIn2);
75604   if( rc==SQLITE_OK ){
75605     if( isSorter(pC) ){
75606       rc = sqlite3VdbeSorterWrite(pC, pIn2);
75607     }else{
75608       nKey = pIn2->n;
75609       zKey = pIn2->z;
75610       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3,
75611           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
75612           );
75613       assert( pC->deferredMoveto==0 );
75614       pC->cacheStatus = CACHE_STALE;
75615     }
75616   }
75617   break;
75618 }
75619 
75620 /* Opcode: IdxDelete P1 P2 P3 * *
75621 ** Synopsis: key=r[P2@P3]
75622 **
75623 ** The content of P3 registers starting at register P2 form
75624 ** an unpacked index key. This opcode removes that entry from the
75625 ** index opened by cursor P1.
75626 */
75627 case OP_IdxDelete: {
75628   VdbeCursor *pC;
75629   BtCursor *pCrsr;
75630   int res;
75631   UnpackedRecord r;
75632 
75633   assert( pOp->p3>0 );
75634   assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
75635   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75636   pC = p->apCsr[pOp->p1];
75637   assert( pC!=0 );
75638   pCrsr = pC->pCursor;
75639   assert( pCrsr!=0 );
75640   assert( pOp->p5==0 );
75641   r.pKeyInfo = pC->pKeyInfo;
75642   r.nField = (u16)pOp->p3;
75643   r.default_rc = 0;
75644   r.aMem = &aMem[pOp->p2];
75645 #ifdef SQLITE_DEBUG
75646   { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
75647 #endif
75648   rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
75649   if( rc==SQLITE_OK && res==0 ){
75650     rc = sqlite3BtreeDelete(pCrsr);
75651   }
75652   assert( pC->deferredMoveto==0 );
75653   pC->cacheStatus = CACHE_STALE;
75654   break;
75655 }
75656 
75657 /* Opcode: IdxRowid P1 P2 * * *
75658 ** Synopsis: r[P2]=rowid
75659 **
75660 ** Write into register P2 an integer which is the last entry in the record at
75661 ** the end of the index key pointed to by cursor P1.  This integer should be
75662 ** the rowid of the table entry to which this index entry points.
75663 **
75664 ** See also: Rowid, MakeRecord.
75665 */
75666 case OP_IdxRowid: {              /* out2 */
75667   BtCursor *pCrsr;
75668   VdbeCursor *pC;
75669   i64 rowid;
75670 
75671   pOut = out2Prerelease(p, pOp);
75672   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75673   pC = p->apCsr[pOp->p1];
75674   assert( pC!=0 );
75675   pCrsr = pC->pCursor;
75676   assert( pCrsr!=0 );
75677   pOut->flags = MEM_Null;
75678   assert( pC->isTable==0 );
75679   assert( pC->deferredMoveto==0 );
75680 
75681   /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
75682   ** out from under the cursor.  That will never happend for an IdxRowid
75683   ** opcode, hence the NEVER() arround the check of the return value.
75684   */
75685   rc = sqlite3VdbeCursorRestore(pC);
75686   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
75687 
75688   if( !pC->nullRow ){
75689     rowid = 0;  /* Not needed.  Only used to silence a warning. */
75690     rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
75691     if( rc!=SQLITE_OK ){
75692       goto abort_due_to_error;
75693     }
75694     pOut->u.i = rowid;
75695     pOut->flags = MEM_Int;
75696   }
75697   break;
75698 }
75699 
75700 /* Opcode: IdxGE P1 P2 P3 P4 P5
75701 ** Synopsis: key=r[P3@P4]
75702 **
75703 ** The P4 register values beginning with P3 form an unpacked index
75704 ** key that omits the PRIMARY KEY.  Compare this key value against the index
75705 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
75706 ** fields at the end.
75707 **
75708 ** If the P1 index entry is greater than or equal to the key value
75709 ** then jump to P2.  Otherwise fall through to the next instruction.
75710 */
75711 /* Opcode: IdxGT P1 P2 P3 P4 P5
75712 ** Synopsis: key=r[P3@P4]
75713 **
75714 ** The P4 register values beginning with P3 form an unpacked index
75715 ** key that omits the PRIMARY KEY.  Compare this key value against the index
75716 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
75717 ** fields at the end.
75718 **
75719 ** If the P1 index entry is greater than the key value
75720 ** then jump to P2.  Otherwise fall through to the next instruction.
75721 */
75722 /* Opcode: IdxLT P1 P2 P3 P4 P5
75723 ** Synopsis: key=r[P3@P4]
75724 **
75725 ** The P4 register values beginning with P3 form an unpacked index
75726 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
75727 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
75728 ** ROWID on the P1 index.
75729 **
75730 ** If the P1 index entry is less than the key value then jump to P2.
75731 ** Otherwise fall through to the next instruction.
75732 */
75733 /* Opcode: IdxLE P1 P2 P3 P4 P5
75734 ** Synopsis: key=r[P3@P4]
75735 **
75736 ** The P4 register values beginning with P3 form an unpacked index
75737 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
75738 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
75739 ** ROWID on the P1 index.
75740 **
75741 ** If the P1 index entry is less than or equal to the key value then jump
75742 ** to P2. Otherwise fall through to the next instruction.
75743 */
75744 case OP_IdxLE:          /* jump */
75745 case OP_IdxGT:          /* jump */
75746 case OP_IdxLT:          /* jump */
75747 case OP_IdxGE:  {       /* jump */
75748   VdbeCursor *pC;
75749   int res;
75750   UnpackedRecord r;
75751 
75752   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75753   pC = p->apCsr[pOp->p1];
75754   assert( pC!=0 );
75755   assert( pC->isOrdered );
75756   assert( pC->pCursor!=0);
75757   assert( pC->deferredMoveto==0 );
75758   assert( pOp->p5==0 || pOp->p5==1 );
75759   assert( pOp->p4type==P4_INT32 );
75760   r.pKeyInfo = pC->pKeyInfo;
75761   r.nField = (u16)pOp->p4.i;
75762   if( pOp->opcode<OP_IdxLT ){
75763     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
75764     r.default_rc = -1;
75765   }else{
75766     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
75767     r.default_rc = 0;
75768   }
75769   r.aMem = &aMem[pOp->p3];
75770 #ifdef SQLITE_DEBUG
75771   { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
75772 #endif
75773   res = 0;  /* Not needed.  Only used to silence a warning. */
75774   rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
75775   assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
75776   if( (pOp->opcode&1)==(OP_IdxLT&1) ){
75777     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
75778     res = -res;
75779   }else{
75780     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
75781     res++;
75782   }
75783   VdbeBranchTaken(res>0,2);
75784   if( res>0 ) goto jump_to_p2;
75785   break;
75786 }
75787 
75788 /* Opcode: Destroy P1 P2 P3 * *
75789 **
75790 ** Delete an entire database table or index whose root page in the database
75791 ** file is given by P1.
75792 **
75793 ** The table being destroyed is in the main database file if P3==0.  If
75794 ** P3==1 then the table to be clear is in the auxiliary database file
75795 ** that is used to store tables create using CREATE TEMPORARY TABLE.
75796 **
75797 ** If AUTOVACUUM is enabled then it is possible that another root page
75798 ** might be moved into the newly deleted root page in order to keep all
75799 ** root pages contiguous at the beginning of the database.  The former
75800 ** value of the root page that moved - its value before the move occurred -
75801 ** is stored in register P2.  If no page
75802 ** movement was required (because the table being dropped was already
75803 ** the last one in the database) then a zero is stored in register P2.
75804 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
75805 **
75806 ** See also: Clear
75807 */
75808 case OP_Destroy: {     /* out2 */
75809   int iMoved;
75810   int iDb;
75811 
75812   assert( p->readOnly==0 );
75813   pOut = out2Prerelease(p, pOp);
75814   pOut->flags = MEM_Null;
75815   if( db->nVdbeRead > db->nVDestroy+1 ){
75816     rc = SQLITE_LOCKED;
75817     p->errorAction = OE_Abort;
75818   }else{
75819     iDb = pOp->p3;
75820     assert( DbMaskTest(p->btreeMask, iDb) );
75821     iMoved = 0;  /* Not needed.  Only to silence a warning. */
75822     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
75823     pOut->flags = MEM_Int;
75824     pOut->u.i = iMoved;
75825 #ifndef SQLITE_OMIT_AUTOVACUUM
75826     if( rc==SQLITE_OK && iMoved!=0 ){
75827       sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
75828       /* All OP_Destroy operations occur on the same btree */
75829       assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
75830       resetSchemaOnFault = iDb+1;
75831     }
75832 #endif
75833   }
75834   break;
75835 }
75836 
75837 /* Opcode: Clear P1 P2 P3
75838 **
75839 ** Delete all contents of the database table or index whose root page
75840 ** in the database file is given by P1.  But, unlike Destroy, do not
75841 ** remove the table or index from the database file.
75842 **
75843 ** The table being clear is in the main database file if P2==0.  If
75844 ** P2==1 then the table to be clear is in the auxiliary database file
75845 ** that is used to store tables create using CREATE TEMPORARY TABLE.
75846 **
75847 ** If the P3 value is non-zero, then the table referred to must be an
75848 ** intkey table (an SQL table, not an index). In this case the row change
75849 ** count is incremented by the number of rows in the table being cleared.
75850 ** If P3 is greater than zero, then the value stored in register P3 is
75851 ** also incremented by the number of rows in the table being cleared.
75852 **
75853 ** See also: Destroy
75854 */
75855 case OP_Clear: {
75856   int nChange;
75857 
75858   nChange = 0;
75859   assert( p->readOnly==0 );
75860   assert( DbMaskTest(p->btreeMask, pOp->p2) );
75861   rc = sqlite3BtreeClearTable(
75862       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
75863   );
75864   if( pOp->p3 ){
75865     p->nChange += nChange;
75866     if( pOp->p3>0 ){
75867       assert( memIsValid(&aMem[pOp->p3]) );
75868       memAboutToChange(p, &aMem[pOp->p3]);
75869       aMem[pOp->p3].u.i += nChange;
75870     }
75871   }
75872   break;
75873 }
75874 
75875 /* Opcode: ResetSorter P1 * * * *
75876 **
75877 ** Delete all contents from the ephemeral table or sorter
75878 ** that is open on cursor P1.
75879 **
75880 ** This opcode only works for cursors used for sorting and
75881 ** opened with OP_OpenEphemeral or OP_SorterOpen.
75882 */
75883 case OP_ResetSorter: {
75884   VdbeCursor *pC;
75885 
75886   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75887   pC = p->apCsr[pOp->p1];
75888   assert( pC!=0 );
75889   if( pC->pSorter ){
75890     sqlite3VdbeSorterReset(db, pC->pSorter);
75891   }else{
75892     assert( pC->isEphemeral );
75893     rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
75894   }
75895   break;
75896 }
75897 
75898 /* Opcode: CreateTable P1 P2 * * *
75899 ** Synopsis: r[P2]=root iDb=P1
75900 **
75901 ** Allocate a new table in the main database file if P1==0 or in the
75902 ** auxiliary database file if P1==1 or in an attached database if
75903 ** P1>1.  Write the root page number of the new table into
75904 ** register P2
75905 **
75906 ** The difference between a table and an index is this:  A table must
75907 ** have a 4-byte integer key and can have arbitrary data.  An index
75908 ** has an arbitrary key but no data.
75909 **
75910 ** See also: CreateIndex
75911 */
75912 /* Opcode: CreateIndex P1 P2 * * *
75913 ** Synopsis: r[P2]=root iDb=P1
75914 **
75915 ** Allocate a new index in the main database file if P1==0 or in the
75916 ** auxiliary database file if P1==1 or in an attached database if
75917 ** P1>1.  Write the root page number of the new table into
75918 ** register P2.
75919 **
75920 ** See documentation on OP_CreateTable for additional information.
75921 */
75922 case OP_CreateIndex:            /* out2 */
75923 case OP_CreateTable: {          /* out2 */
75924   int pgno;
75925   int flags;
75926   Db *pDb;
75927 
75928   pOut = out2Prerelease(p, pOp);
75929   pgno = 0;
75930   assert( pOp->p1>=0 && pOp->p1<db->nDb );
75931   assert( DbMaskTest(p->btreeMask, pOp->p1) );
75932   assert( p->readOnly==0 );
75933   pDb = &db->aDb[pOp->p1];
75934   assert( pDb->pBt!=0 );
75935   if( pOp->opcode==OP_CreateTable ){
75936     /* flags = BTREE_INTKEY; */
75937     flags = BTREE_INTKEY;
75938   }else{
75939     flags = BTREE_BLOBKEY;
75940   }
75941   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
75942   pOut->u.i = pgno;
75943   break;
75944 }
75945 
75946 /* Opcode: ParseSchema P1 * * P4 *
75947 **
75948 ** Read and parse all entries from the SQLITE_MASTER table of database P1
75949 ** that match the WHERE clause P4.
75950 **
75951 ** This opcode invokes the parser to create a new virtual machine,
75952 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
75953 */
75954 case OP_ParseSchema: {
75955   int iDb;
75956   const char *zMaster;
75957   char *zSql;
75958   InitData initData;
75959 
75960   /* Any prepared statement that invokes this opcode will hold mutexes
75961   ** on every btree.  This is a prerequisite for invoking
75962   ** sqlite3InitCallback().
75963   */
75964 #ifdef SQLITE_DEBUG
75965   for(iDb=0; iDb<db->nDb; iDb++){
75966     assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
75967   }
75968 #endif
75969 
75970   iDb = pOp->p1;
75971   assert( iDb>=0 && iDb<db->nDb );
75972   assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
75973   /* Used to be a conditional */ {
75974     zMaster = SCHEMA_TABLE(iDb);
75975     initData.db = db;
75976     initData.iDb = pOp->p1;
75977     initData.pzErrMsg = &p->zErrMsg;
75978     zSql = sqlite3MPrintf(db,
75979        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
75980        db->aDb[iDb].zName, zMaster, pOp->p4.z);
75981     if( zSql==0 ){
75982       rc = SQLITE_NOMEM;
75983     }else{
75984       assert( db->init.busy==0 );
75985       db->init.busy = 1;
75986       initData.rc = SQLITE_OK;
75987       assert( !db->mallocFailed );
75988       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
75989       if( rc==SQLITE_OK ) rc = initData.rc;
75990       sqlite3DbFree(db, zSql);
75991       db->init.busy = 0;
75992     }
75993   }
75994   if( rc ) sqlite3ResetAllSchemasOfConnection(db);
75995   if( rc==SQLITE_NOMEM ){
75996     goto no_mem;
75997   }
75998   break;
75999 }
76000 
76001 #if !defined(SQLITE_OMIT_ANALYZE)
76002 /* Opcode: LoadAnalysis P1 * * * *
76003 **
76004 ** Read the sqlite_stat1 table for database P1 and load the content
76005 ** of that table into the internal index hash table.  This will cause
76006 ** the analysis to be used when preparing all subsequent queries.
76007 */
76008 case OP_LoadAnalysis: {
76009   assert( pOp->p1>=0 && pOp->p1<db->nDb );
76010   rc = sqlite3AnalysisLoad(db, pOp->p1);
76011   break;
76012 }
76013 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
76014 
76015 /* Opcode: DropTable P1 * * P4 *
76016 **
76017 ** Remove the internal (in-memory) data structures that describe
76018 ** the table named P4 in database P1.  This is called after a table
76019 ** is dropped from disk (using the Destroy opcode) in order to keep
76020 ** the internal representation of the
76021 ** schema consistent with what is on disk.
76022 */
76023 case OP_DropTable: {
76024   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
76025   break;
76026 }
76027 
76028 /* Opcode: DropIndex P1 * * P4 *
76029 **
76030 ** Remove the internal (in-memory) data structures that describe
76031 ** the index named P4 in database P1.  This is called after an index
76032 ** is dropped from disk (using the Destroy opcode)
76033 ** in order to keep the internal representation of the
76034 ** schema consistent with what is on disk.
76035 */
76036 case OP_DropIndex: {
76037   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
76038   break;
76039 }
76040 
76041 /* Opcode: DropTrigger P1 * * P4 *
76042 **
76043 ** Remove the internal (in-memory) data structures that describe
76044 ** the trigger named P4 in database P1.  This is called after a trigger
76045 ** is dropped from disk (using the Destroy opcode) in order to keep
76046 ** the internal representation of the
76047 ** schema consistent with what is on disk.
76048 */
76049 case OP_DropTrigger: {
76050   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
76051   break;
76052 }
76053 
76054 
76055 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
76056 /* Opcode: IntegrityCk P1 P2 P3 * P5
76057 **
76058 ** Do an analysis of the currently open database.  Store in
76059 ** register P1 the text of an error message describing any problems.
76060 ** If no problems are found, store a NULL in register P1.
76061 **
76062 ** The register P3 contains the maximum number of allowed errors.
76063 ** At most reg(P3) errors will be reported.
76064 ** In other words, the analysis stops as soon as reg(P1) errors are
76065 ** seen.  Reg(P1) is updated with the number of errors remaining.
76066 **
76067 ** The root page numbers of all tables in the database are integer
76068 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
76069 ** total.
76070 **
76071 ** If P5 is not zero, the check is done on the auxiliary database
76072 ** file, not the main database file.
76073 **
76074 ** This opcode is used to implement the integrity_check pragma.
76075 */
76076 case OP_IntegrityCk: {
76077   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
76078   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
76079   int j;          /* Loop counter */
76080   int nErr;       /* Number of errors reported */
76081   char *z;        /* Text of the error report */
76082   Mem *pnErr;     /* Register keeping track of errors remaining */
76083 
76084   assert( p->bIsReader );
76085   nRoot = pOp->p2;
76086   assert( nRoot>0 );
76087   aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
76088   if( aRoot==0 ) goto no_mem;
76089   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
76090   pnErr = &aMem[pOp->p3];
76091   assert( (pnErr->flags & MEM_Int)!=0 );
76092   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
76093   pIn1 = &aMem[pOp->p1];
76094   for(j=0; j<nRoot; j++){
76095     aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
76096   }
76097   aRoot[j] = 0;
76098   assert( pOp->p5<db->nDb );
76099   assert( DbMaskTest(p->btreeMask, pOp->p5) );
76100   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
76101                                  (int)pnErr->u.i, &nErr);
76102   sqlite3DbFree(db, aRoot);
76103   pnErr->u.i -= nErr;
76104   sqlite3VdbeMemSetNull(pIn1);
76105   if( nErr==0 ){
76106     assert( z==0 );
76107   }else if( z==0 ){
76108     goto no_mem;
76109   }else{
76110     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
76111   }
76112   UPDATE_MAX_BLOBSIZE(pIn1);
76113   sqlite3VdbeChangeEncoding(pIn1, encoding);
76114   break;
76115 }
76116 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
76117 
76118 /* Opcode: RowSetAdd P1 P2 * * *
76119 ** Synopsis:  rowset(P1)=r[P2]
76120 **
76121 ** Insert the integer value held by register P2 into a boolean index
76122 ** held in register P1.
76123 **
76124 ** An assertion fails if P2 is not an integer.
76125 */
76126 case OP_RowSetAdd: {       /* in1, in2 */
76127   pIn1 = &aMem[pOp->p1];
76128   pIn2 = &aMem[pOp->p2];
76129   assert( (pIn2->flags & MEM_Int)!=0 );
76130   if( (pIn1->flags & MEM_RowSet)==0 ){
76131     sqlite3VdbeMemSetRowSet(pIn1);
76132     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
76133   }
76134   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
76135   break;
76136 }
76137 
76138 /* Opcode: RowSetRead P1 P2 P3 * *
76139 ** Synopsis:  r[P3]=rowset(P1)
76140 **
76141 ** Extract the smallest value from boolean index P1 and put that value into
76142 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
76143 ** unchanged and jump to instruction P2.
76144 */
76145 case OP_RowSetRead: {       /* jump, in1, out3 */
76146   i64 val;
76147 
76148   pIn1 = &aMem[pOp->p1];
76149   if( (pIn1->flags & MEM_RowSet)==0
76150    || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
76151   ){
76152     /* The boolean index is empty */
76153     sqlite3VdbeMemSetNull(pIn1);
76154     VdbeBranchTaken(1,2);
76155     goto jump_to_p2_and_check_for_interrupt;
76156   }else{
76157     /* A value was pulled from the index */
76158     VdbeBranchTaken(0,2);
76159     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
76160   }
76161   goto check_for_interrupt;
76162 }
76163 
76164 /* Opcode: RowSetTest P1 P2 P3 P4
76165 ** Synopsis: if r[P3] in rowset(P1) goto P2
76166 **
76167 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
76168 ** contains a RowSet object and that RowSet object contains
76169 ** the value held in P3, jump to register P2. Otherwise, insert the
76170 ** integer in P3 into the RowSet and continue on to the
76171 ** next opcode.
76172 **
76173 ** The RowSet object is optimized for the case where successive sets
76174 ** of integers, where each set contains no duplicates. Each set
76175 ** of values is identified by a unique P4 value. The first set
76176 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
76177 ** non-negative.  For non-negative values of P4 only the lower 4
76178 ** bits are significant.
76179 **
76180 ** This allows optimizations: (a) when P4==0 there is no need to test
76181 ** the rowset object for P3, as it is guaranteed not to contain it,
76182 ** (b) when P4==-1 there is no need to insert the value, as it will
76183 ** never be tested for, and (c) when a value that is part of set X is
76184 ** inserted, there is no need to search to see if the same value was
76185 ** previously inserted as part of set X (only if it was previously
76186 ** inserted as part of some other set).
76187 */
76188 case OP_RowSetTest: {                     /* jump, in1, in3 */
76189   int iSet;
76190   int exists;
76191 
76192   pIn1 = &aMem[pOp->p1];
76193   pIn3 = &aMem[pOp->p3];
76194   iSet = pOp->p4.i;
76195   assert( pIn3->flags&MEM_Int );
76196 
76197   /* If there is anything other than a rowset object in memory cell P1,
76198   ** delete it now and initialize P1 with an empty rowset
76199   */
76200   if( (pIn1->flags & MEM_RowSet)==0 ){
76201     sqlite3VdbeMemSetRowSet(pIn1);
76202     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
76203   }
76204 
76205   assert( pOp->p4type==P4_INT32 );
76206   assert( iSet==-1 || iSet>=0 );
76207   if( iSet ){
76208     exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
76209     VdbeBranchTaken(exists!=0,2);
76210     if( exists ) goto jump_to_p2;
76211   }
76212   if( iSet>=0 ){
76213     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
76214   }
76215   break;
76216 }
76217 
76218 
76219 #ifndef SQLITE_OMIT_TRIGGER
76220 
76221 /* Opcode: Program P1 P2 P3 P4 P5
76222 **
76223 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
76224 **
76225 ** P1 contains the address of the memory cell that contains the first memory
76226 ** cell in an array of values used as arguments to the sub-program. P2
76227 ** contains the address to jump to if the sub-program throws an IGNORE
76228 ** exception using the RAISE() function. Register P3 contains the address
76229 ** of a memory cell in this (the parent) VM that is used to allocate the
76230 ** memory required by the sub-vdbe at runtime.
76231 **
76232 ** P4 is a pointer to the VM containing the trigger program.
76233 **
76234 ** If P5 is non-zero, then recursive program invocation is enabled.
76235 */
76236 case OP_Program: {        /* jump */
76237   int nMem;               /* Number of memory registers for sub-program */
76238   int nByte;              /* Bytes of runtime space required for sub-program */
76239   Mem *pRt;               /* Register to allocate runtime space */
76240   Mem *pMem;              /* Used to iterate through memory cells */
76241   Mem *pEnd;              /* Last memory cell in new array */
76242   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
76243   SubProgram *pProgram;   /* Sub-program to execute */
76244   void *t;                /* Token identifying trigger */
76245 
76246   pProgram = pOp->p4.pProgram;
76247   pRt = &aMem[pOp->p3];
76248   assert( pProgram->nOp>0 );
76249 
76250   /* If the p5 flag is clear, then recursive invocation of triggers is
76251   ** disabled for backwards compatibility (p5 is set if this sub-program
76252   ** is really a trigger, not a foreign key action, and the flag set
76253   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
76254   **
76255   ** It is recursive invocation of triggers, at the SQL level, that is
76256   ** disabled. In some cases a single trigger may generate more than one
76257   ** SubProgram (if the trigger may be executed with more than one different
76258   ** ON CONFLICT algorithm). SubProgram structures associated with a
76259   ** single trigger all have the same value for the SubProgram.token
76260   ** variable.  */
76261   if( pOp->p5 ){
76262     t = pProgram->token;
76263     for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
76264     if( pFrame ) break;
76265   }
76266 
76267   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
76268     rc = SQLITE_ERROR;
76269     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
76270     break;
76271   }
76272 
76273   /* Register pRt is used to store the memory required to save the state
76274   ** of the current program, and the memory required at runtime to execute
76275   ** the trigger program. If this trigger has been fired before, then pRt
76276   ** is already allocated. Otherwise, it must be initialized.  */
76277   if( (pRt->flags&MEM_Frame)==0 ){
76278     /* SubProgram.nMem is set to the number of memory cells used by the
76279     ** program stored in SubProgram.aOp. As well as these, one memory
76280     ** cell is required for each cursor used by the program. Set local
76281     ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
76282     */
76283     nMem = pProgram->nMem + pProgram->nCsr;
76284     nByte = ROUND8(sizeof(VdbeFrame))
76285               + nMem * sizeof(Mem)
76286               + pProgram->nCsr * sizeof(VdbeCursor *)
76287               + pProgram->nOnce * sizeof(u8);
76288     pFrame = sqlite3DbMallocZero(db, nByte);
76289     if( !pFrame ){
76290       goto no_mem;
76291     }
76292     sqlite3VdbeMemRelease(pRt);
76293     pRt->flags = MEM_Frame;
76294     pRt->u.pFrame = pFrame;
76295 
76296     pFrame->v = p;
76297     pFrame->nChildMem = nMem;
76298     pFrame->nChildCsr = pProgram->nCsr;
76299     pFrame->pc = (int)(pOp - aOp);
76300     pFrame->aMem = p->aMem;
76301     pFrame->nMem = p->nMem;
76302     pFrame->apCsr = p->apCsr;
76303     pFrame->nCursor = p->nCursor;
76304     pFrame->aOp = p->aOp;
76305     pFrame->nOp = p->nOp;
76306     pFrame->token = pProgram->token;
76307     pFrame->aOnceFlag = p->aOnceFlag;
76308     pFrame->nOnceFlag = p->nOnceFlag;
76309 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
76310     pFrame->anExec = p->anExec;
76311 #endif
76312 
76313     pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
76314     for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
76315       pMem->flags = MEM_Undefined;
76316       pMem->db = db;
76317     }
76318   }else{
76319     pFrame = pRt->u.pFrame;
76320     assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
76321     assert( pProgram->nCsr==pFrame->nChildCsr );
76322     assert( (int)(pOp - aOp)==pFrame->pc );
76323   }
76324 
76325   p->nFrame++;
76326   pFrame->pParent = p->pFrame;
76327   pFrame->lastRowid = lastRowid;
76328   pFrame->nChange = p->nChange;
76329   pFrame->nDbChange = p->db->nChange;
76330   p->nChange = 0;
76331   p->pFrame = pFrame;
76332   p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
76333   p->nMem = pFrame->nChildMem;
76334   p->nCursor = (u16)pFrame->nChildCsr;
76335   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
76336   p->aOp = aOp = pProgram->aOp;
76337   p->nOp = pProgram->nOp;
76338   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
76339   p->nOnceFlag = pProgram->nOnce;
76340 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
76341   p->anExec = 0;
76342 #endif
76343   pOp = &aOp[-1];
76344   memset(p->aOnceFlag, 0, p->nOnceFlag);
76345 
76346   break;
76347 }
76348 
76349 /* Opcode: Param P1 P2 * * *
76350 **
76351 ** This opcode is only ever present in sub-programs called via the
76352 ** OP_Program instruction. Copy a value currently stored in a memory
76353 ** cell of the calling (parent) frame to cell P2 in the current frames
76354 ** address space. This is used by trigger programs to access the new.*
76355 ** and old.* values.
76356 **
76357 ** The address of the cell in the parent frame is determined by adding
76358 ** the value of the P1 argument to the value of the P1 argument to the
76359 ** calling OP_Program instruction.
76360 */
76361 case OP_Param: {           /* out2 */
76362   VdbeFrame *pFrame;
76363   Mem *pIn;
76364   pOut = out2Prerelease(p, pOp);
76365   pFrame = p->pFrame;
76366   pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
76367   sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
76368   break;
76369 }
76370 
76371 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
76372 
76373 #ifndef SQLITE_OMIT_FOREIGN_KEY
76374 /* Opcode: FkCounter P1 P2 * * *
76375 ** Synopsis: fkctr[P1]+=P2
76376 **
76377 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
76378 ** If P1 is non-zero, the database constraint counter is incremented
76379 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
76380 ** statement counter is incremented (immediate foreign key constraints).
76381 */
76382 case OP_FkCounter: {
76383   if( db->flags & SQLITE_DeferFKs ){
76384     db->nDeferredImmCons += pOp->p2;
76385   }else if( pOp->p1 ){
76386     db->nDeferredCons += pOp->p2;
76387   }else{
76388     p->nFkConstraint += pOp->p2;
76389   }
76390   break;
76391 }
76392 
76393 /* Opcode: FkIfZero P1 P2 * * *
76394 ** Synopsis: if fkctr[P1]==0 goto P2
76395 **
76396 ** This opcode tests if a foreign key constraint-counter is currently zero.
76397 ** If so, jump to instruction P2. Otherwise, fall through to the next
76398 ** instruction.
76399 **
76400 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
76401 ** is zero (the one that counts deferred constraint violations). If P1 is
76402 ** zero, the jump is taken if the statement constraint-counter is zero
76403 ** (immediate foreign key constraint violations).
76404 */
76405 case OP_FkIfZero: {         /* jump */
76406   if( pOp->p1 ){
76407     VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
76408     if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
76409   }else{
76410     VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
76411     if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
76412   }
76413   break;
76414 }
76415 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
76416 
76417 #ifndef SQLITE_OMIT_AUTOINCREMENT
76418 /* Opcode: MemMax P1 P2 * * *
76419 ** Synopsis: r[P1]=max(r[P1],r[P2])
76420 **
76421 ** P1 is a register in the root frame of this VM (the root frame is
76422 ** different from the current frame if this instruction is being executed
76423 ** within a sub-program). Set the value of register P1 to the maximum of
76424 ** its current value and the value in register P2.
76425 **
76426 ** This instruction throws an error if the memory cell is not initially
76427 ** an integer.
76428 */
76429 case OP_MemMax: {        /* in2 */
76430   VdbeFrame *pFrame;
76431   if( p->pFrame ){
76432     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
76433     pIn1 = &pFrame->aMem[pOp->p1];
76434   }else{
76435     pIn1 = &aMem[pOp->p1];
76436   }
76437   assert( memIsValid(pIn1) );
76438   sqlite3VdbeMemIntegerify(pIn1);
76439   pIn2 = &aMem[pOp->p2];
76440   sqlite3VdbeMemIntegerify(pIn2);
76441   if( pIn1->u.i<pIn2->u.i){
76442     pIn1->u.i = pIn2->u.i;
76443   }
76444   break;
76445 }
76446 #endif /* SQLITE_OMIT_AUTOINCREMENT */
76447 
76448 /* Opcode: IfPos P1 P2 * * *
76449 ** Synopsis: if r[P1]>0 goto P2
76450 **
76451 ** Register P1 must contain an integer.
76452 ** If the value of register P1 is 1 or greater, jump to P2 and
76453 ** add the literal value P3 to register P1.
76454 **
76455 ** If the initial value of register P1 is less than 1, then the
76456 ** value is unchanged and control passes through to the next instruction.
76457 */
76458 case OP_IfPos: {        /* jump, in1 */
76459   pIn1 = &aMem[pOp->p1];
76460   assert( pIn1->flags&MEM_Int );
76461   VdbeBranchTaken( pIn1->u.i>0, 2);
76462   if( pIn1->u.i>0 ) goto jump_to_p2;
76463   break;
76464 }
76465 
76466 /* Opcode: IfNeg P1 P2 P3 * *
76467 ** Synopsis: r[P1]+=P3, if r[P1]<0 goto P2
76468 **
76469 ** Register P1 must contain an integer.  Add literal P3 to the value in
76470 ** register P1 then if the value of register P1 is less than zero, jump to P2.
76471 */
76472 case OP_IfNeg: {        /* jump, in1 */
76473   pIn1 = &aMem[pOp->p1];
76474   assert( pIn1->flags&MEM_Int );
76475   pIn1->u.i += pOp->p3;
76476   VdbeBranchTaken(pIn1->u.i<0, 2);
76477   if( pIn1->u.i<0 ) goto jump_to_p2;
76478   break;
76479 }
76480 
76481 /* Opcode: IfNotZero P1 P2 P3 * *
76482 ** Synopsis: if r[P1]!=0 then r[P1]+=P3, goto P2
76483 **
76484 ** Register P1 must contain an integer.  If the content of register P1 is
76485 ** initially nonzero, then add P3 to P1 and jump to P2.  If register P1 is
76486 ** initially zero, leave it unchanged and fall through.
76487 */
76488 case OP_IfNotZero: {        /* jump, in1 */
76489   pIn1 = &aMem[pOp->p1];
76490   assert( pIn1->flags&MEM_Int );
76491   VdbeBranchTaken(pIn1->u.i<0, 2);
76492   if( pIn1->u.i ){
76493      pIn1->u.i += pOp->p3;
76494      goto jump_to_p2;
76495   }
76496   break;
76497 }
76498 
76499 /* Opcode: DecrJumpZero P1 P2 * * *
76500 ** Synopsis: if (--r[P1])==0 goto P2
76501 **
76502 ** Register P1 must hold an integer.  Decrement the value in register P1
76503 ** then jump to P2 if the new value is exactly zero.
76504 */
76505 case OP_DecrJumpZero: {      /* jump, in1 */
76506   pIn1 = &aMem[pOp->p1];
76507   assert( pIn1->flags&MEM_Int );
76508   pIn1->u.i--;
76509   VdbeBranchTaken(pIn1->u.i==0, 2);
76510   if( pIn1->u.i==0 ) goto jump_to_p2;
76511   break;
76512 }
76513 
76514 
76515 /* Opcode: JumpZeroIncr P1 P2 * * *
76516 ** Synopsis: if (r[P1]++)==0 ) goto P2
76517 **
76518 ** The register P1 must contain an integer.  If register P1 is initially
76519 ** zero, then jump to P2.  Increment register P1 regardless of whether or
76520 ** not the jump is taken.
76521 */
76522 case OP_JumpZeroIncr: {        /* jump, in1 */
76523   pIn1 = &aMem[pOp->p1];
76524   assert( pIn1->flags&MEM_Int );
76525   VdbeBranchTaken(pIn1->u.i==0, 2);
76526   if( (pIn1->u.i++)==0 ) goto jump_to_p2;
76527   break;
76528 }
76529 
76530 /* Opcode: AggStep * P2 P3 P4 P5
76531 ** Synopsis: accum=r[P3] step(r[P2@P5])
76532 **
76533 ** Execute the step function for an aggregate.  The
76534 ** function has P5 arguments.   P4 is a pointer to the FuncDef
76535 ** structure that specifies the function.  Use register
76536 ** P3 as the accumulator.
76537 **
76538 ** The P5 arguments are taken from register P2 and its
76539 ** successors.
76540 */
76541 case OP_AggStep: {
76542   int n;
76543   int i;
76544   Mem *pMem;
76545   Mem *pRec;
76546   Mem t;
76547   sqlite3_context ctx;
76548   sqlite3_value **apVal;
76549 
76550   n = pOp->p5;
76551   assert( n>=0 );
76552   pRec = &aMem[pOp->p2];
76553   apVal = p->apArg;
76554   assert( apVal || n==0 );
76555   for(i=0; i<n; i++, pRec++){
76556     assert( memIsValid(pRec) );
76557     apVal[i] = pRec;
76558     memAboutToChange(p, pRec);
76559   }
76560   ctx.pFunc = pOp->p4.pFunc;
76561   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
76562   ctx.pMem = pMem = &aMem[pOp->p3];
76563   pMem->n++;
76564   sqlite3VdbeMemInit(&t, db, MEM_Null);
76565   ctx.pOut = &t;
76566   ctx.isError = 0;
76567   ctx.pVdbe = p;
76568   ctx.iOp = (int)(pOp - aOp);
76569   ctx.skipFlag = 0;
76570   (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
76571   if( ctx.isError ){
76572     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&t));
76573     rc = ctx.isError;
76574   }
76575   if( ctx.skipFlag ){
76576     assert( pOp[-1].opcode==OP_CollSeq );
76577     i = pOp[-1].p1;
76578     if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
76579   }
76580   sqlite3VdbeMemRelease(&t);
76581   break;
76582 }
76583 
76584 /* Opcode: AggFinal P1 P2 * P4 *
76585 ** Synopsis: accum=r[P1] N=P2
76586 **
76587 ** Execute the finalizer function for an aggregate.  P1 is
76588 ** the memory location that is the accumulator for the aggregate.
76589 **
76590 ** P2 is the number of arguments that the step function takes and
76591 ** P4 is a pointer to the FuncDef for this function.  The P2
76592 ** argument is not used by this opcode.  It is only there to disambiguate
76593 ** functions that can take varying numbers of arguments.  The
76594 ** P4 argument is only needed for the degenerate case where
76595 ** the step function was not previously called.
76596 */
76597 case OP_AggFinal: {
76598   Mem *pMem;
76599   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
76600   pMem = &aMem[pOp->p1];
76601   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
76602   rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
76603   if( rc ){
76604     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
76605   }
76606   sqlite3VdbeChangeEncoding(pMem, encoding);
76607   UPDATE_MAX_BLOBSIZE(pMem);
76608   if( sqlite3VdbeMemTooBig(pMem) ){
76609     goto too_big;
76610   }
76611   break;
76612 }
76613 
76614 #ifndef SQLITE_OMIT_WAL
76615 /* Opcode: Checkpoint P1 P2 P3 * *
76616 **
76617 ** Checkpoint database P1. This is a no-op if P1 is not currently in
76618 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
76619 ** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
76620 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
76621 ** WAL after the checkpoint into mem[P3+1] and the number of pages
76622 ** in the WAL that have been checkpointed after the checkpoint
76623 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
76624 ** mem[P3+2] are initialized to -1.
76625 */
76626 case OP_Checkpoint: {
76627   int i;                          /* Loop counter */
76628   int aRes[3];                    /* Results */
76629   Mem *pMem;                      /* Write results here */
76630 
76631   assert( p->readOnly==0 );
76632   aRes[0] = 0;
76633   aRes[1] = aRes[2] = -1;
76634   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
76635        || pOp->p2==SQLITE_CHECKPOINT_FULL
76636        || pOp->p2==SQLITE_CHECKPOINT_RESTART
76637        || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
76638   );
76639   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
76640   if( rc==SQLITE_BUSY ){
76641     rc = SQLITE_OK;
76642     aRes[0] = 1;
76643   }
76644   for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
76645     sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
76646   }
76647   break;
76648 };
76649 #endif
76650 
76651 #ifndef SQLITE_OMIT_PRAGMA
76652 /* Opcode: JournalMode P1 P2 P3 * *
76653 **
76654 ** Change the journal mode of database P1 to P3. P3 must be one of the
76655 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
76656 ** modes (delete, truncate, persist, off and memory), this is a simple
76657 ** operation. No IO is required.
76658 **
76659 ** If changing into or out of WAL mode the procedure is more complicated.
76660 **
76661 ** Write a string containing the final journal-mode to register P2.
76662 */
76663 case OP_JournalMode: {    /* out2 */
76664   Btree *pBt;                     /* Btree to change journal mode of */
76665   Pager *pPager;                  /* Pager associated with pBt */
76666   int eNew;                       /* New journal mode */
76667   int eOld;                       /* The old journal mode */
76668 #ifndef SQLITE_OMIT_WAL
76669   const char *zFilename;          /* Name of database file for pPager */
76670 #endif
76671 
76672   pOut = out2Prerelease(p, pOp);
76673   eNew = pOp->p3;
76674   assert( eNew==PAGER_JOURNALMODE_DELETE
76675        || eNew==PAGER_JOURNALMODE_TRUNCATE
76676        || eNew==PAGER_JOURNALMODE_PERSIST
76677        || eNew==PAGER_JOURNALMODE_OFF
76678        || eNew==PAGER_JOURNALMODE_MEMORY
76679        || eNew==PAGER_JOURNALMODE_WAL
76680        || eNew==PAGER_JOURNALMODE_QUERY
76681   );
76682   assert( pOp->p1>=0 && pOp->p1<db->nDb );
76683   assert( p->readOnly==0 );
76684 
76685   pBt = db->aDb[pOp->p1].pBt;
76686   pPager = sqlite3BtreePager(pBt);
76687   eOld = sqlite3PagerGetJournalMode(pPager);
76688   if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
76689   if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
76690 
76691 #ifndef SQLITE_OMIT_WAL
76692   zFilename = sqlite3PagerFilename(pPager, 1);
76693 
76694   /* Do not allow a transition to journal_mode=WAL for a database
76695   ** in temporary storage or if the VFS does not support shared memory
76696   */
76697   if( eNew==PAGER_JOURNALMODE_WAL
76698    && (sqlite3Strlen30(zFilename)==0           /* Temp file */
76699        || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
76700   ){
76701     eNew = eOld;
76702   }
76703 
76704   if( (eNew!=eOld)
76705    && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
76706   ){
76707     if( !db->autoCommit || db->nVdbeRead>1 ){
76708       rc = SQLITE_ERROR;
76709       sqlite3SetString(&p->zErrMsg, db,
76710           "cannot change %s wal mode from within a transaction",
76711           (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
76712       );
76713       break;
76714     }else{
76715 
76716       if( eOld==PAGER_JOURNALMODE_WAL ){
76717         /* If leaving WAL mode, close the log file. If successful, the call
76718         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
76719         ** file. An EXCLUSIVE lock may still be held on the database file
76720         ** after a successful return.
76721         */
76722         rc = sqlite3PagerCloseWal(pPager);
76723         if( rc==SQLITE_OK ){
76724           sqlite3PagerSetJournalMode(pPager, eNew);
76725         }
76726       }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
76727         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
76728         ** as an intermediate */
76729         sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
76730       }
76731 
76732       /* Open a transaction on the database file. Regardless of the journal
76733       ** mode, this transaction always uses a rollback journal.
76734       */
76735       assert( sqlite3BtreeIsInTrans(pBt)==0 );
76736       if( rc==SQLITE_OK ){
76737         rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
76738       }
76739     }
76740   }
76741 #endif /* ifndef SQLITE_OMIT_WAL */
76742 
76743   if( rc ){
76744     eNew = eOld;
76745   }
76746   eNew = sqlite3PagerSetJournalMode(pPager, eNew);
76747 
76748   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
76749   pOut->z = (char *)sqlite3JournalModename(eNew);
76750   pOut->n = sqlite3Strlen30(pOut->z);
76751   pOut->enc = SQLITE_UTF8;
76752   sqlite3VdbeChangeEncoding(pOut, encoding);
76753   break;
76754 };
76755 #endif /* SQLITE_OMIT_PRAGMA */
76756 
76757 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
76758 /* Opcode: Vacuum * * * * *
76759 **
76760 ** Vacuum the entire database.  This opcode will cause other virtual
76761 ** machines to be created and run.  It may not be called from within
76762 ** a transaction.
76763 */
76764 case OP_Vacuum: {
76765   assert( p->readOnly==0 );
76766   rc = sqlite3RunVacuum(&p->zErrMsg, db);
76767   break;
76768 }
76769 #endif
76770 
76771 #if !defined(SQLITE_OMIT_AUTOVACUUM)
76772 /* Opcode: IncrVacuum P1 P2 * * *
76773 **
76774 ** Perform a single step of the incremental vacuum procedure on
76775 ** the P1 database. If the vacuum has finished, jump to instruction
76776 ** P2. Otherwise, fall through to the next instruction.
76777 */
76778 case OP_IncrVacuum: {        /* jump */
76779   Btree *pBt;
76780 
76781   assert( pOp->p1>=0 && pOp->p1<db->nDb );
76782   assert( DbMaskTest(p->btreeMask, pOp->p1) );
76783   assert( p->readOnly==0 );
76784   pBt = db->aDb[pOp->p1].pBt;
76785   rc = sqlite3BtreeIncrVacuum(pBt);
76786   VdbeBranchTaken(rc==SQLITE_DONE,2);
76787   if( rc==SQLITE_DONE ){
76788     rc = SQLITE_OK;
76789     goto jump_to_p2;
76790   }
76791   break;
76792 }
76793 #endif
76794 
76795 /* Opcode: Expire P1 * * * *
76796 **
76797 ** Cause precompiled statements to expire.  When an expired statement
76798 ** is executed using sqlite3_step() it will either automatically
76799 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
76800 ** or it will fail with SQLITE_SCHEMA.
76801 **
76802 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
76803 ** then only the currently executing statement is expired.
76804 */
76805 case OP_Expire: {
76806   if( !pOp->p1 ){
76807     sqlite3ExpirePreparedStatements(db);
76808   }else{
76809     p->expired = 1;
76810   }
76811   break;
76812 }
76813 
76814 #ifndef SQLITE_OMIT_SHARED_CACHE
76815 /* Opcode: TableLock P1 P2 P3 P4 *
76816 ** Synopsis: iDb=P1 root=P2 write=P3
76817 **
76818 ** Obtain a lock on a particular table. This instruction is only used when
76819 ** the shared-cache feature is enabled.
76820 **
76821 ** P1 is the index of the database in sqlite3.aDb[] of the database
76822 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
76823 ** a write lock if P3==1.
76824 **
76825 ** P2 contains the root-page of the table to lock.
76826 **
76827 ** P4 contains a pointer to the name of the table being locked. This is only
76828 ** used to generate an error message if the lock cannot be obtained.
76829 */
76830 case OP_TableLock: {
76831   u8 isWriteLock = (u8)pOp->p3;
76832   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
76833     int p1 = pOp->p1;
76834     assert( p1>=0 && p1<db->nDb );
76835     assert( DbMaskTest(p->btreeMask, p1) );
76836     assert( isWriteLock==0 || isWriteLock==1 );
76837     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
76838     if( (rc&0xFF)==SQLITE_LOCKED ){
76839       const char *z = pOp->p4.z;
76840       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
76841     }
76842   }
76843   break;
76844 }
76845 #endif /* SQLITE_OMIT_SHARED_CACHE */
76846 
76847 #ifndef SQLITE_OMIT_VIRTUALTABLE
76848 /* Opcode: VBegin * * * P4 *
76849 **
76850 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
76851 ** xBegin method for that table.
76852 **
76853 ** Also, whether or not P4 is set, check that this is not being called from
76854 ** within a callback to a virtual table xSync() method. If it is, the error
76855 ** code will be set to SQLITE_LOCKED.
76856 */
76857 case OP_VBegin: {
76858   VTable *pVTab;
76859   pVTab = pOp->p4.pVtab;
76860   rc = sqlite3VtabBegin(db, pVTab);
76861   if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
76862   break;
76863 }
76864 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76865 
76866 #ifndef SQLITE_OMIT_VIRTUALTABLE
76867 /* Opcode: VCreate P1 P2 * * *
76868 **
76869 ** P2 is a register that holds the name of a virtual table in database
76870 ** P1. Call the xCreate method for that table.
76871 */
76872 case OP_VCreate: {
76873   Mem sMem;          /* For storing the record being decoded */
76874   const char *zTab;  /* Name of the virtual table */
76875 
76876   memset(&sMem, 0, sizeof(sMem));
76877   sMem.db = db;
76878   /* Because P2 is always a static string, it is impossible for the
76879   ** sqlite3VdbeMemCopy() to fail */
76880   assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
76881   assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
76882   rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
76883   assert( rc==SQLITE_OK );
76884   zTab = (const char*)sqlite3_value_text(&sMem);
76885   assert( zTab || db->mallocFailed );
76886   if( zTab ){
76887     rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
76888   }
76889   sqlite3VdbeMemRelease(&sMem);
76890   break;
76891 }
76892 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76893 
76894 #ifndef SQLITE_OMIT_VIRTUALTABLE
76895 /* Opcode: VDestroy P1 * * P4 *
76896 **
76897 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
76898 ** of that table.
76899 */
76900 case OP_VDestroy: {
76901   db->nVDestroy++;
76902   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
76903   db->nVDestroy--;
76904   break;
76905 }
76906 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76907 
76908 #ifndef SQLITE_OMIT_VIRTUALTABLE
76909 /* Opcode: VOpen P1 * * P4 *
76910 **
76911 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
76912 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
76913 ** table and stores that cursor in P1.
76914 */
76915 case OP_VOpen: {
76916   VdbeCursor *pCur;
76917   sqlite3_vtab_cursor *pVtabCursor;
76918   sqlite3_vtab *pVtab;
76919   const sqlite3_module *pModule;
76920 
76921   assert( p->bIsReader );
76922   pCur = 0;
76923   pVtabCursor = 0;
76924   pVtab = pOp->p4.pVtab->pVtab;
76925   if( pVtab==0 || NEVER(pVtab->pModule==0) ){
76926     rc = SQLITE_LOCKED;
76927     break;
76928   }
76929   pModule = pVtab->pModule;
76930   rc = pModule->xOpen(pVtab, &pVtabCursor);
76931   sqlite3VtabImportErrmsg(p, pVtab);
76932   if( SQLITE_OK==rc ){
76933     /* Initialize sqlite3_vtab_cursor base class */
76934     pVtabCursor->pVtab = pVtab;
76935 
76936     /* Initialize vdbe cursor object */
76937     pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
76938     if( pCur ){
76939       pCur->pVtabCursor = pVtabCursor;
76940       pVtab->nRef++;
76941     }else{
76942       assert( db->mallocFailed );
76943       pModule->xClose(pVtabCursor);
76944       goto no_mem;
76945     }
76946   }
76947   break;
76948 }
76949 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76950 
76951 #ifndef SQLITE_OMIT_VIRTUALTABLE
76952 /* Opcode: VFilter P1 P2 P3 P4 *
76953 ** Synopsis: iplan=r[P3] zplan='P4'
76954 **
76955 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
76956 ** the filtered result set is empty.
76957 **
76958 ** P4 is either NULL or a string that was generated by the xBestIndex
76959 ** method of the module.  The interpretation of the P4 string is left
76960 ** to the module implementation.
76961 **
76962 ** This opcode invokes the xFilter method on the virtual table specified
76963 ** by P1.  The integer query plan parameter to xFilter is stored in register
76964 ** P3. Register P3+1 stores the argc parameter to be passed to the
76965 ** xFilter method. Registers P3+2..P3+1+argc are the argc
76966 ** additional parameters which are passed to
76967 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
76968 **
76969 ** A jump is made to P2 if the result set after filtering would be empty.
76970 */
76971 case OP_VFilter: {   /* jump */
76972   int nArg;
76973   int iQuery;
76974   const sqlite3_module *pModule;
76975   Mem *pQuery;
76976   Mem *pArgc;
76977   sqlite3_vtab_cursor *pVtabCursor;
76978   sqlite3_vtab *pVtab;
76979   VdbeCursor *pCur;
76980   int res;
76981   int i;
76982   Mem **apArg;
76983 
76984   pQuery = &aMem[pOp->p3];
76985   pArgc = &pQuery[1];
76986   pCur = p->apCsr[pOp->p1];
76987   assert( memIsValid(pQuery) );
76988   REGISTER_TRACE(pOp->p3, pQuery);
76989   assert( pCur->pVtabCursor );
76990   pVtabCursor = pCur->pVtabCursor;
76991   pVtab = pVtabCursor->pVtab;
76992   pModule = pVtab->pModule;
76993 
76994   /* Grab the index number and argc parameters */
76995   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
76996   nArg = (int)pArgc->u.i;
76997   iQuery = (int)pQuery->u.i;
76998 
76999   /* Invoke the xFilter method */
77000   res = 0;
77001   apArg = p->apArg;
77002   for(i = 0; i<nArg; i++){
77003     apArg[i] = &pArgc[i+1];
77004   }
77005   rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
77006   sqlite3VtabImportErrmsg(p, pVtab);
77007   if( rc==SQLITE_OK ){
77008     res = pModule->xEof(pVtabCursor);
77009   }
77010   pCur->nullRow = 0;
77011   VdbeBranchTaken(res!=0,2);
77012   if( res ) goto jump_to_p2;
77013   break;
77014 }
77015 #endif /* SQLITE_OMIT_VIRTUALTABLE */
77016 
77017 #ifndef SQLITE_OMIT_VIRTUALTABLE
77018 /* Opcode: VColumn P1 P2 P3 * *
77019 ** Synopsis: r[P3]=vcolumn(P2)
77020 **
77021 ** Store the value of the P2-th column of
77022 ** the row of the virtual-table that the
77023 ** P1 cursor is pointing to into register P3.
77024 */
77025 case OP_VColumn: {
77026   sqlite3_vtab *pVtab;
77027   const sqlite3_module *pModule;
77028   Mem *pDest;
77029   sqlite3_context sContext;
77030 
77031   VdbeCursor *pCur = p->apCsr[pOp->p1];
77032   assert( pCur->pVtabCursor );
77033   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
77034   pDest = &aMem[pOp->p3];
77035   memAboutToChange(p, pDest);
77036   if( pCur->nullRow ){
77037     sqlite3VdbeMemSetNull(pDest);
77038     break;
77039   }
77040   pVtab = pCur->pVtabCursor->pVtab;
77041   pModule = pVtab->pModule;
77042   assert( pModule->xColumn );
77043   memset(&sContext, 0, sizeof(sContext));
77044   sContext.pOut = pDest;
77045   MemSetTypeFlag(pDest, MEM_Null);
77046   rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
77047   sqlite3VtabImportErrmsg(p, pVtab);
77048   if( sContext.isError ){
77049     rc = sContext.isError;
77050   }
77051   sqlite3VdbeChangeEncoding(pDest, encoding);
77052   REGISTER_TRACE(pOp->p3, pDest);
77053   UPDATE_MAX_BLOBSIZE(pDest);
77054 
77055   if( sqlite3VdbeMemTooBig(pDest) ){
77056     goto too_big;
77057   }
77058   break;
77059 }
77060 #endif /* SQLITE_OMIT_VIRTUALTABLE */
77061 
77062 #ifndef SQLITE_OMIT_VIRTUALTABLE
77063 /* Opcode: VNext P1 P2 * * *
77064 **
77065 ** Advance virtual table P1 to the next row in its result set and
77066 ** jump to instruction P2.  Or, if the virtual table has reached
77067 ** the end of its result set, then fall through to the next instruction.
77068 */
77069 case OP_VNext: {   /* jump */
77070   sqlite3_vtab *pVtab;
77071   const sqlite3_module *pModule;
77072   int res;
77073   VdbeCursor *pCur;
77074 
77075   res = 0;
77076   pCur = p->apCsr[pOp->p1];
77077   assert( pCur->pVtabCursor );
77078   if( pCur->nullRow ){
77079     break;
77080   }
77081   pVtab = pCur->pVtabCursor->pVtab;
77082   pModule = pVtab->pModule;
77083   assert( pModule->xNext );
77084 
77085   /* Invoke the xNext() method of the module. There is no way for the
77086   ** underlying implementation to return an error if one occurs during
77087   ** xNext(). Instead, if an error occurs, true is returned (indicating that
77088   ** data is available) and the error code returned when xColumn or
77089   ** some other method is next invoked on the save virtual table cursor.
77090   */
77091   rc = pModule->xNext(pCur->pVtabCursor);
77092   sqlite3VtabImportErrmsg(p, pVtab);
77093   if( rc==SQLITE_OK ){
77094     res = pModule->xEof(pCur->pVtabCursor);
77095   }
77096   VdbeBranchTaken(!res,2);
77097   if( !res ){
77098     /* If there is data, jump to P2 */
77099     goto jump_to_p2_and_check_for_interrupt;
77100   }
77101   goto check_for_interrupt;
77102 }
77103 #endif /* SQLITE_OMIT_VIRTUALTABLE */
77104 
77105 #ifndef SQLITE_OMIT_VIRTUALTABLE
77106 /* Opcode: VRename P1 * * P4 *
77107 **
77108 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
77109 ** This opcode invokes the corresponding xRename method. The value
77110 ** in register P1 is passed as the zName argument to the xRename method.
77111 */
77112 case OP_VRename: {
77113   sqlite3_vtab *pVtab;
77114   Mem *pName;
77115 
77116   pVtab = pOp->p4.pVtab->pVtab;
77117   pName = &aMem[pOp->p1];
77118   assert( pVtab->pModule->xRename );
77119   assert( memIsValid(pName) );
77120   assert( p->readOnly==0 );
77121   REGISTER_TRACE(pOp->p1, pName);
77122   assert( pName->flags & MEM_Str );
77123   testcase( pName->enc==SQLITE_UTF8 );
77124   testcase( pName->enc==SQLITE_UTF16BE );
77125   testcase( pName->enc==SQLITE_UTF16LE );
77126   rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
77127   if( rc==SQLITE_OK ){
77128     rc = pVtab->pModule->xRename(pVtab, pName->z);
77129     sqlite3VtabImportErrmsg(p, pVtab);
77130     p->expired = 0;
77131   }
77132   break;
77133 }
77134 #endif
77135 
77136 #ifndef SQLITE_OMIT_VIRTUALTABLE
77137 /* Opcode: VUpdate P1 P2 P3 P4 P5
77138 ** Synopsis: data=r[P3@P2]
77139 **
77140 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
77141 ** This opcode invokes the corresponding xUpdate method. P2 values
77142 ** are contiguous memory cells starting at P3 to pass to the xUpdate
77143 ** invocation. The value in register (P3+P2-1) corresponds to the
77144 ** p2th element of the argv array passed to xUpdate.
77145 **
77146 ** The xUpdate method will do a DELETE or an INSERT or both.
77147 ** The argv[0] element (which corresponds to memory cell P3)
77148 ** is the rowid of a row to delete.  If argv[0] is NULL then no
77149 ** deletion occurs.  The argv[1] element is the rowid of the new
77150 ** row.  This can be NULL to have the virtual table select the new
77151 ** rowid for itself.  The subsequent elements in the array are
77152 ** the values of columns in the new row.
77153 **
77154 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
77155 ** a row to delete.
77156 **
77157 ** P1 is a boolean flag. If it is set to true and the xUpdate call
77158 ** is successful, then the value returned by sqlite3_last_insert_rowid()
77159 ** is set to the value of the rowid for the row just inserted.
77160 **
77161 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
77162 ** apply in the case of a constraint failure on an insert or update.
77163 */
77164 case OP_VUpdate: {
77165   sqlite3_vtab *pVtab;
77166   const sqlite3_module *pModule;
77167   int nArg;
77168   int i;
77169   sqlite_int64 rowid;
77170   Mem **apArg;
77171   Mem *pX;
77172 
77173   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
77174        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
77175   );
77176   assert( p->readOnly==0 );
77177   pVtab = pOp->p4.pVtab->pVtab;
77178   if( pVtab==0 || NEVER(pVtab->pModule==0) ){
77179     rc = SQLITE_LOCKED;
77180     break;
77181   }
77182   pModule = pVtab->pModule;
77183   nArg = pOp->p2;
77184   assert( pOp->p4type==P4_VTAB );
77185   if( ALWAYS(pModule->xUpdate) ){
77186     u8 vtabOnConflict = db->vtabOnConflict;
77187     apArg = p->apArg;
77188     pX = &aMem[pOp->p3];
77189     for(i=0; i<nArg; i++){
77190       assert( memIsValid(pX) );
77191       memAboutToChange(p, pX);
77192       apArg[i] = pX;
77193       pX++;
77194     }
77195     db->vtabOnConflict = pOp->p5;
77196     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
77197     db->vtabOnConflict = vtabOnConflict;
77198     sqlite3VtabImportErrmsg(p, pVtab);
77199     if( rc==SQLITE_OK && pOp->p1 ){
77200       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
77201       db->lastRowid = lastRowid = rowid;
77202     }
77203     if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
77204       if( pOp->p5==OE_Ignore ){
77205         rc = SQLITE_OK;
77206       }else{
77207         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
77208       }
77209     }else{
77210       p->nChange++;
77211     }
77212   }
77213   break;
77214 }
77215 #endif /* SQLITE_OMIT_VIRTUALTABLE */
77216 
77217 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
77218 /* Opcode: Pagecount P1 P2 * * *
77219 **
77220 ** Write the current number of pages in database P1 to memory cell P2.
77221 */
77222 case OP_Pagecount: {            /* out2 */
77223   pOut = out2Prerelease(p, pOp);
77224   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
77225   break;
77226 }
77227 #endif
77228 
77229 
77230 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
77231 /* Opcode: MaxPgcnt P1 P2 P3 * *
77232 **
77233 ** Try to set the maximum page count for database P1 to the value in P3.
77234 ** Do not let the maximum page count fall below the current page count and
77235 ** do not change the maximum page count value if P3==0.
77236 **
77237 ** Store the maximum page count after the change in register P2.
77238 */
77239 case OP_MaxPgcnt: {            /* out2 */
77240   unsigned int newMax;
77241   Btree *pBt;
77242 
77243   pOut = out2Prerelease(p, pOp);
77244   pBt = db->aDb[pOp->p1].pBt;
77245   newMax = 0;
77246   if( pOp->p3 ){
77247     newMax = sqlite3BtreeLastPage(pBt);
77248     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
77249   }
77250   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
77251   break;
77252 }
77253 #endif
77254 
77255 
77256 /* Opcode: Init * P2 * P4 *
77257 ** Synopsis:  Start at P2
77258 **
77259 ** Programs contain a single instance of this opcode as the very first
77260 ** opcode.
77261 **
77262 ** If tracing is enabled (by the sqlite3_trace()) interface, then
77263 ** the UTF-8 string contained in P4 is emitted on the trace callback.
77264 ** Or if P4 is blank, use the string returned by sqlite3_sql().
77265 **
77266 ** If P2 is not zero, jump to instruction P2.
77267 */
77268 case OP_Init: {          /* jump */
77269   char *zTrace;
77270   char *z;
77271 
77272 #ifndef SQLITE_OMIT_TRACE
77273   if( db->xTrace
77274    && !p->doingRerun
77275    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
77276   ){
77277     z = sqlite3VdbeExpandSql(p, zTrace);
77278     db->xTrace(db->pTraceArg, z);
77279     sqlite3DbFree(db, z);
77280   }
77281 #ifdef SQLITE_USE_FCNTL_TRACE
77282   zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
77283   if( zTrace ){
77284     int i;
77285     for(i=0; i<db->nDb; i++){
77286       if( DbMaskTest(p->btreeMask, i)==0 ) continue;
77287       sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
77288     }
77289   }
77290 #endif /* SQLITE_USE_FCNTL_TRACE */
77291 #ifdef SQLITE_DEBUG
77292   if( (db->flags & SQLITE_SqlTrace)!=0
77293    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
77294   ){
77295     sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
77296   }
77297 #endif /* SQLITE_DEBUG */
77298 #endif /* SQLITE_OMIT_TRACE */
77299   if( pOp->p2 ) goto jump_to_p2;
77300   break;
77301 }
77302 
77303 
77304 /* Opcode: Noop * * * * *
77305 **
77306 ** Do nothing.  This instruction is often useful as a jump
77307 ** destination.
77308 */
77309 /*
77310 ** The magic Explain opcode are only inserted when explain==2 (which
77311 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
77312 ** This opcode records information from the optimizer.  It is the
77313 ** the same as a no-op.  This opcodesnever appears in a real VM program.
77314 */
77315 default: {          /* This is really OP_Noop and OP_Explain */
77316   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
77317   break;
77318 }
77319 
77320 /*****************************************************************************
77321 ** The cases of the switch statement above this line should all be indented
77322 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
77323 ** readability.  From this point on down, the normal indentation rules are
77324 ** restored.
77325 *****************************************************************************/
77326     }
77327 
77328 #ifdef VDBE_PROFILE
77329     {
77330       u64 endTime = sqlite3Hwtime();
77331       if( endTime>start ) pOrigOp->cycles += endTime - start;
77332       pOrigOp->cnt++;
77333     }
77334 #endif
77335 
77336     /* The following code adds nothing to the actual functionality
77337     ** of the program.  It is only here for testing and debugging.
77338     ** On the other hand, it does burn CPU cycles every time through
77339     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
77340     */
77341 #ifndef NDEBUG
77342     assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
77343 
77344 #ifdef SQLITE_DEBUG
77345     if( db->flags & SQLITE_VdbeTrace ){
77346       if( rc!=0 ) printf("rc=%d\n",rc);
77347       if( pOrigOp->opflags & (OPFLG_OUT2) ){
77348         registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
77349       }
77350       if( pOrigOp->opflags & OPFLG_OUT3 ){
77351         registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
77352       }
77353     }
77354 #endif  /* SQLITE_DEBUG */
77355 #endif  /* NDEBUG */
77356   }  /* The end of the for(;;) loop the loops through opcodes */
77357 
77358   /* If we reach this point, it means that execution is finished with
77359   ** an error of some kind.
77360   */
77361 vdbe_error_halt:
77362   assert( rc );
77363   p->rc = rc;
77364   testcase( sqlite3GlobalConfig.xLog!=0 );
77365   sqlite3_log(rc, "statement aborts at %d: [%s] %s",
77366                    (int)(pOp - aOp), p->zSql, p->zErrMsg);
77367   sqlite3VdbeHalt(p);
77368   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
77369   rc = SQLITE_ERROR;
77370   if( resetSchemaOnFault>0 ){
77371     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
77372   }
77373 
77374   /* This is the only way out of this procedure.  We have to
77375   ** release the mutexes on btrees that were acquired at the
77376   ** top. */
77377 vdbe_return:
77378   db->lastRowid = lastRowid;
77379   testcase( nVmStep>0 );
77380   p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
77381   sqlite3VdbeLeave(p);
77382   return rc;
77383 
77384   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
77385   ** is encountered.
77386   */
77387 too_big:
77388   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
77389   rc = SQLITE_TOOBIG;
77390   goto vdbe_error_halt;
77391 
77392   /* Jump to here if a malloc() fails.
77393   */
77394 no_mem:
77395   db->mallocFailed = 1;
77396   sqlite3SetString(&p->zErrMsg, db, "out of memory");
77397   rc = SQLITE_NOMEM;
77398   goto vdbe_error_halt;
77399 
77400   /* Jump to here for any other kind of fatal error.  The "rc" variable
77401   ** should hold the error number.
77402   */
77403 abort_due_to_error:
77404   assert( p->zErrMsg==0 );
77405   if( db->mallocFailed ) rc = SQLITE_NOMEM;
77406   if( rc!=SQLITE_IOERR_NOMEM ){
77407     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
77408   }
77409   goto vdbe_error_halt;
77410 
77411   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
77412   ** flag.
77413   */
77414 abort_due_to_interrupt:
77415   assert( db->u1.isInterrupted );
77416   rc = SQLITE_INTERRUPT;
77417   p->rc = rc;
77418   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
77419   goto vdbe_error_halt;
77420 }
77421 
77422 
77423 /************** End of vdbe.c ************************************************/
77424 /************** Begin file vdbeblob.c ****************************************/
77425 /*
77426 ** 2007 May 1
77427 **
77428 ** The author disclaims copyright to this source code.  In place of
77429 ** a legal notice, here is a blessing:
77430 **
77431 **    May you do good and not evil.
77432 **    May you find forgiveness for yourself and forgive others.
77433 **    May you share freely, never taking more than you give.
77434 **
77435 *************************************************************************
77436 **
77437 ** This file contains code used to implement incremental BLOB I/O.
77438 */
77439 
77440 
77441 #ifndef SQLITE_OMIT_INCRBLOB
77442 
77443 /*
77444 ** Valid sqlite3_blob* handles point to Incrblob structures.
77445 */
77446 typedef struct Incrblob Incrblob;
77447 struct Incrblob {
77448   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
77449   int nByte;              /* Size of open blob, in bytes */
77450   int iOffset;            /* Byte offset of blob in cursor data */
77451   int iCol;               /* Table column this handle is open on */
77452   BtCursor *pCsr;         /* Cursor pointing at blob row */
77453   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
77454   sqlite3 *db;            /* The associated database */
77455 };
77456 
77457 
77458 /*
77459 ** This function is used by both blob_open() and blob_reopen(). It seeks
77460 ** the b-tree cursor associated with blob handle p to point to row iRow.
77461 ** If successful, SQLITE_OK is returned and subsequent calls to
77462 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
77463 **
77464 ** If an error occurs, or if the specified row does not exist or does not
77465 ** contain a value of type TEXT or BLOB in the column nominated when the
77466 ** blob handle was opened, then an error code is returned and *pzErr may
77467 ** be set to point to a buffer containing an error message. It is the
77468 ** responsibility of the caller to free the error message buffer using
77469 ** sqlite3DbFree().
77470 **
77471 ** If an error does occur, then the b-tree cursor is closed. All subsequent
77472 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
77473 ** immediately return SQLITE_ABORT.
77474 */
77475 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
77476   int rc;                         /* Error code */
77477   char *zErr = 0;                 /* Error message */
77478   Vdbe *v = (Vdbe *)p->pStmt;
77479 
77480   /* Set the value of the SQL statements only variable to integer iRow.
77481   ** This is done directly instead of using sqlite3_bind_int64() to avoid
77482   ** triggering asserts related to mutexes.
77483   */
77484   assert( v->aVar[0].flags&MEM_Int );
77485   v->aVar[0].u.i = iRow;
77486 
77487   rc = sqlite3_step(p->pStmt);
77488   if( rc==SQLITE_ROW ){
77489     VdbeCursor *pC = v->apCsr[0];
77490     u32 type = pC->aType[p->iCol];
77491     if( type<12 ){
77492       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
77493           type==0?"null": type==7?"real": "integer"
77494       );
77495       rc = SQLITE_ERROR;
77496       sqlite3_finalize(p->pStmt);
77497       p->pStmt = 0;
77498     }else{
77499       p->iOffset = pC->aType[p->iCol + pC->nField];
77500       p->nByte = sqlite3VdbeSerialTypeLen(type);
77501       p->pCsr =  pC->pCursor;
77502       sqlite3BtreeIncrblobCursor(p->pCsr);
77503     }
77504   }
77505 
77506   if( rc==SQLITE_ROW ){
77507     rc = SQLITE_OK;
77508   }else if( p->pStmt ){
77509     rc = sqlite3_finalize(p->pStmt);
77510     p->pStmt = 0;
77511     if( rc==SQLITE_OK ){
77512       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
77513       rc = SQLITE_ERROR;
77514     }else{
77515       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
77516     }
77517   }
77518 
77519   assert( rc!=SQLITE_OK || zErr==0 );
77520   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
77521 
77522   *pzErr = zErr;
77523   return rc;
77524 }
77525 
77526 /*
77527 ** Open a blob handle.
77528 */
77529 SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
77530   sqlite3* db,            /* The database connection */
77531   const char *zDb,        /* The attached database containing the blob */
77532   const char *zTable,     /* The table containing the blob */
77533   const char *zColumn,    /* The column containing the blob */
77534   sqlite_int64 iRow,      /* The row containing the glob */
77535   int flags,              /* True -> read/write access, false -> read-only */
77536   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
77537 ){
77538   int nAttempt = 0;
77539   int iCol;               /* Index of zColumn in row-record */
77540 
77541   /* This VDBE program seeks a btree cursor to the identified
77542   ** db/table/row entry. The reason for using a vdbe program instead
77543   ** of writing code to use the b-tree layer directly is that the
77544   ** vdbe program will take advantage of the various transaction,
77545   ** locking and error handling infrastructure built into the vdbe.
77546   **
77547   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
77548   ** Code external to the Vdbe then "borrows" the b-tree cursor and
77549   ** uses it to implement the blob_read(), blob_write() and
77550   ** blob_bytes() functions.
77551   **
77552   ** The sqlite3_blob_close() function finalizes the vdbe program,
77553   ** which closes the b-tree cursor and (possibly) commits the
77554   ** transaction.
77555   */
77556   static const int iLn = VDBE_OFFSET_LINENO(4);
77557   static const VdbeOpList openBlob[] = {
77558     /* {OP_Transaction, 0, 0, 0},  // 0: Inserted separately */
77559     {OP_TableLock, 0, 0, 0},       /* 1: Acquire a read or write lock */
77560     /* One of the following two instructions is replaced by an OP_Noop. */
77561     {OP_OpenRead, 0, 0, 0},        /* 2: Open cursor 0 for reading */
77562     {OP_OpenWrite, 0, 0, 0},       /* 3: Open cursor 0 for read/write */
77563     {OP_Variable, 1, 1, 1},        /* 4: Push the rowid to the stack */
77564     {OP_NotExists, 0, 10, 1},      /* 5: Seek the cursor */
77565     {OP_Column, 0, 0, 1},          /* 6  */
77566     {OP_ResultRow, 1, 0, 0},       /* 7  */
77567     {OP_Goto, 0, 4, 0},            /* 8  */
77568     {OP_Close, 0, 0, 0},           /* 9  */
77569     {OP_Halt, 0, 0, 0},            /* 10 */
77570   };
77571 
77572   int rc = SQLITE_OK;
77573   char *zErr = 0;
77574   Table *pTab;
77575   Parse *pParse = 0;
77576   Incrblob *pBlob = 0;
77577 
77578 #ifdef SQLITE_ENABLE_API_ARMOR
77579   if( ppBlob==0 ){
77580     return SQLITE_MISUSE_BKPT;
77581   }
77582 #endif
77583   *ppBlob = 0;
77584 #ifdef SQLITE_ENABLE_API_ARMOR
77585   if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
77586     return SQLITE_MISUSE_BKPT;
77587   }
77588 #endif
77589   flags = !!flags;                /* flags = (flags ? 1 : 0); */
77590 
77591   sqlite3_mutex_enter(db->mutex);
77592 
77593   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
77594   if( !pBlob ) goto blob_open_out;
77595   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
77596   if( !pParse ) goto blob_open_out;
77597 
77598   do {
77599     memset(pParse, 0, sizeof(Parse));
77600     pParse->db = db;
77601     sqlite3DbFree(db, zErr);
77602     zErr = 0;
77603 
77604     sqlite3BtreeEnterAll(db);
77605     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
77606     if( pTab && IsVirtual(pTab) ){
77607       pTab = 0;
77608       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
77609     }
77610     if( pTab && !HasRowid(pTab) ){
77611       pTab = 0;
77612       sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
77613     }
77614 #ifndef SQLITE_OMIT_VIEW
77615     if( pTab && pTab->pSelect ){
77616       pTab = 0;
77617       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
77618     }
77619 #endif
77620     if( !pTab ){
77621       if( pParse->zErrMsg ){
77622         sqlite3DbFree(db, zErr);
77623         zErr = pParse->zErrMsg;
77624         pParse->zErrMsg = 0;
77625       }
77626       rc = SQLITE_ERROR;
77627       sqlite3BtreeLeaveAll(db);
77628       goto blob_open_out;
77629     }
77630 
77631     /* Now search pTab for the exact column. */
77632     for(iCol=0; iCol<pTab->nCol; iCol++) {
77633       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
77634         break;
77635       }
77636     }
77637     if( iCol==pTab->nCol ){
77638       sqlite3DbFree(db, zErr);
77639       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
77640       rc = SQLITE_ERROR;
77641       sqlite3BtreeLeaveAll(db);
77642       goto blob_open_out;
77643     }
77644 
77645     /* If the value is being opened for writing, check that the
77646     ** column is not indexed, and that it is not part of a foreign key.
77647     ** It is against the rules to open a column to which either of these
77648     ** descriptions applies for writing.  */
77649     if( flags ){
77650       const char *zFault = 0;
77651       Index *pIdx;
77652 #ifndef SQLITE_OMIT_FOREIGN_KEY
77653       if( db->flags&SQLITE_ForeignKeys ){
77654         /* Check that the column is not part of an FK child key definition. It
77655         ** is not necessary to check if it is part of a parent key, as parent
77656         ** key columns must be indexed. The check below will pick up this
77657         ** case.  */
77658         FKey *pFKey;
77659         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
77660           int j;
77661           for(j=0; j<pFKey->nCol; j++){
77662             if( pFKey->aCol[j].iFrom==iCol ){
77663               zFault = "foreign key";
77664             }
77665           }
77666         }
77667       }
77668 #endif
77669       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
77670         int j;
77671         for(j=0; j<pIdx->nKeyCol; j++){
77672           if( pIdx->aiColumn[j]==iCol ){
77673             zFault = "indexed";
77674           }
77675         }
77676       }
77677       if( zFault ){
77678         sqlite3DbFree(db, zErr);
77679         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
77680         rc = SQLITE_ERROR;
77681         sqlite3BtreeLeaveAll(db);
77682         goto blob_open_out;
77683       }
77684     }
77685 
77686     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
77687     assert( pBlob->pStmt || db->mallocFailed );
77688     if( pBlob->pStmt ){
77689       Vdbe *v = (Vdbe *)pBlob->pStmt;
77690       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
77691 
77692 
77693       sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
77694                            pTab->pSchema->schema_cookie,
77695                            pTab->pSchema->iGeneration);
77696       sqlite3VdbeChangeP5(v, 1);
77697       sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
77698 
77699       /* Make sure a mutex is held on the table to be accessed */
77700       sqlite3VdbeUsesBtree(v, iDb);
77701 
77702       /* Configure the OP_TableLock instruction */
77703 #ifdef SQLITE_OMIT_SHARED_CACHE
77704       sqlite3VdbeChangeToNoop(v, 1);
77705 #else
77706       sqlite3VdbeChangeP1(v, 1, iDb);
77707       sqlite3VdbeChangeP2(v, 1, pTab->tnum);
77708       sqlite3VdbeChangeP3(v, 1, flags);
77709       sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
77710 #endif
77711 
77712       /* Remove either the OP_OpenWrite or OpenRead. Set the P2
77713       ** parameter of the other to pTab->tnum.  */
77714       sqlite3VdbeChangeToNoop(v, 3 - flags);
77715       sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
77716       sqlite3VdbeChangeP3(v, 2 + flags, iDb);
77717 
77718       /* Configure the number of columns. Configure the cursor to
77719       ** think that the table has one more column than it really
77720       ** does. An OP_Column to retrieve this imaginary column will
77721       ** always return an SQL NULL. This is useful because it means
77722       ** we can invoke OP_Column to fill in the vdbe cursors type
77723       ** and offset cache without causing any IO.
77724       */
77725       sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
77726       sqlite3VdbeChangeP2(v, 6, pTab->nCol);
77727       if( !db->mallocFailed ){
77728         pParse->nVar = 1;
77729         pParse->nMem = 1;
77730         pParse->nTab = 1;
77731         sqlite3VdbeMakeReady(v, pParse);
77732       }
77733     }
77734 
77735     pBlob->flags = flags;
77736     pBlob->iCol = iCol;
77737     pBlob->db = db;
77738     sqlite3BtreeLeaveAll(db);
77739     if( db->mallocFailed ){
77740       goto blob_open_out;
77741     }
77742     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
77743     rc = blobSeekToRow(pBlob, iRow, &zErr);
77744   } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
77745 
77746 blob_open_out:
77747   if( rc==SQLITE_OK && db->mallocFailed==0 ){
77748     *ppBlob = (sqlite3_blob *)pBlob;
77749   }else{
77750     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
77751     sqlite3DbFree(db, pBlob);
77752   }
77753   sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
77754   sqlite3DbFree(db, zErr);
77755   sqlite3ParserReset(pParse);
77756   sqlite3StackFree(db, pParse);
77757   rc = sqlite3ApiExit(db, rc);
77758   sqlite3_mutex_leave(db->mutex);
77759   return rc;
77760 }
77761 
77762 /*
77763 ** Close a blob handle that was previously created using
77764 ** sqlite3_blob_open().
77765 */
77766 SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *pBlob){
77767   Incrblob *p = (Incrblob *)pBlob;
77768   int rc;
77769   sqlite3 *db;
77770 
77771   if( p ){
77772     db = p->db;
77773     sqlite3_mutex_enter(db->mutex);
77774     rc = sqlite3_finalize(p->pStmt);
77775     sqlite3DbFree(db, p);
77776     sqlite3_mutex_leave(db->mutex);
77777   }else{
77778     rc = SQLITE_OK;
77779   }
77780   return rc;
77781 }
77782 
77783 /*
77784 ** Perform a read or write operation on a blob
77785 */
77786 static int blobReadWrite(
77787   sqlite3_blob *pBlob,
77788   void *z,
77789   int n,
77790   int iOffset,
77791   int (*xCall)(BtCursor*, u32, u32, void*)
77792 ){
77793   int rc;
77794   Incrblob *p = (Incrblob *)pBlob;
77795   Vdbe *v;
77796   sqlite3 *db;
77797 
77798   if( p==0 ) return SQLITE_MISUSE_BKPT;
77799   db = p->db;
77800   sqlite3_mutex_enter(db->mutex);
77801   v = (Vdbe*)p->pStmt;
77802 
77803   if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
77804     /* Request is out of range. Return a transient error. */
77805     rc = SQLITE_ERROR;
77806   }else if( v==0 ){
77807     /* If there is no statement handle, then the blob-handle has
77808     ** already been invalidated. Return SQLITE_ABORT in this case.
77809     */
77810     rc = SQLITE_ABORT;
77811   }else{
77812     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
77813     ** returned, clean-up the statement handle.
77814     */
77815     assert( db == v->db );
77816     sqlite3BtreeEnterCursor(p->pCsr);
77817     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
77818     sqlite3BtreeLeaveCursor(p->pCsr);
77819     if( rc==SQLITE_ABORT ){
77820       sqlite3VdbeFinalize(v);
77821       p->pStmt = 0;
77822     }else{
77823       v->rc = rc;
77824     }
77825   }
77826   sqlite3Error(db, rc);
77827   rc = sqlite3ApiExit(db, rc);
77828   sqlite3_mutex_leave(db->mutex);
77829   return rc;
77830 }
77831 
77832 /*
77833 ** Read data from a blob handle.
77834 */
77835 SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
77836   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
77837 }
77838 
77839 /*
77840 ** Write data to a blob handle.
77841 */
77842 SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
77843   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
77844 }
77845 
77846 /*
77847 ** Query a blob handle for the size of the data.
77848 **
77849 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
77850 ** so no mutex is required for access.
77851 */
77852 SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *pBlob){
77853   Incrblob *p = (Incrblob *)pBlob;
77854   return (p && p->pStmt) ? p->nByte : 0;
77855 }
77856 
77857 /*
77858 ** Move an existing blob handle to point to a different row of the same
77859 ** database table.
77860 **
77861 ** If an error occurs, or if the specified row does not exist or does not
77862 ** contain a blob or text value, then an error code is returned and the
77863 ** database handle error code and message set. If this happens, then all
77864 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
77865 ** immediately return SQLITE_ABORT.
77866 */
77867 SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
77868   int rc;
77869   Incrblob *p = (Incrblob *)pBlob;
77870   sqlite3 *db;
77871 
77872   if( p==0 ) return SQLITE_MISUSE_BKPT;
77873   db = p->db;
77874   sqlite3_mutex_enter(db->mutex);
77875 
77876   if( p->pStmt==0 ){
77877     /* If there is no statement handle, then the blob-handle has
77878     ** already been invalidated. Return SQLITE_ABORT in this case.
77879     */
77880     rc = SQLITE_ABORT;
77881   }else{
77882     char *zErr;
77883     rc = blobSeekToRow(p, iRow, &zErr);
77884     if( rc!=SQLITE_OK ){
77885       sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
77886       sqlite3DbFree(db, zErr);
77887     }
77888     assert( rc!=SQLITE_SCHEMA );
77889   }
77890 
77891   rc = sqlite3ApiExit(db, rc);
77892   assert( rc==SQLITE_OK || p->pStmt==0 );
77893   sqlite3_mutex_leave(db->mutex);
77894   return rc;
77895 }
77896 
77897 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
77898 
77899 /************** End of vdbeblob.c ********************************************/
77900 /************** Begin file vdbesort.c ****************************************/
77901 /*
77902 ** 2011-07-09
77903 **
77904 ** The author disclaims copyright to this source code.  In place of
77905 ** a legal notice, here is a blessing:
77906 **
77907 **    May you do good and not evil.
77908 **    May you find forgiveness for yourself and forgive others.
77909 **    May you share freely, never taking more than you give.
77910 **
77911 *************************************************************************
77912 ** This file contains code for the VdbeSorter object, used in concert with
77913 ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
77914 ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
77915 ** using indexes and without LIMIT clauses.
77916 **
77917 ** The VdbeSorter object implements a multi-threaded external merge sort
77918 ** algorithm that is efficient even if the number of elements being sorted
77919 ** exceeds the available memory.
77920 **
77921 ** Here is the (internal, non-API) interface between this module and the
77922 ** rest of the SQLite system:
77923 **
77924 **    sqlite3VdbeSorterInit()       Create a new VdbeSorter object.
77925 **
77926 **    sqlite3VdbeSorterWrite()      Add a single new row to the VdbeSorter
77927 **                                  object.  The row is a binary blob in the
77928 **                                  OP_MakeRecord format that contains both
77929 **                                  the ORDER BY key columns and result columns
77930 **                                  in the case of a SELECT w/ ORDER BY, or
77931 **                                  the complete record for an index entry
77932 **                                  in the case of a CREATE INDEX.
77933 **
77934 **    sqlite3VdbeSorterRewind()     Sort all content previously added.
77935 **                                  Position the read cursor on the
77936 **                                  first sorted element.
77937 **
77938 **    sqlite3VdbeSorterNext()       Advance the read cursor to the next sorted
77939 **                                  element.
77940 **
77941 **    sqlite3VdbeSorterRowkey()     Return the complete binary blob for the
77942 **                                  row currently under the read cursor.
77943 **
77944 **    sqlite3VdbeSorterCompare()    Compare the binary blob for the row
77945 **                                  currently under the read cursor against
77946 **                                  another binary blob X and report if
77947 **                                  X is strictly less than the read cursor.
77948 **                                  Used to enforce uniqueness in a
77949 **                                  CREATE UNIQUE INDEX statement.
77950 **
77951 **    sqlite3VdbeSorterClose()      Close the VdbeSorter object and reclaim
77952 **                                  all resources.
77953 **
77954 **    sqlite3VdbeSorterReset()      Refurbish the VdbeSorter for reuse.  This
77955 **                                  is like Close() followed by Init() only
77956 **                                  much faster.
77957 **
77958 ** The interfaces above must be called in a particular order.  Write() can
77959 ** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and
77960 ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
77961 **
77962 **   Init()
77963 **   for each record: Write()
77964 **   Rewind()
77965 **     Rowkey()/Compare()
77966 **   Next()
77967 **   Close()
77968 **
77969 ** Algorithm:
77970 **
77971 ** Records passed to the sorter via calls to Write() are initially held
77972 ** unsorted in main memory. Assuming the amount of memory used never exceeds
77973 ** a threshold, when Rewind() is called the set of records is sorted using
77974 ** an in-memory merge sort. In this case, no temporary files are required
77975 ** and subsequent calls to Rowkey(), Next() and Compare() read records
77976 ** directly from main memory.
77977 **
77978 ** If the amount of space used to store records in main memory exceeds the
77979 ** threshold, then the set of records currently in memory are sorted and
77980 ** written to a temporary file in "Packed Memory Array" (PMA) format.
77981 ** A PMA created at this point is known as a "level-0 PMA". Higher levels
77982 ** of PMAs may be created by merging existing PMAs together - for example
77983 ** merging two or more level-0 PMAs together creates a level-1 PMA.
77984 **
77985 ** The threshold for the amount of main memory to use before flushing
77986 ** records to a PMA is roughly the same as the limit configured for the
77987 ** page-cache of the main database. Specifically, the threshold is set to
77988 ** the value returned by "PRAGMA main.page_size" multipled by
77989 ** that returned by "PRAGMA main.cache_size", in bytes.
77990 **
77991 ** If the sorter is running in single-threaded mode, then all PMAs generated
77992 ** are appended to a single temporary file. Or, if the sorter is running in
77993 ** multi-threaded mode then up to (N+1) temporary files may be opened, where
77994 ** N is the configured number of worker threads. In this case, instead of
77995 ** sorting the records and writing the PMA to a temporary file itself, the
77996 ** calling thread usually launches a worker thread to do so. Except, if
77997 ** there are already N worker threads running, the main thread does the work
77998 ** itself.
77999 **
78000 ** The sorter is running in multi-threaded mode if (a) the library was built
78001 ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
78002 ** than zero, and (b) worker threads have been enabled at runtime by calling
78003 ** "PRAGMA threads=N" with some value of N greater than 0.
78004 **
78005 ** When Rewind() is called, any data remaining in memory is flushed to a
78006 ** final PMA. So at this point the data is stored in some number of sorted
78007 ** PMAs within temporary files on disk.
78008 **
78009 ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
78010 ** sorter is running in single-threaded mode, then these PMAs are merged
78011 ** incrementally as keys are retreived from the sorter by the VDBE.  The
78012 ** MergeEngine object, described in further detail below, performs this
78013 ** merge.
78014 **
78015 ** Or, if running in multi-threaded mode, then a background thread is
78016 ** launched to merge the existing PMAs. Once the background thread has
78017 ** merged T bytes of data into a single sorted PMA, the main thread
78018 ** begins reading keys from that PMA while the background thread proceeds
78019 ** with merging the next T bytes of data. And so on.
78020 **
78021 ** Parameter T is set to half the value of the memory threshold used
78022 ** by Write() above to determine when to create a new PMA.
78023 **
78024 ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
78025 ** Rewind() is called, then a hierarchy of incremental-merges is used.
78026 ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
78027 ** disk are merged together. Then T bytes of data from the second set, and
78028 ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
78029 ** PMAs at a time. This done is to improve locality.
78030 **
78031 ** If running in multi-threaded mode and there are more than
78032 ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
78033 ** than one background thread may be created. Specifically, there may be
78034 ** one background thread for each temporary file on disk, and one background
78035 ** thread to merge the output of each of the others to a single PMA for
78036 ** the main thread to read from.
78037 */
78038 
78039 /*
78040 ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
78041 ** messages to stderr that may be helpful in understanding the performance
78042 ** characteristics of the sorter in multi-threaded mode.
78043 */
78044 #if 0
78045 # define SQLITE_DEBUG_SORTER_THREADS 1
78046 #endif
78047 
78048 /*
78049 ** Hard-coded maximum amount of data to accumulate in memory before flushing
78050 ** to a level 0 PMA. The purpose of this limit is to prevent various integer
78051 ** overflows. 512MiB.
78052 */
78053 #define SQLITE_MAX_PMASZ    (1<<29)
78054 
78055 /*
78056 ** Private objects used by the sorter
78057 */
78058 typedef struct MergeEngine MergeEngine;     /* Merge PMAs together */
78059 typedef struct PmaReader PmaReader;         /* Incrementally read one PMA */
78060 typedef struct PmaWriter PmaWriter;         /* Incrementally write one PMA */
78061 typedef struct SorterRecord SorterRecord;   /* A record being sorted */
78062 typedef struct SortSubtask SortSubtask;     /* A sub-task in the sort process */
78063 typedef struct SorterFile SorterFile;       /* Temporary file object wrapper */
78064 typedef struct SorterList SorterList;       /* In-memory list of records */
78065 typedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */
78066 
78067 /*
78068 ** A container for a temp file handle and the current amount of data
78069 ** stored in the file.
78070 */
78071 struct SorterFile {
78072   sqlite3_file *pFd;              /* File handle */
78073   i64 iEof;                       /* Bytes of data stored in pFd */
78074 };
78075 
78076 /*
78077 ** An in-memory list of objects to be sorted.
78078 **
78079 ** If aMemory==0 then each object is allocated separately and the objects
78080 ** are connected using SorterRecord.u.pNext.  If aMemory!=0 then all objects
78081 ** are stored in the aMemory[] bulk memory, one right after the other, and
78082 ** are connected using SorterRecord.u.iNext.
78083 */
78084 struct SorterList {
78085   SorterRecord *pList;            /* Linked list of records */
78086   u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */
78087   int szPMA;                      /* Size of pList as PMA in bytes */
78088 };
78089 
78090 /*
78091 ** The MergeEngine object is used to combine two or more smaller PMAs into
78092 ** one big PMA using a merge operation.  Separate PMAs all need to be
78093 ** combined into one big PMA in order to be able to step through the sorted
78094 ** records in order.
78095 **
78096 ** The aReadr[] array contains a PmaReader object for each of the PMAs being
78097 ** merged.  An aReadr[] object either points to a valid key or else is at EOF.
78098 ** ("EOF" means "End Of File".  When aReadr[] is at EOF there is no more data.)
78099 ** For the purposes of the paragraphs below, we assume that the array is
78100 ** actually N elements in size, where N is the smallest power of 2 greater
78101 ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
78102 ** are treated as if they are empty (always at EOF).
78103 **
78104 ** The aTree[] array is also N elements in size. The value of N is stored in
78105 ** the MergeEngine.nTree variable.
78106 **
78107 ** The final (N/2) elements of aTree[] contain the results of comparing
78108 ** pairs of PMA keys together. Element i contains the result of
78109 ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
78110 ** aTree element is set to the index of it.
78111 **
78112 ** For the purposes of this comparison, EOF is considered greater than any
78113 ** other key value. If the keys are equal (only possible with two EOF
78114 ** values), it doesn't matter which index is stored.
78115 **
78116 ** The (N/4) elements of aTree[] that precede the final (N/2) described
78117 ** above contains the index of the smallest of each block of 4 PmaReaders
78118 ** And so on. So that aTree[1] contains the index of the PmaReader that
78119 ** currently points to the smallest key value. aTree[0] is unused.
78120 **
78121 ** Example:
78122 **
78123 **     aReadr[0] -> Banana
78124 **     aReadr[1] -> Feijoa
78125 **     aReadr[2] -> Elderberry
78126 **     aReadr[3] -> Currant
78127 **     aReadr[4] -> Grapefruit
78128 **     aReadr[5] -> Apple
78129 **     aReadr[6] -> Durian
78130 **     aReadr[7] -> EOF
78131 **
78132 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
78133 **
78134 ** The current element is "Apple" (the value of the key indicated by
78135 ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
78136 ** be advanced to the next key in its segment. Say the next key is
78137 ** "Eggplant":
78138 **
78139 **     aReadr[5] -> Eggplant
78140 **
78141 ** The contents of aTree[] are updated first by comparing the new PmaReader
78142 ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
78143 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
78144 ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
78145 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
78146 ** so the value written into element 1 of the array is 0. As follows:
78147 **
78148 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
78149 **
78150 ** In other words, each time we advance to the next sorter element, log2(N)
78151 ** key comparison operations are required, where N is the number of segments
78152 ** being merged (rounded up to the next power of 2).
78153 */
78154 struct MergeEngine {
78155   int nTree;                 /* Used size of aTree/aReadr (power of 2) */
78156   SortSubtask *pTask;        /* Used by this thread only */
78157   int *aTree;                /* Current state of incremental merge */
78158   PmaReader *aReadr;         /* Array of PmaReaders to merge data from */
78159 };
78160 
78161 /*
78162 ** This object represents a single thread of control in a sort operation.
78163 ** Exactly VdbeSorter.nTask instances of this object are allocated
78164 ** as part of each VdbeSorter object. Instances are never allocated any
78165 ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
78166 ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread).  Thus for
78167 ** single-threaded operation, there is exactly one instance of this object
78168 ** and for multi-threaded operation there are two or more instances.
78169 **
78170 ** Essentially, this structure contains all those fields of the VdbeSorter
78171 ** structure for which each thread requires a separate instance. For example,
78172 ** each thread requries its own UnpackedRecord object to unpack records in
78173 ** as part of comparison operations.
78174 **
78175 ** Before a background thread is launched, variable bDone is set to 0. Then,
78176 ** right before it exits, the thread itself sets bDone to 1. This is used for
78177 ** two purposes:
78178 **
78179 **   1. When flushing the contents of memory to a level-0 PMA on disk, to
78180 **      attempt to select a SortSubtask for which there is not already an
78181 **      active background thread (since doing so causes the main thread
78182 **      to block until it finishes).
78183 **
78184 **   2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
78185 **      to sqlite3ThreadJoin() is likely to block. Cases that are likely to
78186 **      block provoke debugging output.
78187 **
78188 ** In both cases, the effects of the main thread seeing (bDone==0) even
78189 ** after the thread has finished are not dire. So we don't worry about
78190 ** memory barriers and such here.
78191 */
78192 typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
78193 struct SortSubtask {
78194   SQLiteThread *pThread;          /* Background thread, if any */
78195   int bDone;                      /* Set if thread is finished but not joined */
78196   VdbeSorter *pSorter;            /* Sorter that owns this sub-task */
78197   UnpackedRecord *pUnpacked;      /* Space to unpack a record */
78198   SorterList list;                /* List for thread to write to a PMA */
78199   int nPMA;                       /* Number of PMAs currently in file */
78200   SorterCompare xCompare;         /* Compare function to use */
78201   SorterFile file;                /* Temp file for level-0 PMAs */
78202   SorterFile file2;               /* Space for other PMAs */
78203 };
78204 
78205 
78206 /*
78207 ** Main sorter structure. A single instance of this is allocated for each
78208 ** sorter cursor created by the VDBE.
78209 **
78210 ** mxKeysize:
78211 **   As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
78212 **   this variable is updated so as to be set to the size on disk of the
78213 **   largest record in the sorter.
78214 */
78215 struct VdbeSorter {
78216   int mnPmaSize;                  /* Minimum PMA size, in bytes */
78217   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
78218   int mxKeysize;                  /* Largest serialized key seen so far */
78219   int pgsz;                       /* Main database page size */
78220   PmaReader *pReader;             /* Readr data from here after Rewind() */
78221   MergeEngine *pMerger;           /* Or here, if bUseThreads==0 */
78222   sqlite3 *db;                    /* Database connection */
78223   KeyInfo *pKeyInfo;              /* How to compare records */
78224   UnpackedRecord *pUnpacked;      /* Used by VdbeSorterCompare() */
78225   SorterList list;                /* List of in-memory records */
78226   int iMemory;                    /* Offset of free space in list.aMemory */
78227   int nMemory;                    /* Size of list.aMemory allocation in bytes */
78228   u8 bUsePMA;                     /* True if one or more PMAs created */
78229   u8 bUseThreads;                 /* True to use background threads */
78230   u8 iPrev;                       /* Previous thread used to flush PMA */
78231   u8 nTask;                       /* Size of aTask[] array */
78232   u8 typeMask;
78233   SortSubtask aTask[1];           /* One or more subtasks */
78234 };
78235 
78236 #define SORTER_TYPE_INTEGER 0x01
78237 #define SORTER_TYPE_TEXT    0x02
78238 
78239 /*
78240 ** An instance of the following object is used to read records out of a
78241 ** PMA, in sorted order.  The next key to be read is cached in nKey/aKey.
78242 ** aKey might point into aMap or into aBuffer.  If neither of those locations
78243 ** contain a contiguous representation of the key, then aAlloc is allocated
78244 ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
78245 **
78246 ** pFd==0 at EOF.
78247 */
78248 struct PmaReader {
78249   i64 iReadOff;               /* Current read offset */
78250   i64 iEof;                   /* 1 byte past EOF for this PmaReader */
78251   int nAlloc;                 /* Bytes of space at aAlloc */
78252   int nKey;                   /* Number of bytes in key */
78253   sqlite3_file *pFd;          /* File handle we are reading from */
78254   u8 *aAlloc;                 /* Space for aKey if aBuffer and pMap wont work */
78255   u8 *aKey;                   /* Pointer to current key */
78256   u8 *aBuffer;                /* Current read buffer */
78257   int nBuffer;                /* Size of read buffer in bytes */
78258   u8 *aMap;                   /* Pointer to mapping of entire file */
78259   IncrMerger *pIncr;          /* Incremental merger */
78260 };
78261 
78262 /*
78263 ** Normally, a PmaReader object iterates through an existing PMA stored
78264 ** within a temp file. However, if the PmaReader.pIncr variable points to
78265 ** an object of the following type, it may be used to iterate/merge through
78266 ** multiple PMAs simultaneously.
78267 **
78268 ** There are two types of IncrMerger object - single (bUseThread==0) and
78269 ** multi-threaded (bUseThread==1).
78270 **
78271 ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
78272 ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
78273 ** size. When the IncrMerger is initialized, it reads enough data from
78274 ** pMerger to populate aFile[0]. It then sets variables within the
78275 ** corresponding PmaReader object to read from that file and kicks off
78276 ** a background thread to populate aFile[1] with the next mxSz bytes of
78277 ** sorted record data from pMerger.
78278 **
78279 ** When the PmaReader reaches the end of aFile[0], it blocks until the
78280 ** background thread has finished populating aFile[1]. It then exchanges
78281 ** the contents of the aFile[0] and aFile[1] variables within this structure,
78282 ** sets the PmaReader fields to read from the new aFile[0] and kicks off
78283 ** another background thread to populate the new aFile[1]. And so on, until
78284 ** the contents of pMerger are exhausted.
78285 **
78286 ** A single-threaded IncrMerger does not open any temporary files of its
78287 ** own. Instead, it has exclusive access to mxSz bytes of space beginning
78288 ** at offset iStartOff of file pTask->file2. And instead of using a
78289 ** background thread to prepare data for the PmaReader, with a single
78290 ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
78291 ** keys from pMerger by the calling thread whenever the PmaReader runs out
78292 ** of data.
78293 */
78294 struct IncrMerger {
78295   SortSubtask *pTask;             /* Task that owns this merger */
78296   MergeEngine *pMerger;           /* Merge engine thread reads data from */
78297   i64 iStartOff;                  /* Offset to start writing file at */
78298   int mxSz;                       /* Maximum bytes of data to store */
78299   int bEof;                       /* Set to true when merge is finished */
78300   int bUseThread;                 /* True to use a bg thread for this object */
78301   SorterFile aFile[2];            /* aFile[0] for reading, [1] for writing */
78302 };
78303 
78304 /*
78305 ** An instance of this object is used for writing a PMA.
78306 **
78307 ** The PMA is written one record at a time.  Each record is of an arbitrary
78308 ** size.  But I/O is more efficient if it occurs in page-sized blocks where
78309 ** each block is aligned on a page boundary.  This object caches writes to
78310 ** the PMA so that aligned, page-size blocks are written.
78311 */
78312 struct PmaWriter {
78313   int eFWErr;                     /* Non-zero if in an error state */
78314   u8 *aBuffer;                    /* Pointer to write buffer */
78315   int nBuffer;                    /* Size of write buffer in bytes */
78316   int iBufStart;                  /* First byte of buffer to write */
78317   int iBufEnd;                    /* Last byte of buffer to write */
78318   i64 iWriteOff;                  /* Offset of start of buffer in file */
78319   sqlite3_file *pFd;              /* File handle to write to */
78320 };
78321 
78322 /*
78323 ** This object is the header on a single record while that record is being
78324 ** held in memory and prior to being written out as part of a PMA.
78325 **
78326 ** How the linked list is connected depends on how memory is being managed
78327 ** by this module. If using a separate allocation for each in-memory record
78328 ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
78329 ** SorterRecord.u.pNext pointers.
78330 **
78331 ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
78332 ** then while records are being accumulated the list is linked using the
78333 ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
78334 ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
78335 ** has finished passing records to the sorter, or when the in-memory buffer
78336 ** is full, the list is sorted. As part of the sorting process, it is
78337 ** converted to use the SorterRecord.u.pNext pointers. See function
78338 ** vdbeSorterSort() for details.
78339 */
78340 struct SorterRecord {
78341   int nVal;                       /* Size of the record in bytes */
78342   union {
78343     SorterRecord *pNext;          /* Pointer to next record in list */
78344     int iNext;                    /* Offset within aMemory of next record */
78345   } u;
78346   /* The data for the record immediately follows this header */
78347 };
78348 
78349 /* Return a pointer to the buffer containing the record data for SorterRecord
78350 ** object p. Should be used as if:
78351 **
78352 **   void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
78353 */
78354 #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
78355 
78356 
78357 /* Maximum number of PMAs that a single MergeEngine can merge */
78358 #define SORTER_MAX_MERGE_COUNT 16
78359 
78360 static int vdbeIncrSwap(IncrMerger*);
78361 static void vdbeIncrFree(IncrMerger *);
78362 
78363 /*
78364 ** Free all memory belonging to the PmaReader object passed as the
78365 ** argument. All structure fields are set to zero before returning.
78366 */
78367 static void vdbePmaReaderClear(PmaReader *pReadr){
78368   sqlite3_free(pReadr->aAlloc);
78369   sqlite3_free(pReadr->aBuffer);
78370   if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
78371   vdbeIncrFree(pReadr->pIncr);
78372   memset(pReadr, 0, sizeof(PmaReader));
78373 }
78374 
78375 /*
78376 ** Read the next nByte bytes of data from the PMA p.
78377 ** If successful, set *ppOut to point to a buffer containing the data
78378 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
78379 ** error code.
78380 **
78381 ** The buffer returned in *ppOut is only valid until the
78382 ** next call to this function.
78383 */
78384 static int vdbePmaReadBlob(
78385   PmaReader *p,                   /* PmaReader from which to take the blob */
78386   int nByte,                      /* Bytes of data to read */
78387   u8 **ppOut                      /* OUT: Pointer to buffer containing data */
78388 ){
78389   int iBuf;                       /* Offset within buffer to read from */
78390   int nAvail;                     /* Bytes of data available in buffer */
78391 
78392   if( p->aMap ){
78393     *ppOut = &p->aMap[p->iReadOff];
78394     p->iReadOff += nByte;
78395     return SQLITE_OK;
78396   }
78397 
78398   assert( p->aBuffer );
78399 
78400   /* If there is no more data to be read from the buffer, read the next
78401   ** p->nBuffer bytes of data from the file into it. Or, if there are less
78402   ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
78403   iBuf = p->iReadOff % p->nBuffer;
78404   if( iBuf==0 ){
78405     int nRead;                    /* Bytes to read from disk */
78406     int rc;                       /* sqlite3OsRead() return code */
78407 
78408     /* Determine how many bytes of data to read. */
78409     if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
78410       nRead = p->nBuffer;
78411     }else{
78412       nRead = (int)(p->iEof - p->iReadOff);
78413     }
78414     assert( nRead>0 );
78415 
78416     /* Readr data from the file. Return early if an error occurs. */
78417     rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
78418     assert( rc!=SQLITE_IOERR_SHORT_READ );
78419     if( rc!=SQLITE_OK ) return rc;
78420   }
78421   nAvail = p->nBuffer - iBuf;
78422 
78423   if( nByte<=nAvail ){
78424     /* The requested data is available in the in-memory buffer. In this
78425     ** case there is no need to make a copy of the data, just return a
78426     ** pointer into the buffer to the caller.  */
78427     *ppOut = &p->aBuffer[iBuf];
78428     p->iReadOff += nByte;
78429   }else{
78430     /* The requested data is not all available in the in-memory buffer.
78431     ** In this case, allocate space at p->aAlloc[] to copy the requested
78432     ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
78433     int nRem;                     /* Bytes remaining to copy */
78434 
78435     /* Extend the p->aAlloc[] allocation if required. */
78436     if( p->nAlloc<nByte ){
78437       u8 *aNew;
78438       int nNew = MAX(128, p->nAlloc*2);
78439       while( nByte>nNew ) nNew = nNew*2;
78440       aNew = sqlite3Realloc(p->aAlloc, nNew);
78441       if( !aNew ) return SQLITE_NOMEM;
78442       p->nAlloc = nNew;
78443       p->aAlloc = aNew;
78444     }
78445 
78446     /* Copy as much data as is available in the buffer into the start of
78447     ** p->aAlloc[].  */
78448     memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
78449     p->iReadOff += nAvail;
78450     nRem = nByte - nAvail;
78451 
78452     /* The following loop copies up to p->nBuffer bytes per iteration into
78453     ** the p->aAlloc[] buffer.  */
78454     while( nRem>0 ){
78455       int rc;                     /* vdbePmaReadBlob() return code */
78456       int nCopy;                  /* Number of bytes to copy */
78457       u8 *aNext;                  /* Pointer to buffer to copy data from */
78458 
78459       nCopy = nRem;
78460       if( nRem>p->nBuffer ) nCopy = p->nBuffer;
78461       rc = vdbePmaReadBlob(p, nCopy, &aNext);
78462       if( rc!=SQLITE_OK ) return rc;
78463       assert( aNext!=p->aAlloc );
78464       memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
78465       nRem -= nCopy;
78466     }
78467 
78468     *ppOut = p->aAlloc;
78469   }
78470 
78471   return SQLITE_OK;
78472 }
78473 
78474 /*
78475 ** Read a varint from the stream of data accessed by p. Set *pnOut to
78476 ** the value read.
78477 */
78478 static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
78479   int iBuf;
78480 
78481   if( p->aMap ){
78482     p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
78483   }else{
78484     iBuf = p->iReadOff % p->nBuffer;
78485     if( iBuf && (p->nBuffer-iBuf)>=9 ){
78486       p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
78487     }else{
78488       u8 aVarint[16], *a;
78489       int i = 0, rc;
78490       do{
78491         rc = vdbePmaReadBlob(p, 1, &a);
78492         if( rc ) return rc;
78493         aVarint[(i++)&0xf] = a[0];
78494       }while( (a[0]&0x80)!=0 );
78495       sqlite3GetVarint(aVarint, pnOut);
78496     }
78497   }
78498 
78499   return SQLITE_OK;
78500 }
78501 
78502 /*
78503 ** Attempt to memory map file pFile. If successful, set *pp to point to the
78504 ** new mapping and return SQLITE_OK. If the mapping is not attempted
78505 ** (because the file is too large or the VFS layer is configured not to use
78506 ** mmap), return SQLITE_OK and set *pp to NULL.
78507 **
78508 ** Or, if an error occurs, return an SQLite error code. The final value of
78509 ** *pp is undefined in this case.
78510 */
78511 static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
78512   int rc = SQLITE_OK;
78513   if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
78514     sqlite3_file *pFd = pFile->pFd;
78515     if( pFd->pMethods->iVersion>=3 ){
78516       rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
78517       testcase( rc!=SQLITE_OK );
78518     }
78519   }
78520   return rc;
78521 }
78522 
78523 /*
78524 ** Attach PmaReader pReadr to file pFile (if it is not already attached to
78525 ** that file) and seek it to offset iOff within the file.  Return SQLITE_OK
78526 ** if successful, or an SQLite error code if an error occurs.
78527 */
78528 static int vdbePmaReaderSeek(
78529   SortSubtask *pTask,             /* Task context */
78530   PmaReader *pReadr,              /* Reader whose cursor is to be moved */
78531   SorterFile *pFile,              /* Sorter file to read from */
78532   i64 iOff                        /* Offset in pFile */
78533 ){
78534   int rc = SQLITE_OK;
78535 
78536   assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
78537 
78538   if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
78539   if( pReadr->aMap ){
78540     sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
78541     pReadr->aMap = 0;
78542   }
78543   pReadr->iReadOff = iOff;
78544   pReadr->iEof = pFile->iEof;
78545   pReadr->pFd = pFile->pFd;
78546 
78547   rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
78548   if( rc==SQLITE_OK && pReadr->aMap==0 ){
78549     int pgsz = pTask->pSorter->pgsz;
78550     int iBuf = pReadr->iReadOff % pgsz;
78551     if( pReadr->aBuffer==0 ){
78552       pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
78553       if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM;
78554       pReadr->nBuffer = pgsz;
78555     }
78556     if( rc==SQLITE_OK && iBuf ){
78557       int nRead = pgsz - iBuf;
78558       if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
78559         nRead = (int)(pReadr->iEof - pReadr->iReadOff);
78560       }
78561       rc = sqlite3OsRead(
78562           pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
78563       );
78564       testcase( rc!=SQLITE_OK );
78565     }
78566   }
78567 
78568   return rc;
78569 }
78570 
78571 /*
78572 ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
78573 ** no error occurs, or an SQLite error code if one does.
78574 */
78575 static int vdbePmaReaderNext(PmaReader *pReadr){
78576   int rc = SQLITE_OK;             /* Return Code */
78577   u64 nRec = 0;                   /* Size of record in bytes */
78578 
78579 
78580   if( pReadr->iReadOff>=pReadr->iEof ){
78581     IncrMerger *pIncr = pReadr->pIncr;
78582     int bEof = 1;
78583     if( pIncr ){
78584       rc = vdbeIncrSwap(pIncr);
78585       if( rc==SQLITE_OK && pIncr->bEof==0 ){
78586         rc = vdbePmaReaderSeek(
78587             pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
78588         );
78589         bEof = 0;
78590       }
78591     }
78592 
78593     if( bEof ){
78594       /* This is an EOF condition */
78595       vdbePmaReaderClear(pReadr);
78596       testcase( rc!=SQLITE_OK );
78597       return rc;
78598     }
78599   }
78600 
78601   if( rc==SQLITE_OK ){
78602     rc = vdbePmaReadVarint(pReadr, &nRec);
78603   }
78604   if( rc==SQLITE_OK ){
78605     pReadr->nKey = (int)nRec;
78606     rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
78607     testcase( rc!=SQLITE_OK );
78608   }
78609 
78610   return rc;
78611 }
78612 
78613 /*
78614 ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
78615 ** starting at offset iStart and ending at offset iEof-1. This function
78616 ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
78617 ** PMA is empty).
78618 **
78619 ** If the pnByte parameter is NULL, then it is assumed that the file
78620 ** contains a single PMA, and that that PMA omits the initial length varint.
78621 */
78622 static int vdbePmaReaderInit(
78623   SortSubtask *pTask,             /* Task context */
78624   SorterFile *pFile,              /* Sorter file to read from */
78625   i64 iStart,                     /* Start offset in pFile */
78626   PmaReader *pReadr,              /* PmaReader to populate */
78627   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
78628 ){
78629   int rc;
78630 
78631   assert( pFile->iEof>iStart );
78632   assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
78633   assert( pReadr->aBuffer==0 );
78634   assert( pReadr->aMap==0 );
78635 
78636   rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
78637   if( rc==SQLITE_OK ){
78638     u64 nByte;                    /* Size of PMA in bytes */
78639     rc = vdbePmaReadVarint(pReadr, &nByte);
78640     pReadr->iEof = pReadr->iReadOff + nByte;
78641     *pnByte += nByte;
78642   }
78643 
78644   if( rc==SQLITE_OK ){
78645     rc = vdbePmaReaderNext(pReadr);
78646   }
78647   return rc;
78648 }
78649 
78650 /*
78651 ** A version of vdbeSorterCompare() that assumes that it has already been
78652 ** determined that the first field of key1 is equal to the first field of
78653 ** key2.
78654 */
78655 static int vdbeSorterCompareTail(
78656   SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
78657   int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
78658   const void *pKey1, int nKey1,   /* Left side of comparison */
78659   const void *pKey2, int nKey2    /* Right side of comparison */
78660 ){
78661   UnpackedRecord *r2 = pTask->pUnpacked;
78662   if( *pbKey2Cached==0 ){
78663     sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
78664     *pbKey2Cached = 1;
78665   }
78666   return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
78667 }
78668 
78669 /*
78670 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
78671 ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
78672 ** used by the comparison. Return the result of the comparison.
78673 **
78674 ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
78675 ** it is assumed that (pTask->pUnpacked) contains the unpacked version
78676 ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
78677 ** version of key2 and *pbKey2Cached set to true before returning.
78678 **
78679 ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
78680 ** to SQLITE_NOMEM.
78681 */
78682 static int vdbeSorterCompare(
78683   SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
78684   int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
78685   const void *pKey1, int nKey1,   /* Left side of comparison */
78686   const void *pKey2, int nKey2    /* Right side of comparison */
78687 ){
78688   UnpackedRecord *r2 = pTask->pUnpacked;
78689   if( !*pbKey2Cached ){
78690     sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
78691     *pbKey2Cached = 1;
78692   }
78693   return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
78694 }
78695 
78696 /*
78697 ** A specially optimized version of vdbeSorterCompare() that assumes that
78698 ** the first field of each key is a TEXT value and that the collation
78699 ** sequence to compare them with is BINARY.
78700 */
78701 static int vdbeSorterCompareText(
78702   SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
78703   int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
78704   const void *pKey1, int nKey1,   /* Left side of comparison */
78705   const void *pKey2, int nKey2    /* Right side of comparison */
78706 ){
78707   const u8 * const p1 = (const u8 * const)pKey1;
78708   const u8 * const p2 = (const u8 * const)pKey2;
78709   const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
78710   const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
78711 
78712   int n1;
78713   int n2;
78714   int res;
78715 
78716   getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
78717   getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
78718   res = memcmp(v1, v2, MIN(n1, n2));
78719   if( res==0 ){
78720     res = n1 - n2;
78721   }
78722 
78723   if( res==0 ){
78724     if( pTask->pSorter->pKeyInfo->nField>1 ){
78725       res = vdbeSorterCompareTail(
78726           pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
78727       );
78728     }
78729   }else{
78730     if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
78731       res = res * -1;
78732     }
78733   }
78734 
78735   return res;
78736 }
78737 
78738 /*
78739 ** A specially optimized version of vdbeSorterCompare() that assumes that
78740 ** the first field of each key is an INTEGER value.
78741 */
78742 static int vdbeSorterCompareInt(
78743   SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
78744   int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
78745   const void *pKey1, int nKey1,   /* Left side of comparison */
78746   const void *pKey2, int nKey2    /* Right side of comparison */
78747 ){
78748   const u8 * const p1 = (const u8 * const)pKey1;
78749   const u8 * const p2 = (const u8 * const)pKey2;
78750   const int s1 = p1[1];                 /* Left hand serial type */
78751   const int s2 = p2[1];                 /* Right hand serial type */
78752   const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
78753   const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
78754   int res;                              /* Return value */
78755 
78756   assert( (s1>0 && s1<7) || s1==8 || s1==9 );
78757   assert( (s2>0 && s2<7) || s2==8 || s2==9 );
78758 
78759   if( s1>7 && s2>7 ){
78760     res = s1 - s2;
78761   }else{
78762     if( s1==s2 ){
78763       if( (*v1 ^ *v2) & 0x80 ){
78764         /* The two values have different signs */
78765         res = (*v1 & 0x80) ? -1 : +1;
78766       }else{
78767         /* The two values have the same sign. Compare using memcmp(). */
78768         static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 };
78769         int i;
78770         res = 0;
78771         for(i=0; i<aLen[s1]; i++){
78772           if( (res = v1[i] - v2[i]) ) break;
78773         }
78774       }
78775     }else{
78776       if( s2>7 ){
78777         res = +1;
78778       }else if( s1>7 ){
78779         res = -1;
78780       }else{
78781         res = s1 - s2;
78782       }
78783       assert( res!=0 );
78784 
78785       if( res>0 ){
78786         if( *v1 & 0x80 ) res = -1;
78787       }else{
78788         if( *v2 & 0x80 ) res = +1;
78789       }
78790     }
78791   }
78792 
78793   if( res==0 ){
78794     if( pTask->pSorter->pKeyInfo->nField>1 ){
78795       res = vdbeSorterCompareTail(
78796           pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
78797       );
78798     }
78799   }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
78800     res = res * -1;
78801   }
78802 
78803   return res;
78804 }
78805 
78806 /*
78807 ** Initialize the temporary index cursor just opened as a sorter cursor.
78808 **
78809 ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
78810 ** to determine the number of fields that should be compared from the
78811 ** records being sorted. However, if the value passed as argument nField
78812 ** is non-zero and the sorter is able to guarantee a stable sort, nField
78813 ** is used instead. This is used when sorting records for a CREATE INDEX
78814 ** statement. In this case, keys are always delivered to the sorter in
78815 ** order of the primary key, which happens to be make up the final part
78816 ** of the records being sorted. So if the sort is stable, there is never
78817 ** any reason to compare PK fields and they can be ignored for a small
78818 ** performance boost.
78819 **
78820 ** The sorter can guarantee a stable sort when running in single-threaded
78821 ** mode, but not in multi-threaded mode.
78822 **
78823 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
78824 */
78825 SQLITE_PRIVATE int sqlite3VdbeSorterInit(
78826   sqlite3 *db,                    /* Database connection (for malloc()) */
78827   int nField,                     /* Number of key fields in each record */
78828   VdbeCursor *pCsr                /* Cursor that holds the new sorter */
78829 ){
78830   int pgsz;                       /* Page size of main database */
78831   int i;                          /* Used to iterate through aTask[] */
78832   int mxCache;                    /* Cache size */
78833   VdbeSorter *pSorter;            /* The new sorter */
78834   KeyInfo *pKeyInfo;              /* Copy of pCsr->pKeyInfo with db==0 */
78835   int szKeyInfo;                  /* Size of pCsr->pKeyInfo in bytes */
78836   int sz;                         /* Size of pSorter in bytes */
78837   int rc = SQLITE_OK;
78838 #if SQLITE_MAX_WORKER_THREADS==0
78839 # define nWorker 0
78840 #else
78841   int nWorker;
78842 #endif
78843 
78844   /* Initialize the upper limit on the number of worker threads */
78845 #if SQLITE_MAX_WORKER_THREADS>0
78846   if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
78847     nWorker = 0;
78848   }else{
78849     nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
78850   }
78851 #endif
78852 
78853   /* Do not allow the total number of threads (main thread + all workers)
78854   ** to exceed the maximum merge count */
78855 #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
78856   if( nWorker>=SORTER_MAX_MERGE_COUNT ){
78857     nWorker = SORTER_MAX_MERGE_COUNT-1;
78858   }
78859 #endif
78860 
78861   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
78862   szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
78863   sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
78864 
78865   pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
78866   pCsr->pSorter = pSorter;
78867   if( pSorter==0 ){
78868     rc = SQLITE_NOMEM;
78869   }else{
78870     pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
78871     memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
78872     pKeyInfo->db = 0;
78873     if( nField && nWorker==0 ){
78874       pKeyInfo->nXField += (pKeyInfo->nField - nField);
78875       pKeyInfo->nField = nField;
78876     }
78877     pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
78878     pSorter->nTask = nWorker + 1;
78879     pSorter->iPrev = nWorker-1;
78880     pSorter->bUseThreads = (pSorter->nTask>1);
78881     pSorter->db = db;
78882     for(i=0; i<pSorter->nTask; i++){
78883       SortSubtask *pTask = &pSorter->aTask[i];
78884       pTask->pSorter = pSorter;
78885     }
78886 
78887     if( !sqlite3TempInMemory(db) ){
78888       u32 szPma = sqlite3GlobalConfig.szPma;
78889       pSorter->mnPmaSize = szPma * pgsz;
78890       mxCache = db->aDb[0].pSchema->cache_size;
78891       if( mxCache<(int)szPma ) mxCache = (int)szPma;
78892       pSorter->mxPmaSize = MIN((i64)mxCache*pgsz, SQLITE_MAX_PMASZ);
78893 
78894       /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
78895       ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
78896       ** large heap allocations.
78897       */
78898       if( sqlite3GlobalConfig.pScratch==0 ){
78899         assert( pSorter->iMemory==0 );
78900         pSorter->nMemory = pgsz;
78901         pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
78902         if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM;
78903       }
78904     }
78905 
78906     if( (pKeyInfo->nField+pKeyInfo->nXField)<13
78907      && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
78908     ){
78909       pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
78910     }
78911   }
78912 
78913   return rc;
78914 }
78915 #undef nWorker   /* Defined at the top of this function */
78916 
78917 /*
78918 ** Free the list of sorted records starting at pRecord.
78919 */
78920 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
78921   SorterRecord *p;
78922   SorterRecord *pNext;
78923   for(p=pRecord; p; p=pNext){
78924     pNext = p->u.pNext;
78925     sqlite3DbFree(db, p);
78926   }
78927 }
78928 
78929 /*
78930 ** Free all resources owned by the object indicated by argument pTask. All
78931 ** fields of *pTask are zeroed before returning.
78932 */
78933 static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
78934   sqlite3DbFree(db, pTask->pUnpacked);
78935 #if SQLITE_MAX_WORKER_THREADS>0
78936   /* pTask->list.aMemory can only be non-zero if it was handed memory
78937   ** from the main thread.  That only occurs SQLITE_MAX_WORKER_THREADS>0 */
78938   if( pTask->list.aMemory ){
78939     sqlite3_free(pTask->list.aMemory);
78940   }else
78941 #endif
78942   {
78943     assert( pTask->list.aMemory==0 );
78944     vdbeSorterRecordFree(0, pTask->list.pList);
78945   }
78946   if( pTask->file.pFd ){
78947     sqlite3OsCloseFree(pTask->file.pFd);
78948   }
78949   if( pTask->file2.pFd ){
78950     sqlite3OsCloseFree(pTask->file2.pFd);
78951   }
78952   memset(pTask, 0, sizeof(SortSubtask));
78953 }
78954 
78955 #ifdef SQLITE_DEBUG_SORTER_THREADS
78956 static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
78957   i64 t;
78958   int iTask = (pTask - pTask->pSorter->aTask);
78959   sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
78960   fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
78961 }
78962 static void vdbeSorterRewindDebug(const char *zEvent){
78963   i64 t;
78964   sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
78965   fprintf(stderr, "%lld:X %s\n", t, zEvent);
78966 }
78967 static void vdbeSorterPopulateDebug(
78968   SortSubtask *pTask,
78969   const char *zEvent
78970 ){
78971   i64 t;
78972   int iTask = (pTask - pTask->pSorter->aTask);
78973   sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
78974   fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
78975 }
78976 static void vdbeSorterBlockDebug(
78977   SortSubtask *pTask,
78978   int bBlocked,
78979   const char *zEvent
78980 ){
78981   if( bBlocked ){
78982     i64 t;
78983     sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
78984     fprintf(stderr, "%lld:main %s\n", t, zEvent);
78985   }
78986 }
78987 #else
78988 # define vdbeSorterWorkDebug(x,y)
78989 # define vdbeSorterRewindDebug(y)
78990 # define vdbeSorterPopulateDebug(x,y)
78991 # define vdbeSorterBlockDebug(x,y,z)
78992 #endif
78993 
78994 #if SQLITE_MAX_WORKER_THREADS>0
78995 /*
78996 ** Join thread pTask->thread.
78997 */
78998 static int vdbeSorterJoinThread(SortSubtask *pTask){
78999   int rc = SQLITE_OK;
79000   if( pTask->pThread ){
79001 #ifdef SQLITE_DEBUG_SORTER_THREADS
79002     int bDone = pTask->bDone;
79003 #endif
79004     void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
79005     vdbeSorterBlockDebug(pTask, !bDone, "enter");
79006     (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
79007     vdbeSorterBlockDebug(pTask, !bDone, "exit");
79008     rc = SQLITE_PTR_TO_INT(pRet);
79009     assert( pTask->bDone==1 );
79010     pTask->bDone = 0;
79011     pTask->pThread = 0;
79012   }
79013   return rc;
79014 }
79015 
79016 /*
79017 ** Launch a background thread to run xTask(pIn).
79018 */
79019 static int vdbeSorterCreateThread(
79020   SortSubtask *pTask,             /* Thread will use this task object */
79021   void *(*xTask)(void*),          /* Routine to run in a separate thread */
79022   void *pIn                       /* Argument passed into xTask() */
79023 ){
79024   assert( pTask->pThread==0 && pTask->bDone==0 );
79025   return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
79026 }
79027 
79028 /*
79029 ** Join all outstanding threads launched by SorterWrite() to create
79030 ** level-0 PMAs.
79031 */
79032 static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
79033   int rc = rcin;
79034   int i;
79035 
79036   /* This function is always called by the main user thread.
79037   **
79038   ** If this function is being called after SorterRewind() has been called,
79039   ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
79040   ** is currently attempt to join one of the other threads. To avoid a race
79041   ** condition where this thread also attempts to join the same object, join
79042   ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
79043   for(i=pSorter->nTask-1; i>=0; i--){
79044     SortSubtask *pTask = &pSorter->aTask[i];
79045     int rc2 = vdbeSorterJoinThread(pTask);
79046     if( rc==SQLITE_OK ) rc = rc2;
79047   }
79048   return rc;
79049 }
79050 #else
79051 # define vdbeSorterJoinAll(x,rcin) (rcin)
79052 # define vdbeSorterJoinThread(pTask) SQLITE_OK
79053 #endif
79054 
79055 /*
79056 ** Allocate a new MergeEngine object capable of handling up to
79057 ** nReader PmaReader inputs.
79058 **
79059 ** nReader is automatically rounded up to the next power of two.
79060 ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
79061 */
79062 static MergeEngine *vdbeMergeEngineNew(int nReader){
79063   int N = 2;                      /* Smallest power of two >= nReader */
79064   int nByte;                      /* Total bytes of space to allocate */
79065   MergeEngine *pNew;              /* Pointer to allocated object to return */
79066 
79067   assert( nReader<=SORTER_MAX_MERGE_COUNT );
79068 
79069   while( N<nReader ) N += N;
79070   nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
79071 
79072   pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
79073   if( pNew ){
79074     pNew->nTree = N;
79075     pNew->pTask = 0;
79076     pNew->aReadr = (PmaReader*)&pNew[1];
79077     pNew->aTree = (int*)&pNew->aReadr[N];
79078   }
79079   return pNew;
79080 }
79081 
79082 /*
79083 ** Free the MergeEngine object passed as the only argument.
79084 */
79085 static void vdbeMergeEngineFree(MergeEngine *pMerger){
79086   int i;
79087   if( pMerger ){
79088     for(i=0; i<pMerger->nTree; i++){
79089       vdbePmaReaderClear(&pMerger->aReadr[i]);
79090     }
79091   }
79092   sqlite3_free(pMerger);
79093 }
79094 
79095 /*
79096 ** Free all resources associated with the IncrMerger object indicated by
79097 ** the first argument.
79098 */
79099 static void vdbeIncrFree(IncrMerger *pIncr){
79100   if( pIncr ){
79101 #if SQLITE_MAX_WORKER_THREADS>0
79102     if( pIncr->bUseThread ){
79103       vdbeSorterJoinThread(pIncr->pTask);
79104       if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
79105       if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
79106     }
79107 #endif
79108     vdbeMergeEngineFree(pIncr->pMerger);
79109     sqlite3_free(pIncr);
79110   }
79111 }
79112 
79113 /*
79114 ** Reset a sorting cursor back to its original empty state.
79115 */
79116 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
79117   int i;
79118   (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
79119   assert( pSorter->bUseThreads || pSorter->pReader==0 );
79120 #if SQLITE_MAX_WORKER_THREADS>0
79121   if( pSorter->pReader ){
79122     vdbePmaReaderClear(pSorter->pReader);
79123     sqlite3DbFree(db, pSorter->pReader);
79124     pSorter->pReader = 0;
79125   }
79126 #endif
79127   vdbeMergeEngineFree(pSorter->pMerger);
79128   pSorter->pMerger = 0;
79129   for(i=0; i<pSorter->nTask; i++){
79130     SortSubtask *pTask = &pSorter->aTask[i];
79131     vdbeSortSubtaskCleanup(db, pTask);
79132     pTask->pSorter = pSorter;
79133   }
79134   if( pSorter->list.aMemory==0 ){
79135     vdbeSorterRecordFree(0, pSorter->list.pList);
79136   }
79137   pSorter->list.pList = 0;
79138   pSorter->list.szPMA = 0;
79139   pSorter->bUsePMA = 0;
79140   pSorter->iMemory = 0;
79141   pSorter->mxKeysize = 0;
79142   sqlite3DbFree(db, pSorter->pUnpacked);
79143   pSorter->pUnpacked = 0;
79144 }
79145 
79146 /*
79147 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
79148 */
79149 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
79150   VdbeSorter *pSorter = pCsr->pSorter;
79151   if( pSorter ){
79152     sqlite3VdbeSorterReset(db, pSorter);
79153     sqlite3_free(pSorter->list.aMemory);
79154     sqlite3DbFree(db, pSorter);
79155     pCsr->pSorter = 0;
79156   }
79157 }
79158 
79159 #if SQLITE_MAX_MMAP_SIZE>0
79160 /*
79161 ** The first argument is a file-handle open on a temporary file. The file
79162 ** is guaranteed to be nByte bytes or smaller in size. This function
79163 ** attempts to extend the file to nByte bytes in size and to ensure that
79164 ** the VFS has memory mapped it.
79165 **
79166 ** Whether or not the file does end up memory mapped of course depends on
79167 ** the specific VFS implementation.
79168 */
79169 static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
79170   if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
79171     void *p = 0;
79172     int chunksize = 4*1024;
79173     sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
79174     sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
79175     sqlite3OsFetch(pFd, 0, (int)nByte, &p);
79176     sqlite3OsUnfetch(pFd, 0, p);
79177   }
79178 }
79179 #else
79180 # define vdbeSorterExtendFile(x,y,z)
79181 #endif
79182 
79183 /*
79184 ** Allocate space for a file-handle and open a temporary file. If successful,
79185 ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
79186 ** Otherwise, set *ppFd to 0 and return an SQLite error code.
79187 */
79188 static int vdbeSorterOpenTempFile(
79189   sqlite3 *db,                    /* Database handle doing sort */
79190   i64 nExtend,                    /* Attempt to extend file to this size */
79191   sqlite3_file **ppFd
79192 ){
79193   int rc;
79194   if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
79195   rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
79196       SQLITE_OPEN_TEMP_JOURNAL |
79197       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
79198       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &rc
79199   );
79200   if( rc==SQLITE_OK ){
79201     i64 max = SQLITE_MAX_MMAP_SIZE;
79202     sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
79203     if( nExtend>0 ){
79204       vdbeSorterExtendFile(db, *ppFd, nExtend);
79205     }
79206   }
79207   return rc;
79208 }
79209 
79210 /*
79211 ** If it has not already been allocated, allocate the UnpackedRecord
79212 ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
79213 ** if no allocation was required), or SQLITE_NOMEM otherwise.
79214 */
79215 static int vdbeSortAllocUnpacked(SortSubtask *pTask){
79216   if( pTask->pUnpacked==0 ){
79217     char *pFree;
79218     pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
79219         pTask->pSorter->pKeyInfo, 0, 0, &pFree
79220     );
79221     assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
79222     if( pFree==0 ) return SQLITE_NOMEM;
79223     pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
79224     pTask->pUnpacked->errCode = 0;
79225   }
79226   return SQLITE_OK;
79227 }
79228 
79229 
79230 /*
79231 ** Merge the two sorted lists p1 and p2 into a single list.
79232 ** Set *ppOut to the head of the new list.
79233 */
79234 static void vdbeSorterMerge(
79235   SortSubtask *pTask,             /* Calling thread context */
79236   SorterRecord *p1,               /* First list to merge */
79237   SorterRecord *p2,               /* Second list to merge */
79238   SorterRecord **ppOut            /* OUT: Head of merged list */
79239 ){
79240   SorterRecord *pFinal = 0;
79241   SorterRecord **pp = &pFinal;
79242   int bCached = 0;
79243 
79244   while( p1 && p2 ){
79245     int res;
79246     res = pTask->xCompare(
79247         pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
79248     );
79249 
79250     if( res<=0 ){
79251       *pp = p1;
79252       pp = &p1->u.pNext;
79253       p1 = p1->u.pNext;
79254     }else{
79255       *pp = p2;
79256       pp = &p2->u.pNext;
79257       p2 = p2->u.pNext;
79258       bCached = 0;
79259     }
79260   }
79261   *pp = p1 ? p1 : p2;
79262   *ppOut = pFinal;
79263 }
79264 
79265 /*
79266 ** Return the SorterCompare function to compare values collected by the
79267 ** sorter object passed as the only argument.
79268 */
79269 static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
79270   if( p->typeMask==SORTER_TYPE_INTEGER ){
79271     return vdbeSorterCompareInt;
79272   }else if( p->typeMask==SORTER_TYPE_TEXT ){
79273     return vdbeSorterCompareText;
79274   }
79275   return vdbeSorterCompare;
79276 }
79277 
79278 /*
79279 ** Sort the linked list of records headed at pTask->pList. Return
79280 ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
79281 ** an error occurs.
79282 */
79283 static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
79284   int i;
79285   SorterRecord **aSlot;
79286   SorterRecord *p;
79287   int rc;
79288 
79289   rc = vdbeSortAllocUnpacked(pTask);
79290   if( rc!=SQLITE_OK ) return rc;
79291 
79292   p = pList->pList;
79293   pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
79294 
79295   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
79296   if( !aSlot ){
79297     return SQLITE_NOMEM;
79298   }
79299 
79300   while( p ){
79301     SorterRecord *pNext;
79302     if( pList->aMemory ){
79303       if( (u8*)p==pList->aMemory ){
79304         pNext = 0;
79305       }else{
79306         assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
79307         pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
79308       }
79309     }else{
79310       pNext = p->u.pNext;
79311     }
79312 
79313     p->u.pNext = 0;
79314     for(i=0; aSlot[i]; i++){
79315       vdbeSorterMerge(pTask, p, aSlot[i], &p);
79316       aSlot[i] = 0;
79317     }
79318     aSlot[i] = p;
79319     p = pNext;
79320   }
79321 
79322   p = 0;
79323   for(i=0; i<64; i++){
79324     vdbeSorterMerge(pTask, p, aSlot[i], &p);
79325   }
79326   pList->pList = p;
79327 
79328   sqlite3_free(aSlot);
79329   assert( pTask->pUnpacked->errCode==SQLITE_OK
79330        || pTask->pUnpacked->errCode==SQLITE_NOMEM
79331   );
79332   return pTask->pUnpacked->errCode;
79333 }
79334 
79335 /*
79336 ** Initialize a PMA-writer object.
79337 */
79338 static void vdbePmaWriterInit(
79339   sqlite3_file *pFd,              /* File handle to write to */
79340   PmaWriter *p,                   /* Object to populate */
79341   int nBuf,                       /* Buffer size */
79342   i64 iStart                      /* Offset of pFd to begin writing at */
79343 ){
79344   memset(p, 0, sizeof(PmaWriter));
79345   p->aBuffer = (u8*)sqlite3Malloc(nBuf);
79346   if( !p->aBuffer ){
79347     p->eFWErr = SQLITE_NOMEM;
79348   }else{
79349     p->iBufEnd = p->iBufStart = (iStart % nBuf);
79350     p->iWriteOff = iStart - p->iBufStart;
79351     p->nBuffer = nBuf;
79352     p->pFd = pFd;
79353   }
79354 }
79355 
79356 /*
79357 ** Write nData bytes of data to the PMA. Return SQLITE_OK
79358 ** if successful, or an SQLite error code if an error occurs.
79359 */
79360 static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
79361   int nRem = nData;
79362   while( nRem>0 && p->eFWErr==0 ){
79363     int nCopy = nRem;
79364     if( nCopy>(p->nBuffer - p->iBufEnd) ){
79365       nCopy = p->nBuffer - p->iBufEnd;
79366     }
79367 
79368     memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
79369     p->iBufEnd += nCopy;
79370     if( p->iBufEnd==p->nBuffer ){
79371       p->eFWErr = sqlite3OsWrite(p->pFd,
79372           &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
79373           p->iWriteOff + p->iBufStart
79374       );
79375       p->iBufStart = p->iBufEnd = 0;
79376       p->iWriteOff += p->nBuffer;
79377     }
79378     assert( p->iBufEnd<p->nBuffer );
79379 
79380     nRem -= nCopy;
79381   }
79382 }
79383 
79384 /*
79385 ** Flush any buffered data to disk and clean up the PMA-writer object.
79386 ** The results of using the PMA-writer after this call are undefined.
79387 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
79388 ** required. Otherwise, return an SQLite error code.
79389 **
79390 ** Before returning, set *piEof to the offset immediately following the
79391 ** last byte written to the file.
79392 */
79393 static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
79394   int rc;
79395   if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
79396     p->eFWErr = sqlite3OsWrite(p->pFd,
79397         &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
79398         p->iWriteOff + p->iBufStart
79399     );
79400   }
79401   *piEof = (p->iWriteOff + p->iBufEnd);
79402   sqlite3_free(p->aBuffer);
79403   rc = p->eFWErr;
79404   memset(p, 0, sizeof(PmaWriter));
79405   return rc;
79406 }
79407 
79408 /*
79409 ** Write value iVal encoded as a varint to the PMA. Return
79410 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
79411 */
79412 static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
79413   int nByte;
79414   u8 aByte[10];
79415   nByte = sqlite3PutVarint(aByte, iVal);
79416   vdbePmaWriteBlob(p, aByte, nByte);
79417 }
79418 
79419 /*
79420 ** Write the current contents of in-memory linked-list pList to a level-0
79421 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
79422 ** successful, or an SQLite error code otherwise.
79423 **
79424 ** The format of a PMA is:
79425 **
79426 **     * A varint. This varint contains the total number of bytes of content
79427 **       in the PMA (not including the varint itself).
79428 **
79429 **     * One or more records packed end-to-end in order of ascending keys.
79430 **       Each record consists of a varint followed by a blob of data (the
79431 **       key). The varint is the number of bytes in the blob of data.
79432 */
79433 static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
79434   sqlite3 *db = pTask->pSorter->db;
79435   int rc = SQLITE_OK;             /* Return code */
79436   PmaWriter writer;               /* Object used to write to the file */
79437 
79438 #ifdef SQLITE_DEBUG
79439   /* Set iSz to the expected size of file pTask->file after writing the PMA.
79440   ** This is used by an assert() statement at the end of this function.  */
79441   i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
79442 #endif
79443 
79444   vdbeSorterWorkDebug(pTask, "enter");
79445   memset(&writer, 0, sizeof(PmaWriter));
79446   assert( pList->szPMA>0 );
79447 
79448   /* If the first temporary PMA file has not been opened, open it now. */
79449   if( pTask->file.pFd==0 ){
79450     rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
79451     assert( rc!=SQLITE_OK || pTask->file.pFd );
79452     assert( pTask->file.iEof==0 );
79453     assert( pTask->nPMA==0 );
79454   }
79455 
79456   /* Try to get the file to memory map */
79457   if( rc==SQLITE_OK ){
79458     vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
79459   }
79460 
79461   /* Sort the list */
79462   if( rc==SQLITE_OK ){
79463     rc = vdbeSorterSort(pTask, pList);
79464   }
79465 
79466   if( rc==SQLITE_OK ){
79467     SorterRecord *p;
79468     SorterRecord *pNext = 0;
79469 
79470     vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
79471                       pTask->file.iEof);
79472     pTask->nPMA++;
79473     vdbePmaWriteVarint(&writer, pList->szPMA);
79474     for(p=pList->pList; p; p=pNext){
79475       pNext = p->u.pNext;
79476       vdbePmaWriteVarint(&writer, p->nVal);
79477       vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
79478       if( pList->aMemory==0 ) sqlite3_free(p);
79479     }
79480     pList->pList = p;
79481     rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
79482   }
79483 
79484   vdbeSorterWorkDebug(pTask, "exit");
79485   assert( rc!=SQLITE_OK || pList->pList==0 );
79486   assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
79487   return rc;
79488 }
79489 
79490 /*
79491 ** Advance the MergeEngine to its next entry.
79492 ** Set *pbEof to true there is no next entry because
79493 ** the MergeEngine has reached the end of all its inputs.
79494 **
79495 ** Return SQLITE_OK if successful or an error code if an error occurs.
79496 */
79497 static int vdbeMergeEngineStep(
79498   MergeEngine *pMerger,      /* The merge engine to advance to the next row */
79499   int *pbEof                 /* Set TRUE at EOF.  Set false for more content */
79500 ){
79501   int rc;
79502   int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
79503   SortSubtask *pTask = pMerger->pTask;
79504 
79505   /* Advance the current PmaReader */
79506   rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
79507 
79508   /* Update contents of aTree[] */
79509   if( rc==SQLITE_OK ){
79510     int i;                      /* Index of aTree[] to recalculate */
79511     PmaReader *pReadr1;         /* First PmaReader to compare */
79512     PmaReader *pReadr2;         /* Second PmaReader to compare */
79513     int bCached = 0;
79514 
79515     /* Find the first two PmaReaders to compare. The one that was just
79516     ** advanced (iPrev) and the one next to it in the array.  */
79517     pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
79518     pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
79519 
79520     for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
79521       /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
79522       int iRes;
79523       if( pReadr1->pFd==0 ){
79524         iRes = +1;
79525       }else if( pReadr2->pFd==0 ){
79526         iRes = -1;
79527       }else{
79528         iRes = pTask->xCompare(pTask, &bCached,
79529             pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
79530         );
79531       }
79532 
79533       /* If pReadr1 contained the smaller value, set aTree[i] to its index.
79534       ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
79535       ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
79536       ** pKey2 to point to the record belonging to pReadr2.
79537       **
79538       ** Alternatively, if pReadr2 contains the smaller of the two values,
79539       ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
79540       ** was actually called above, then pTask->pUnpacked now contains
79541       ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
79542       ** vdbeSorterCompare() from decoding pReadr2 again.
79543       **
79544       ** If the two values were equal, then the value from the oldest
79545       ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
79546       ** is sorted from oldest to newest, so pReadr1 contains older values
79547       ** than pReadr2 iff (pReadr1<pReadr2).  */
79548       if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
79549         pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
79550         pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
79551         bCached = 0;
79552       }else{
79553         if( pReadr1->pFd ) bCached = 0;
79554         pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
79555         pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
79556       }
79557     }
79558     *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
79559   }
79560 
79561   return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
79562 }
79563 
79564 #if SQLITE_MAX_WORKER_THREADS>0
79565 /*
79566 ** The main routine for background threads that write level-0 PMAs.
79567 */
79568 static void *vdbeSorterFlushThread(void *pCtx){
79569   SortSubtask *pTask = (SortSubtask*)pCtx;
79570   int rc;                         /* Return code */
79571   assert( pTask->bDone==0 );
79572   rc = vdbeSorterListToPMA(pTask, &pTask->list);
79573   pTask->bDone = 1;
79574   return SQLITE_INT_TO_PTR(rc);
79575 }
79576 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
79577 
79578 /*
79579 ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
79580 ** using a background thread.
79581 */
79582 static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
79583 #if SQLITE_MAX_WORKER_THREADS==0
79584   pSorter->bUsePMA = 1;
79585   return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
79586 #else
79587   int rc = SQLITE_OK;
79588   int i;
79589   SortSubtask *pTask = 0;    /* Thread context used to create new PMA */
79590   int nWorker = (pSorter->nTask-1);
79591 
79592   /* Set the flag to indicate that at least one PMA has been written.
79593   ** Or will be, anyhow.  */
79594   pSorter->bUsePMA = 1;
79595 
79596   /* Select a sub-task to sort and flush the current list of in-memory
79597   ** records to disk. If the sorter is running in multi-threaded mode,
79598   ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
79599   ** the background thread from a sub-tasks previous turn is still running,
79600   ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
79601   ** fall back to using the final sub-task. The first (pSorter->nTask-1)
79602   ** sub-tasks are prefered as they use background threads - the final
79603   ** sub-task uses the main thread. */
79604   for(i=0; i<nWorker; i++){
79605     int iTest = (pSorter->iPrev + i + 1) % nWorker;
79606     pTask = &pSorter->aTask[iTest];
79607     if( pTask->bDone ){
79608       rc = vdbeSorterJoinThread(pTask);
79609     }
79610     if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
79611   }
79612 
79613   if( rc==SQLITE_OK ){
79614     if( i==nWorker ){
79615       /* Use the foreground thread for this operation */
79616       rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
79617     }else{
79618       /* Launch a background thread for this operation */
79619       u8 *aMem = pTask->list.aMemory;
79620       void *pCtx = (void*)pTask;
79621 
79622       assert( pTask->pThread==0 && pTask->bDone==0 );
79623       assert( pTask->list.pList==0 );
79624       assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
79625 
79626       pSorter->iPrev = (u8)(pTask - pSorter->aTask);
79627       pTask->list = pSorter->list;
79628       pSorter->list.pList = 0;
79629       pSorter->list.szPMA = 0;
79630       if( aMem ){
79631         pSorter->list.aMemory = aMem;
79632         pSorter->nMemory = sqlite3MallocSize(aMem);
79633       }else if( pSorter->list.aMemory ){
79634         pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
79635         if( !pSorter->list.aMemory ) return SQLITE_NOMEM;
79636       }
79637 
79638       rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
79639     }
79640   }
79641 
79642   return rc;
79643 #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
79644 }
79645 
79646 /*
79647 ** Add a record to the sorter.
79648 */
79649 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
79650   const VdbeCursor *pCsr,         /* Sorter cursor */
79651   Mem *pVal                       /* Memory cell containing record */
79652 ){
79653   VdbeSorter *pSorter = pCsr->pSorter;
79654   int rc = SQLITE_OK;             /* Return Code */
79655   SorterRecord *pNew;             /* New list element */
79656 
79657   int bFlush;                     /* True to flush contents of memory to PMA */
79658   int nReq;                       /* Bytes of memory required */
79659   int nPMA;                       /* Bytes of PMA space required */
79660   int t;                          /* serial type of first record field */
79661 
79662   getVarint32((const u8*)&pVal->z[1], t);
79663   if( t>0 && t<10 && t!=7 ){
79664     pSorter->typeMask &= SORTER_TYPE_INTEGER;
79665   }else if( t>10 && (t & 0x01) ){
79666     pSorter->typeMask &= SORTER_TYPE_TEXT;
79667   }else{
79668     pSorter->typeMask = 0;
79669   }
79670 
79671   assert( pSorter );
79672 
79673   /* Figure out whether or not the current contents of memory should be
79674   ** flushed to a PMA before continuing. If so, do so.
79675   **
79676   ** If using the single large allocation mode (pSorter->aMemory!=0), then
79677   ** flush the contents of memory to a new PMA if (a) at least one value is
79678   ** already in memory and (b) the new value will not fit in memory.
79679   **
79680   ** Or, if using separate allocations for each record, flush the contents
79681   ** of memory to a PMA if either of the following are true:
79682   **
79683   **   * The total memory allocated for the in-memory list is greater
79684   **     than (page-size * cache-size), or
79685   **
79686   **   * The total memory allocated for the in-memory list is greater
79687   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
79688   */
79689   nReq = pVal->n + sizeof(SorterRecord);
79690   nPMA = pVal->n + sqlite3VarintLen(pVal->n);
79691   if( pSorter->mxPmaSize ){
79692     if( pSorter->list.aMemory ){
79693       bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
79694     }else{
79695       bFlush = (
79696           (pSorter->list.szPMA > pSorter->mxPmaSize)
79697        || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
79698       );
79699     }
79700     if( bFlush ){
79701       rc = vdbeSorterFlushPMA(pSorter);
79702       pSorter->list.szPMA = 0;
79703       pSorter->iMemory = 0;
79704       assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
79705     }
79706   }
79707 
79708   pSorter->list.szPMA += nPMA;
79709   if( nPMA>pSorter->mxKeysize ){
79710     pSorter->mxKeysize = nPMA;
79711   }
79712 
79713   if( pSorter->list.aMemory ){
79714     int nMin = pSorter->iMemory + nReq;
79715 
79716     if( nMin>pSorter->nMemory ){
79717       u8 *aNew;
79718       int nNew = pSorter->nMemory * 2;
79719       while( nNew < nMin ) nNew = nNew*2;
79720       if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
79721       if( nNew < nMin ) nNew = nMin;
79722 
79723       aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
79724       if( !aNew ) return SQLITE_NOMEM;
79725       pSorter->list.pList = (SorterRecord*)(
79726           aNew + ((u8*)pSorter->list.pList - pSorter->list.aMemory)
79727       );
79728       pSorter->list.aMemory = aNew;
79729       pSorter->nMemory = nNew;
79730     }
79731 
79732     pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
79733     pSorter->iMemory += ROUND8(nReq);
79734     pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
79735   }else{
79736     pNew = (SorterRecord *)sqlite3Malloc(nReq);
79737     if( pNew==0 ){
79738       return SQLITE_NOMEM;
79739     }
79740     pNew->u.pNext = pSorter->list.pList;
79741   }
79742 
79743   memcpy(SRVAL(pNew), pVal->z, pVal->n);
79744   pNew->nVal = pVal->n;
79745   pSorter->list.pList = pNew;
79746 
79747   return rc;
79748 }
79749 
79750 /*
79751 ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
79752 ** of the data stored in aFile[1] is the same as that used by regular PMAs,
79753 ** except that the number-of-bytes varint is omitted from the start.
79754 */
79755 static int vdbeIncrPopulate(IncrMerger *pIncr){
79756   int rc = SQLITE_OK;
79757   int rc2;
79758   i64 iStart = pIncr->iStartOff;
79759   SorterFile *pOut = &pIncr->aFile[1];
79760   SortSubtask *pTask = pIncr->pTask;
79761   MergeEngine *pMerger = pIncr->pMerger;
79762   PmaWriter writer;
79763   assert( pIncr->bEof==0 );
79764 
79765   vdbeSorterPopulateDebug(pTask, "enter");
79766 
79767   vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
79768   while( rc==SQLITE_OK ){
79769     int dummy;
79770     PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
79771     int nKey = pReader->nKey;
79772     i64 iEof = writer.iWriteOff + writer.iBufEnd;
79773 
79774     /* Check if the output file is full or if the input has been exhausted.
79775     ** In either case exit the loop. */
79776     if( pReader->pFd==0 ) break;
79777     if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
79778 
79779     /* Write the next key to the output. */
79780     vdbePmaWriteVarint(&writer, nKey);
79781     vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
79782     assert( pIncr->pMerger->pTask==pTask );
79783     rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
79784   }
79785 
79786   rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
79787   if( rc==SQLITE_OK ) rc = rc2;
79788   vdbeSorterPopulateDebug(pTask, "exit");
79789   return rc;
79790 }
79791 
79792 #if SQLITE_MAX_WORKER_THREADS>0
79793 /*
79794 ** The main routine for background threads that populate aFile[1] of
79795 ** multi-threaded IncrMerger objects.
79796 */
79797 static void *vdbeIncrPopulateThread(void *pCtx){
79798   IncrMerger *pIncr = (IncrMerger*)pCtx;
79799   void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
79800   pIncr->pTask->bDone = 1;
79801   return pRet;
79802 }
79803 
79804 /*
79805 ** Launch a background thread to populate aFile[1] of pIncr.
79806 */
79807 static int vdbeIncrBgPopulate(IncrMerger *pIncr){
79808   void *p = (void*)pIncr;
79809   assert( pIncr->bUseThread );
79810   return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
79811 }
79812 #endif
79813 
79814 /*
79815 ** This function is called when the PmaReader corresponding to pIncr has
79816 ** finished reading the contents of aFile[0]. Its purpose is to "refill"
79817 ** aFile[0] such that the PmaReader should start rereading it from the
79818 ** beginning.
79819 **
79820 ** For single-threaded objects, this is accomplished by literally reading
79821 ** keys from pIncr->pMerger and repopulating aFile[0].
79822 **
79823 ** For multi-threaded objects, all that is required is to wait until the
79824 ** background thread is finished (if it is not already) and then swap
79825 ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
79826 ** been exhausted, this function also launches a new background thread
79827 ** to populate the new aFile[1].
79828 **
79829 ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
79830 */
79831 static int vdbeIncrSwap(IncrMerger *pIncr){
79832   int rc = SQLITE_OK;
79833 
79834 #if SQLITE_MAX_WORKER_THREADS>0
79835   if( pIncr->bUseThread ){
79836     rc = vdbeSorterJoinThread(pIncr->pTask);
79837 
79838     if( rc==SQLITE_OK ){
79839       SorterFile f0 = pIncr->aFile[0];
79840       pIncr->aFile[0] = pIncr->aFile[1];
79841       pIncr->aFile[1] = f0;
79842     }
79843 
79844     if( rc==SQLITE_OK ){
79845       if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
79846         pIncr->bEof = 1;
79847       }else{
79848         rc = vdbeIncrBgPopulate(pIncr);
79849       }
79850     }
79851   }else
79852 #endif
79853   {
79854     rc = vdbeIncrPopulate(pIncr);
79855     pIncr->aFile[0] = pIncr->aFile[1];
79856     if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
79857       pIncr->bEof = 1;
79858     }
79859   }
79860 
79861   return rc;
79862 }
79863 
79864 /*
79865 ** Allocate and return a new IncrMerger object to read data from pMerger.
79866 **
79867 ** If an OOM condition is encountered, return NULL. In this case free the
79868 ** pMerger argument before returning.
79869 */
79870 static int vdbeIncrMergerNew(
79871   SortSubtask *pTask,     /* The thread that will be using the new IncrMerger */
79872   MergeEngine *pMerger,   /* The MergeEngine that the IncrMerger will control */
79873   IncrMerger **ppOut      /* Write the new IncrMerger here */
79874 ){
79875   int rc = SQLITE_OK;
79876   IncrMerger *pIncr = *ppOut = (IncrMerger*)
79877        (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
79878   if( pIncr ){
79879     pIncr->pMerger = pMerger;
79880     pIncr->pTask = pTask;
79881     pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
79882     pTask->file2.iEof += pIncr->mxSz;
79883   }else{
79884     vdbeMergeEngineFree(pMerger);
79885     rc = SQLITE_NOMEM;
79886   }
79887   return rc;
79888 }
79889 
79890 #if SQLITE_MAX_WORKER_THREADS>0
79891 /*
79892 ** Set the "use-threads" flag on object pIncr.
79893 */
79894 static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
79895   pIncr->bUseThread = 1;
79896   pIncr->pTask->file2.iEof -= pIncr->mxSz;
79897 }
79898 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
79899 
79900 
79901 
79902 /*
79903 ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
79904 ** two PmaReaders that feed that entry.  Neither of the PmaReaders
79905 ** are advanced.  This routine merely does the comparison.
79906 */
79907 static void vdbeMergeEngineCompare(
79908   MergeEngine *pMerger,  /* Merge engine containing PmaReaders to compare */
79909   int iOut               /* Store the result in pMerger->aTree[iOut] */
79910 ){
79911   int i1;
79912   int i2;
79913   int iRes;
79914   PmaReader *p1;
79915   PmaReader *p2;
79916 
79917   assert( iOut<pMerger->nTree && iOut>0 );
79918 
79919   if( iOut>=(pMerger->nTree/2) ){
79920     i1 = (iOut - pMerger->nTree/2) * 2;
79921     i2 = i1 + 1;
79922   }else{
79923     i1 = pMerger->aTree[iOut*2];
79924     i2 = pMerger->aTree[iOut*2+1];
79925   }
79926 
79927   p1 = &pMerger->aReadr[i1];
79928   p2 = &pMerger->aReadr[i2];
79929 
79930   if( p1->pFd==0 ){
79931     iRes = i2;
79932   }else if( p2->pFd==0 ){
79933     iRes = i1;
79934   }else{
79935     SortSubtask *pTask = pMerger->pTask;
79936     int bCached = 0;
79937     int res;
79938     assert( pTask->pUnpacked!=0 );  /* from vdbeSortSubtaskMain() */
79939     res = pTask->xCompare(
79940         pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
79941     );
79942     if( res<=0 ){
79943       iRes = i1;
79944     }else{
79945       iRes = i2;
79946     }
79947   }
79948 
79949   pMerger->aTree[iOut] = iRes;
79950 }
79951 
79952 /*
79953 ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
79954 ** and vdbePmaReaderIncrMergeInit().
79955 **
79956 ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
79957 ** SQLITE_MAX_WORKER_THREADS==0).  The other values are only used
79958 ** when there exists one or more separate worker threads.
79959 */
79960 #define INCRINIT_NORMAL 0
79961 #define INCRINIT_TASK   1
79962 #define INCRINIT_ROOT   2
79963 
79964 /*
79965 ** Forward reference required as the vdbeIncrMergeInit() and
79966 ** vdbePmaReaderIncrInit() routines are called mutually recursively when
79967 ** building a merge tree.
79968 */
79969 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
79970 
79971 /*
79972 ** Initialize the MergeEngine object passed as the second argument. Once this
79973 ** function returns, the first key of merged data may be read from the
79974 ** MergeEngine object in the usual fashion.
79975 **
79976 ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
79977 ** objects attached to the PmaReader objects that the merger reads from have
79978 ** already been populated, but that they have not yet populated aFile[0] and
79979 ** set the PmaReader objects up to read from it. In this case all that is
79980 ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
79981 ** its first key.
79982 **
79983 ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
79984 ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
79985 ** to pMerger.
79986 **
79987 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
79988 */
79989 static int vdbeMergeEngineInit(
79990   SortSubtask *pTask,             /* Thread that will run pMerger */
79991   MergeEngine *pMerger,           /* MergeEngine to initialize */
79992   int eMode                       /* One of the INCRINIT_XXX constants */
79993 ){
79994   int rc = SQLITE_OK;             /* Return code */
79995   int i;                          /* For looping over PmaReader objects */
79996   int nTree = pMerger->nTree;
79997 
79998   /* eMode is always INCRINIT_NORMAL in single-threaded mode */
79999   assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
80000 
80001   /* Verify that the MergeEngine is assigned to a single thread */
80002   assert( pMerger->pTask==0 );
80003   pMerger->pTask = pTask;
80004 
80005   for(i=0; i<nTree; i++){
80006     if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
80007       /* PmaReaders should be normally initialized in order, as if they are
80008       ** reading from the same temp file this makes for more linear file IO.
80009       ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
80010       ** in use it will block the vdbePmaReaderNext() call while it uses
80011       ** the main thread to fill its buffer. So calling PmaReaderNext()
80012       ** on this PmaReader before any of the multi-threaded PmaReaders takes
80013       ** better advantage of multi-processor hardware. */
80014       rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
80015     }else{
80016       rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
80017     }
80018     if( rc!=SQLITE_OK ) return rc;
80019   }
80020 
80021   for(i=pMerger->nTree-1; i>0; i--){
80022     vdbeMergeEngineCompare(pMerger, i);
80023   }
80024   return pTask->pUnpacked->errCode;
80025 }
80026 
80027 /*
80028 ** The PmaReader passed as the first argument is guaranteed to be an
80029 ** incremental-reader (pReadr->pIncr!=0). This function serves to open
80030 ** and/or initialize the temp file related fields of the IncrMerge
80031 ** object at (pReadr->pIncr).
80032 **
80033 ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
80034 ** in the sub-tree headed by pReadr are also initialized. Data is then
80035 ** loaded into the buffers belonging to pReadr and it is set to point to
80036 ** the first key in its range.
80037 **
80038 ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
80039 ** to be a multi-threaded PmaReader and this function is being called in a
80040 ** background thread. In this case all PmaReaders in the sub-tree are
80041 ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
80042 ** pReadr is populated. However, pReadr itself is not set up to point
80043 ** to its first key. A call to vdbePmaReaderNext() is still required to do
80044 ** that.
80045 **
80046 ** The reason this function does not call vdbePmaReaderNext() immediately
80047 ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
80048 ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
80049 ** this entire function is being run by thread (pTask->thread), that will
80050 ** lead to the current background thread attempting to join itself.
80051 **
80052 ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
80053 ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
80054 ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
80055 ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
80056 ** the current PmaReader set to point to the first key in its range.
80057 **
80058 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
80059 */
80060 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
80061   int rc = SQLITE_OK;
80062   IncrMerger *pIncr = pReadr->pIncr;
80063   SortSubtask *pTask = pIncr->pTask;
80064   sqlite3 *db = pTask->pSorter->db;
80065 
80066   /* eMode is always INCRINIT_NORMAL in single-threaded mode */
80067   assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
80068 
80069   rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
80070 
80071   /* Set up the required files for pIncr. A multi-theaded IncrMerge object
80072   ** requires two temp files to itself, whereas a single-threaded object
80073   ** only requires a region of pTask->file2. */
80074   if( rc==SQLITE_OK ){
80075     int mxSz = pIncr->mxSz;
80076 #if SQLITE_MAX_WORKER_THREADS>0
80077     if( pIncr->bUseThread ){
80078       rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
80079       if( rc==SQLITE_OK ){
80080         rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
80081       }
80082     }else
80083 #endif
80084     /*if( !pIncr->bUseThread )*/{
80085       if( pTask->file2.pFd==0 ){
80086         assert( pTask->file2.iEof>0 );
80087         rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
80088         pTask->file2.iEof = 0;
80089       }
80090       if( rc==SQLITE_OK ){
80091         pIncr->aFile[1].pFd = pTask->file2.pFd;
80092         pIncr->iStartOff = pTask->file2.iEof;
80093         pTask->file2.iEof += mxSz;
80094       }
80095     }
80096   }
80097 
80098 #if SQLITE_MAX_WORKER_THREADS>0
80099   if( rc==SQLITE_OK && pIncr->bUseThread ){
80100     /* Use the current thread to populate aFile[1], even though this
80101     ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
80102     ** then this function is already running in background thread
80103     ** pIncr->pTask->thread.
80104     **
80105     ** If this is the INCRINIT_ROOT object, then it is running in the
80106     ** main VDBE thread. But that is Ok, as that thread cannot return
80107     ** control to the VDBE or proceed with anything useful until the
80108     ** first results are ready from this merger object anyway.
80109     */
80110     assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
80111     rc = vdbeIncrPopulate(pIncr);
80112   }
80113 #endif
80114 
80115   if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
80116     rc = vdbePmaReaderNext(pReadr);
80117   }
80118 
80119   return rc;
80120 }
80121 
80122 #if SQLITE_MAX_WORKER_THREADS>0
80123 /*
80124 ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
80125 ** background threads.
80126 */
80127 static void *vdbePmaReaderBgIncrInit(void *pCtx){
80128   PmaReader *pReader = (PmaReader*)pCtx;
80129   void *pRet = SQLITE_INT_TO_PTR(
80130                   vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
80131                );
80132   pReader->pIncr->pTask->bDone = 1;
80133   return pRet;
80134 }
80135 #endif
80136 
80137 /*
80138 ** If the PmaReader passed as the first argument is not an incremental-reader
80139 ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
80140 ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
80141 ** this routine to initialize the incremental merge.
80142 **
80143 ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
80144 ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
80145 ** Or, if the IncrMerger is single threaded, the same function is called
80146 ** using the current thread.
80147 */
80148 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
80149   IncrMerger *pIncr = pReadr->pIncr;   /* Incremental merger */
80150   int rc = SQLITE_OK;                  /* Return code */
80151   if( pIncr ){
80152 #if SQLITE_MAX_WORKER_THREADS>0
80153     assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
80154     if( pIncr->bUseThread ){
80155       void *pCtx = (void*)pReadr;
80156       rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
80157     }else
80158 #endif
80159     {
80160       rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
80161     }
80162   }
80163   return rc;
80164 }
80165 
80166 /*
80167 ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
80168 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
80169 ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
80170 ** to NULL and return an SQLite error code.
80171 **
80172 ** When this function is called, *piOffset is set to the offset of the
80173 ** first PMA to read from pTask->file. Assuming no error occurs, it is
80174 ** set to the offset immediately following the last byte of the last
80175 ** PMA before returning. If an error does occur, then the final value of
80176 ** *piOffset is undefined.
80177 */
80178 static int vdbeMergeEngineLevel0(
80179   SortSubtask *pTask,             /* Sorter task to read from */
80180   int nPMA,                       /* Number of PMAs to read */
80181   i64 *piOffset,                  /* IN/OUT: Readr offset in pTask->file */
80182   MergeEngine **ppOut             /* OUT: New merge-engine */
80183 ){
80184   MergeEngine *pNew;              /* Merge engine to return */
80185   i64 iOff = *piOffset;
80186   int i;
80187   int rc = SQLITE_OK;
80188 
80189   *ppOut = pNew = vdbeMergeEngineNew(nPMA);
80190   if( pNew==0 ) rc = SQLITE_NOMEM;
80191 
80192   for(i=0; i<nPMA && rc==SQLITE_OK; i++){
80193     i64 nDummy;
80194     PmaReader *pReadr = &pNew->aReadr[i];
80195     rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
80196     iOff = pReadr->iEof;
80197   }
80198 
80199   if( rc!=SQLITE_OK ){
80200     vdbeMergeEngineFree(pNew);
80201     *ppOut = 0;
80202   }
80203   *piOffset = iOff;
80204   return rc;
80205 }
80206 
80207 /*
80208 ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
80209 ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
80210 **
80211 ** i.e.
80212 **
80213 **   nPMA<=16    -> TreeDepth() == 0
80214 **   nPMA<=256   -> TreeDepth() == 1
80215 **   nPMA<=65536 -> TreeDepth() == 2
80216 */
80217 static int vdbeSorterTreeDepth(int nPMA){
80218   int nDepth = 0;
80219   i64 nDiv = SORTER_MAX_MERGE_COUNT;
80220   while( nDiv < (i64)nPMA ){
80221     nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
80222     nDepth++;
80223   }
80224   return nDepth;
80225 }
80226 
80227 /*
80228 ** pRoot is the root of an incremental merge-tree with depth nDepth (according
80229 ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
80230 ** tree, counting from zero. This function adds pLeaf to the tree.
80231 **
80232 ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
80233 ** code is returned and pLeaf is freed.
80234 */
80235 static int vdbeSorterAddToTree(
80236   SortSubtask *pTask,             /* Task context */
80237   int nDepth,                     /* Depth of tree according to TreeDepth() */
80238   int iSeq,                       /* Sequence number of leaf within tree */
80239   MergeEngine *pRoot,             /* Root of tree */
80240   MergeEngine *pLeaf              /* Leaf to add to tree */
80241 ){
80242   int rc = SQLITE_OK;
80243   int nDiv = 1;
80244   int i;
80245   MergeEngine *p = pRoot;
80246   IncrMerger *pIncr;
80247 
80248   rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
80249 
80250   for(i=1; i<nDepth; i++){
80251     nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
80252   }
80253 
80254   for(i=1; i<nDepth && rc==SQLITE_OK; i++){
80255     int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
80256     PmaReader *pReadr = &p->aReadr[iIter];
80257 
80258     if( pReadr->pIncr==0 ){
80259       MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
80260       if( pNew==0 ){
80261         rc = SQLITE_NOMEM;
80262       }else{
80263         rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
80264       }
80265     }
80266     if( rc==SQLITE_OK ){
80267       p = pReadr->pIncr->pMerger;
80268       nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
80269     }
80270   }
80271 
80272   if( rc==SQLITE_OK ){
80273     p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
80274   }else{
80275     vdbeIncrFree(pIncr);
80276   }
80277   return rc;
80278 }
80279 
80280 /*
80281 ** This function is called as part of a SorterRewind() operation on a sorter
80282 ** that has already written two or more level-0 PMAs to one or more temp
80283 ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
80284 ** can be used to incrementally merge all PMAs on disk.
80285 **
80286 ** If successful, SQLITE_OK is returned and *ppOut set to point to the
80287 ** MergeEngine object at the root of the tree before returning. Or, if an
80288 ** error occurs, an SQLite error code is returned and the final value
80289 ** of *ppOut is undefined.
80290 */
80291 static int vdbeSorterMergeTreeBuild(
80292   VdbeSorter *pSorter,       /* The VDBE cursor that implements the sort */
80293   MergeEngine **ppOut        /* Write the MergeEngine here */
80294 ){
80295   MergeEngine *pMain = 0;
80296   int rc = SQLITE_OK;
80297   int iTask;
80298 
80299 #if SQLITE_MAX_WORKER_THREADS>0
80300   /* If the sorter uses more than one task, then create the top-level
80301   ** MergeEngine here. This MergeEngine will read data from exactly
80302   ** one PmaReader per sub-task.  */
80303   assert( pSorter->bUseThreads || pSorter->nTask==1 );
80304   if( pSorter->nTask>1 ){
80305     pMain = vdbeMergeEngineNew(pSorter->nTask);
80306     if( pMain==0 ) rc = SQLITE_NOMEM;
80307   }
80308 #endif
80309 
80310   for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
80311     SortSubtask *pTask = &pSorter->aTask[iTask];
80312     assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
80313     if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
80314       MergeEngine *pRoot = 0;     /* Root node of tree for this task */
80315       int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
80316       i64 iReadOff = 0;
80317 
80318       if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
80319         rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
80320       }else{
80321         int i;
80322         int iSeq = 0;
80323         pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
80324         if( pRoot==0 ) rc = SQLITE_NOMEM;
80325         for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
80326           MergeEngine *pMerger = 0; /* New level-0 PMA merger */
80327           int nReader;              /* Number of level-0 PMAs to merge */
80328 
80329           nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
80330           rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
80331           if( rc==SQLITE_OK ){
80332             rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
80333           }
80334         }
80335       }
80336 
80337       if( rc==SQLITE_OK ){
80338 #if SQLITE_MAX_WORKER_THREADS>0
80339         if( pMain!=0 ){
80340           rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
80341         }else
80342 #endif
80343         {
80344           assert( pMain==0 );
80345           pMain = pRoot;
80346         }
80347       }else{
80348         vdbeMergeEngineFree(pRoot);
80349       }
80350     }
80351   }
80352 
80353   if( rc!=SQLITE_OK ){
80354     vdbeMergeEngineFree(pMain);
80355     pMain = 0;
80356   }
80357   *ppOut = pMain;
80358   return rc;
80359 }
80360 
80361 /*
80362 ** This function is called as part of an sqlite3VdbeSorterRewind() operation
80363 ** on a sorter that has written two or more PMAs to temporary files. It sets
80364 ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
80365 ** (for multi-threaded sorters) so that it can be used to iterate through
80366 ** all records stored in the sorter.
80367 **
80368 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
80369 */
80370 static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
80371   int rc;                         /* Return code */
80372   SortSubtask *pTask0 = &pSorter->aTask[0];
80373   MergeEngine *pMain = 0;
80374 #if SQLITE_MAX_WORKER_THREADS
80375   sqlite3 *db = pTask0->pSorter->db;
80376   int i;
80377   SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
80378   for(i=0; i<pSorter->nTask; i++){
80379     pSorter->aTask[i].xCompare = xCompare;
80380   }
80381 #endif
80382 
80383   rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
80384   if( rc==SQLITE_OK ){
80385 #if SQLITE_MAX_WORKER_THREADS
80386     assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
80387     if( pSorter->bUseThreads ){
80388       int iTask;
80389       PmaReader *pReadr = 0;
80390       SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
80391       rc = vdbeSortAllocUnpacked(pLast);
80392       if( rc==SQLITE_OK ){
80393         pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
80394         pSorter->pReader = pReadr;
80395         if( pReadr==0 ) rc = SQLITE_NOMEM;
80396       }
80397       if( rc==SQLITE_OK ){
80398         rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
80399         if( rc==SQLITE_OK ){
80400           vdbeIncrMergerSetThreads(pReadr->pIncr);
80401           for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
80402             IncrMerger *pIncr;
80403             if( (pIncr = pMain->aReadr[iTask].pIncr) ){
80404               vdbeIncrMergerSetThreads(pIncr);
80405               assert( pIncr->pTask!=pLast );
80406             }
80407           }
80408           for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
80409             /* Check that:
80410             **
80411             **   a) The incremental merge object is configured to use the
80412             **      right task, and
80413             **   b) If it is using task (nTask-1), it is configured to run
80414             **      in single-threaded mode. This is important, as the
80415             **      root merge (INCRINIT_ROOT) will be using the same task
80416             **      object.
80417             */
80418             PmaReader *p = &pMain->aReadr[iTask];
80419             assert( p->pIncr==0 || (
80420                 (p->pIncr->pTask==&pSorter->aTask[iTask])             /* a */
80421              && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0)  /* b */
80422             ));
80423             rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
80424           }
80425         }
80426         pMain = 0;
80427       }
80428       if( rc==SQLITE_OK ){
80429         rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
80430       }
80431     }else
80432 #endif
80433     {
80434       rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
80435       pSorter->pMerger = pMain;
80436       pMain = 0;
80437     }
80438   }
80439 
80440   if( rc!=SQLITE_OK ){
80441     vdbeMergeEngineFree(pMain);
80442   }
80443   return rc;
80444 }
80445 
80446 
80447 /*
80448 ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
80449 ** this function is called to prepare for iterating through the records
80450 ** in sorted order.
80451 */
80452 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
80453   VdbeSorter *pSorter = pCsr->pSorter;
80454   int rc = SQLITE_OK;             /* Return code */
80455 
80456   assert( pSorter );
80457 
80458   /* If no data has been written to disk, then do not do so now. Instead,
80459   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
80460   ** from the in-memory list.  */
80461   if( pSorter->bUsePMA==0 ){
80462     if( pSorter->list.pList ){
80463       *pbEof = 0;
80464       rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
80465     }else{
80466       *pbEof = 1;
80467     }
80468     return rc;
80469   }
80470 
80471   /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
80472   ** function flushes the contents of memory to disk, it immediately always
80473   ** creates a new list consisting of a single key immediately afterwards.
80474   ** So the list is never empty at this point.  */
80475   assert( pSorter->list.pList );
80476   rc = vdbeSorterFlushPMA(pSorter);
80477 
80478   /* Join all threads */
80479   rc = vdbeSorterJoinAll(pSorter, rc);
80480 
80481   vdbeSorterRewindDebug("rewind");
80482 
80483   /* Assuming no errors have occurred, set up a merger structure to
80484   ** incrementally read and merge all remaining PMAs.  */
80485   assert( pSorter->pReader==0 );
80486   if( rc==SQLITE_OK ){
80487     rc = vdbeSorterSetupMerge(pSorter);
80488     *pbEof = 0;
80489   }
80490 
80491   vdbeSorterRewindDebug("rewinddone");
80492   return rc;
80493 }
80494 
80495 /*
80496 ** Advance to the next element in the sorter.
80497 */
80498 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
80499   VdbeSorter *pSorter = pCsr->pSorter;
80500   int rc;                         /* Return code */
80501 
80502   assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
80503   if( pSorter->bUsePMA ){
80504     assert( pSorter->pReader==0 || pSorter->pMerger==0 );
80505     assert( pSorter->bUseThreads==0 || pSorter->pReader );
80506     assert( pSorter->bUseThreads==1 || pSorter->pMerger );
80507 #if SQLITE_MAX_WORKER_THREADS>0
80508     if( pSorter->bUseThreads ){
80509       rc = vdbePmaReaderNext(pSorter->pReader);
80510       *pbEof = (pSorter->pReader->pFd==0);
80511     }else
80512 #endif
80513     /*if( !pSorter->bUseThreads )*/ {
80514       assert( pSorter->pMerger!=0 );
80515       assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
80516       rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
80517     }
80518   }else{
80519     SorterRecord *pFree = pSorter->list.pList;
80520     pSorter->list.pList = pFree->u.pNext;
80521     pFree->u.pNext = 0;
80522     if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
80523     *pbEof = !pSorter->list.pList;
80524     rc = SQLITE_OK;
80525   }
80526   return rc;
80527 }
80528 
80529 /*
80530 ** Return a pointer to a buffer owned by the sorter that contains the
80531 ** current key.
80532 */
80533 static void *vdbeSorterRowkey(
80534   const VdbeSorter *pSorter,      /* Sorter object */
80535   int *pnKey                      /* OUT: Size of current key in bytes */
80536 ){
80537   void *pKey;
80538   if( pSorter->bUsePMA ){
80539     PmaReader *pReader;
80540 #if SQLITE_MAX_WORKER_THREADS>0
80541     if( pSorter->bUseThreads ){
80542       pReader = pSorter->pReader;
80543     }else
80544 #endif
80545     /*if( !pSorter->bUseThreads )*/{
80546       pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
80547     }
80548     *pnKey = pReader->nKey;
80549     pKey = pReader->aKey;
80550   }else{
80551     *pnKey = pSorter->list.pList->nVal;
80552     pKey = SRVAL(pSorter->list.pList);
80553   }
80554   return pKey;
80555 }
80556 
80557 /*
80558 ** Copy the current sorter key into the memory cell pOut.
80559 */
80560 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
80561   VdbeSorter *pSorter = pCsr->pSorter;
80562   void *pKey; int nKey;           /* Sorter key to copy into pOut */
80563 
80564   pKey = vdbeSorterRowkey(pSorter, &nKey);
80565   if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
80566     return SQLITE_NOMEM;
80567   }
80568   pOut->n = nKey;
80569   MemSetTypeFlag(pOut, MEM_Blob);
80570   memcpy(pOut->z, pKey, nKey);
80571 
80572   return SQLITE_OK;
80573 }
80574 
80575 /*
80576 ** Compare the key in memory cell pVal with the key that the sorter cursor
80577 ** passed as the first argument currently points to. For the purposes of
80578 ** the comparison, ignore the rowid field at the end of each record.
80579 **
80580 ** If the sorter cursor key contains any NULL values, consider it to be
80581 ** less than pVal. Even if pVal also contains NULL values.
80582 **
80583 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
80584 ** Otherwise, set *pRes to a negative, zero or positive value if the
80585 ** key in pVal is smaller than, equal to or larger than the current sorter
80586 ** key.
80587 **
80588 ** This routine forms the core of the OP_SorterCompare opcode, which in
80589 ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
80590 */
80591 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
80592   const VdbeCursor *pCsr,         /* Sorter cursor */
80593   Mem *pVal,                      /* Value to compare to current sorter key */
80594   int nKeyCol,                    /* Compare this many columns */
80595   int *pRes                       /* OUT: Result of comparison */
80596 ){
80597   VdbeSorter *pSorter = pCsr->pSorter;
80598   UnpackedRecord *r2 = pSorter->pUnpacked;
80599   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
80600   int i;
80601   void *pKey; int nKey;           /* Sorter key to compare pVal with */
80602 
80603   if( r2==0 ){
80604     char *p;
80605     r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
80606     assert( pSorter->pUnpacked==(UnpackedRecord*)p );
80607     if( r2==0 ) return SQLITE_NOMEM;
80608     r2->nField = nKeyCol;
80609   }
80610   assert( r2->nField==nKeyCol );
80611 
80612   pKey = vdbeSorterRowkey(pSorter, &nKey);
80613   sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
80614   for(i=0; i<nKeyCol; i++){
80615     if( r2->aMem[i].flags & MEM_Null ){
80616       *pRes = -1;
80617       return SQLITE_OK;
80618     }
80619   }
80620 
80621   *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
80622   return SQLITE_OK;
80623 }
80624 
80625 /************** End of vdbesort.c ********************************************/
80626 /************** Begin file journal.c *****************************************/
80627 /*
80628 ** 2007 August 22
80629 **
80630 ** The author disclaims copyright to this source code.  In place of
80631 ** a legal notice, here is a blessing:
80632 **
80633 **    May you do good and not evil.
80634 **    May you find forgiveness for yourself and forgive others.
80635 **    May you share freely, never taking more than you give.
80636 **
80637 *************************************************************************
80638 **
80639 ** This file implements a special kind of sqlite3_file object used
80640 ** by SQLite to create journal files if the atomic-write optimization
80641 ** is enabled.
80642 **
80643 ** The distinctive characteristic of this sqlite3_file is that the
80644 ** actual on disk file is created lazily. When the file is created,
80645 ** the caller specifies a buffer size for an in-memory buffer to
80646 ** be used to service read() and write() requests. The actual file
80647 ** on disk is not created or populated until either:
80648 **
80649 **   1) The in-memory representation grows too large for the allocated
80650 **      buffer, or
80651 **   2) The sqlite3JournalCreate() function is called.
80652 */
80653 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
80654 
80655 
80656 /*
80657 ** A JournalFile object is a subclass of sqlite3_file used by
80658 ** as an open file handle for journal files.
80659 */
80660 struct JournalFile {
80661   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
80662   int nBuf;                       /* Size of zBuf[] in bytes */
80663   char *zBuf;                     /* Space to buffer journal writes */
80664   int iSize;                      /* Amount of zBuf[] currently used */
80665   int flags;                      /* xOpen flags */
80666   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
80667   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
80668   const char *zJournal;           /* Name of the journal file */
80669 };
80670 typedef struct JournalFile JournalFile;
80671 
80672 /*
80673 ** If it does not already exists, create and populate the on-disk file
80674 ** for JournalFile p.
80675 */
80676 static int createFile(JournalFile *p){
80677   int rc = SQLITE_OK;
80678   if( !p->pReal ){
80679     sqlite3_file *pReal = (sqlite3_file *)&p[1];
80680     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
80681     if( rc==SQLITE_OK ){
80682       p->pReal = pReal;
80683       if( p->iSize>0 ){
80684         assert(p->iSize<=p->nBuf);
80685         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
80686       }
80687       if( rc!=SQLITE_OK ){
80688         /* If an error occurred while writing to the file, close it before
80689         ** returning. This way, SQLite uses the in-memory journal data to
80690         ** roll back changes made to the internal page-cache before this
80691         ** function was called.  */
80692         sqlite3OsClose(pReal);
80693         p->pReal = 0;
80694       }
80695     }
80696   }
80697   return rc;
80698 }
80699 
80700 /*
80701 ** Close the file.
80702 */
80703 static int jrnlClose(sqlite3_file *pJfd){
80704   JournalFile *p = (JournalFile *)pJfd;
80705   if( p->pReal ){
80706     sqlite3OsClose(p->pReal);
80707   }
80708   sqlite3_free(p->zBuf);
80709   return SQLITE_OK;
80710 }
80711 
80712 /*
80713 ** Read data from the file.
80714 */
80715 static int jrnlRead(
80716   sqlite3_file *pJfd,    /* The journal file from which to read */
80717   void *zBuf,            /* Put the results here */
80718   int iAmt,              /* Number of bytes to read */
80719   sqlite_int64 iOfst     /* Begin reading at this offset */
80720 ){
80721   int rc = SQLITE_OK;
80722   JournalFile *p = (JournalFile *)pJfd;
80723   if( p->pReal ){
80724     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
80725   }else if( (iAmt+iOfst)>p->iSize ){
80726     rc = SQLITE_IOERR_SHORT_READ;
80727   }else{
80728     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
80729   }
80730   return rc;
80731 }
80732 
80733 /*
80734 ** Write data to the file.
80735 */
80736 static int jrnlWrite(
80737   sqlite3_file *pJfd,    /* The journal file into which to write */
80738   const void *zBuf,      /* Take data to be written from here */
80739   int iAmt,              /* Number of bytes to write */
80740   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
80741 ){
80742   int rc = SQLITE_OK;
80743   JournalFile *p = (JournalFile *)pJfd;
80744   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
80745     rc = createFile(p);
80746   }
80747   if( rc==SQLITE_OK ){
80748     if( p->pReal ){
80749       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
80750     }else{
80751       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
80752       if( p->iSize<(iOfst+iAmt) ){
80753         p->iSize = (iOfst+iAmt);
80754       }
80755     }
80756   }
80757   return rc;
80758 }
80759 
80760 /*
80761 ** Truncate the file.
80762 */
80763 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
80764   int rc = SQLITE_OK;
80765   JournalFile *p = (JournalFile *)pJfd;
80766   if( p->pReal ){
80767     rc = sqlite3OsTruncate(p->pReal, size);
80768   }else if( size<p->iSize ){
80769     p->iSize = size;
80770   }
80771   return rc;
80772 }
80773 
80774 /*
80775 ** Sync the file.
80776 */
80777 static int jrnlSync(sqlite3_file *pJfd, int flags){
80778   int rc;
80779   JournalFile *p = (JournalFile *)pJfd;
80780   if( p->pReal ){
80781     rc = sqlite3OsSync(p->pReal, flags);
80782   }else{
80783     rc = SQLITE_OK;
80784   }
80785   return rc;
80786 }
80787 
80788 /*
80789 ** Query the size of the file in bytes.
80790 */
80791 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
80792   int rc = SQLITE_OK;
80793   JournalFile *p = (JournalFile *)pJfd;
80794   if( p->pReal ){
80795     rc = sqlite3OsFileSize(p->pReal, pSize);
80796   }else{
80797     *pSize = (sqlite_int64) p->iSize;
80798   }
80799   return rc;
80800 }
80801 
80802 /*
80803 ** Table of methods for JournalFile sqlite3_file object.
80804 */
80805 static struct sqlite3_io_methods JournalFileMethods = {
80806   1,             /* iVersion */
80807   jrnlClose,     /* xClose */
80808   jrnlRead,      /* xRead */
80809   jrnlWrite,     /* xWrite */
80810   jrnlTruncate,  /* xTruncate */
80811   jrnlSync,      /* xSync */
80812   jrnlFileSize,  /* xFileSize */
80813   0,             /* xLock */
80814   0,             /* xUnlock */
80815   0,             /* xCheckReservedLock */
80816   0,             /* xFileControl */
80817   0,             /* xSectorSize */
80818   0,             /* xDeviceCharacteristics */
80819   0,             /* xShmMap */
80820   0,             /* xShmLock */
80821   0,             /* xShmBarrier */
80822   0              /* xShmUnmap */
80823 };
80824 
80825 /*
80826 ** Open a journal file.
80827 */
80828 SQLITE_PRIVATE int sqlite3JournalOpen(
80829   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
80830   const char *zName,         /* Name of the journal file */
80831   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
80832   int flags,                 /* Opening flags */
80833   int nBuf                   /* Bytes buffered before opening the file */
80834 ){
80835   JournalFile *p = (JournalFile *)pJfd;
80836   memset(p, 0, sqlite3JournalSize(pVfs));
80837   if( nBuf>0 ){
80838     p->zBuf = sqlite3MallocZero(nBuf);
80839     if( !p->zBuf ){
80840       return SQLITE_NOMEM;
80841     }
80842   }else{
80843     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
80844   }
80845   p->pMethod = &JournalFileMethods;
80846   p->nBuf = nBuf;
80847   p->flags = flags;
80848   p->zJournal = zName;
80849   p->pVfs = pVfs;
80850   return SQLITE_OK;
80851 }
80852 
80853 /*
80854 ** If the argument p points to a JournalFile structure, and the underlying
80855 ** file has not yet been created, create it now.
80856 */
80857 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
80858   if( p->pMethods!=&JournalFileMethods ){
80859     return SQLITE_OK;
80860   }
80861   return createFile((JournalFile *)p);
80862 }
80863 
80864 /*
80865 ** The file-handle passed as the only argument is guaranteed to be an open
80866 ** file. It may or may not be of class JournalFile. If the file is a
80867 ** JournalFile, and the underlying file on disk has not yet been opened,
80868 ** return 0. Otherwise, return 1.
80869 */
80870 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
80871   return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
80872 }
80873 
80874 /*
80875 ** Return the number of bytes required to store a JournalFile that uses vfs
80876 ** pVfs to create the underlying on-disk files.
80877 */
80878 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
80879   return (pVfs->szOsFile+sizeof(JournalFile));
80880 }
80881 #endif
80882 
80883 /************** End of journal.c *********************************************/
80884 /************** Begin file memjournal.c **************************************/
80885 /*
80886 ** 2008 October 7
80887 **
80888 ** The author disclaims copyright to this source code.  In place of
80889 ** a legal notice, here is a blessing:
80890 **
80891 **    May you do good and not evil.
80892 **    May you find forgiveness for yourself and forgive others.
80893 **    May you share freely, never taking more than you give.
80894 **
80895 *************************************************************************
80896 **
80897 ** This file contains code use to implement an in-memory rollback journal.
80898 ** The in-memory rollback journal is used to journal transactions for
80899 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
80900 */
80901 
80902 /* Forward references to internal structures */
80903 typedef struct MemJournal MemJournal;
80904 typedef struct FilePoint FilePoint;
80905 typedef struct FileChunk FileChunk;
80906 
80907 /* Space to hold the rollback journal is allocated in increments of
80908 ** this many bytes.
80909 **
80910 ** The size chosen is a little less than a power of two.  That way,
80911 ** the FileChunk object will have a size that almost exactly fills
80912 ** a power-of-two allocation.  This minimizes wasted space in power-of-two
80913 ** memory allocators.
80914 */
80915 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
80916 
80917 /*
80918 ** The rollback journal is composed of a linked list of these structures.
80919 */
80920 struct FileChunk {
80921   FileChunk *pNext;               /* Next chunk in the journal */
80922   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
80923 };
80924 
80925 /*
80926 ** An instance of this object serves as a cursor into the rollback journal.
80927 ** The cursor can be either for reading or writing.
80928 */
80929 struct FilePoint {
80930   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
80931   FileChunk *pChunk;              /* Specific chunk into which cursor points */
80932 };
80933 
80934 /*
80935 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
80936 ** is an instance of this class.
80937 */
80938 struct MemJournal {
80939   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
80940   FileChunk *pFirst;              /* Head of in-memory chunk-list */
80941   FilePoint endpoint;             /* Pointer to the end of the file */
80942   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
80943 };
80944 
80945 /*
80946 ** Read data from the in-memory journal file.  This is the implementation
80947 ** of the sqlite3_vfs.xRead method.
80948 */
80949 static int memjrnlRead(
80950   sqlite3_file *pJfd,    /* The journal file from which to read */
80951   void *zBuf,            /* Put the results here */
80952   int iAmt,              /* Number of bytes to read */
80953   sqlite_int64 iOfst     /* Begin reading at this offset */
80954 ){
80955   MemJournal *p = (MemJournal *)pJfd;
80956   u8 *zOut = zBuf;
80957   int nRead = iAmt;
80958   int iChunkOffset;
80959   FileChunk *pChunk;
80960 
80961   /* SQLite never tries to read past the end of a rollback journal file */
80962   assert( iOfst+iAmt<=p->endpoint.iOffset );
80963 
80964   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
80965     sqlite3_int64 iOff = 0;
80966     for(pChunk=p->pFirst;
80967         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
80968         pChunk=pChunk->pNext
80969     ){
80970       iOff += JOURNAL_CHUNKSIZE;
80971     }
80972   }else{
80973     pChunk = p->readpoint.pChunk;
80974   }
80975 
80976   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
80977   do {
80978     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
80979     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
80980     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
80981     zOut += nCopy;
80982     nRead -= iSpace;
80983     iChunkOffset = 0;
80984   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
80985   p->readpoint.iOffset = iOfst+iAmt;
80986   p->readpoint.pChunk = pChunk;
80987 
80988   return SQLITE_OK;
80989 }
80990 
80991 /*
80992 ** Write data to the file.
80993 */
80994 static int memjrnlWrite(
80995   sqlite3_file *pJfd,    /* The journal file into which to write */
80996   const void *zBuf,      /* Take data to be written from here */
80997   int iAmt,              /* Number of bytes to write */
80998   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
80999 ){
81000   MemJournal *p = (MemJournal *)pJfd;
81001   int nWrite = iAmt;
81002   u8 *zWrite = (u8 *)zBuf;
81003 
81004   /* An in-memory journal file should only ever be appended to. Random
81005   ** access writes are not required by sqlite.
81006   */
81007   assert( iOfst==p->endpoint.iOffset );
81008   UNUSED_PARAMETER(iOfst);
81009 
81010   while( nWrite>0 ){
81011     FileChunk *pChunk = p->endpoint.pChunk;
81012     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
81013     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
81014 
81015     if( iChunkOffset==0 ){
81016       /* New chunk is required to extend the file. */
81017       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
81018       if( !pNew ){
81019         return SQLITE_IOERR_NOMEM;
81020       }
81021       pNew->pNext = 0;
81022       if( pChunk ){
81023         assert( p->pFirst );
81024         pChunk->pNext = pNew;
81025       }else{
81026         assert( !p->pFirst );
81027         p->pFirst = pNew;
81028       }
81029       p->endpoint.pChunk = pNew;
81030     }
81031 
81032     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
81033     zWrite += iSpace;
81034     nWrite -= iSpace;
81035     p->endpoint.iOffset += iSpace;
81036   }
81037 
81038   return SQLITE_OK;
81039 }
81040 
81041 /*
81042 ** Truncate the file.
81043 */
81044 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
81045   MemJournal *p = (MemJournal *)pJfd;
81046   FileChunk *pChunk;
81047   assert(size==0);
81048   UNUSED_PARAMETER(size);
81049   pChunk = p->pFirst;
81050   while( pChunk ){
81051     FileChunk *pTmp = pChunk;
81052     pChunk = pChunk->pNext;
81053     sqlite3_free(pTmp);
81054   }
81055   sqlite3MemJournalOpen(pJfd);
81056   return SQLITE_OK;
81057 }
81058 
81059 /*
81060 ** Close the file.
81061 */
81062 static int memjrnlClose(sqlite3_file *pJfd){
81063   memjrnlTruncate(pJfd, 0);
81064   return SQLITE_OK;
81065 }
81066 
81067 
81068 /*
81069 ** Sync the file.
81070 **
81071 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
81072 ** is never called in a working implementation.  This implementation
81073 ** exists purely as a contingency, in case some malfunction in some other
81074 ** part of SQLite causes Sync to be called by mistake.
81075 */
81076 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
81077   UNUSED_PARAMETER2(NotUsed, NotUsed2);
81078   return SQLITE_OK;
81079 }
81080 
81081 /*
81082 ** Query the size of the file in bytes.
81083 */
81084 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
81085   MemJournal *p = (MemJournal *)pJfd;
81086   *pSize = (sqlite_int64) p->endpoint.iOffset;
81087   return SQLITE_OK;
81088 }
81089 
81090 /*
81091 ** Table of methods for MemJournal sqlite3_file object.
81092 */
81093 static const struct sqlite3_io_methods MemJournalMethods = {
81094   1,                /* iVersion */
81095   memjrnlClose,     /* xClose */
81096   memjrnlRead,      /* xRead */
81097   memjrnlWrite,     /* xWrite */
81098   memjrnlTruncate,  /* xTruncate */
81099   memjrnlSync,      /* xSync */
81100   memjrnlFileSize,  /* xFileSize */
81101   0,                /* xLock */
81102   0,                /* xUnlock */
81103   0,                /* xCheckReservedLock */
81104   0,                /* xFileControl */
81105   0,                /* xSectorSize */
81106   0,                /* xDeviceCharacteristics */
81107   0,                /* xShmMap */
81108   0,                /* xShmLock */
81109   0,                /* xShmBarrier */
81110   0,                /* xShmUnmap */
81111   0,                /* xFetch */
81112   0                 /* xUnfetch */
81113 };
81114 
81115 /*
81116 ** Open a journal file.
81117 */
81118 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
81119   MemJournal *p = (MemJournal *)pJfd;
81120   assert( EIGHT_BYTE_ALIGNMENT(p) );
81121   memset(p, 0, sqlite3MemJournalSize());
81122   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
81123 }
81124 
81125 /*
81126 ** Return true if the file-handle passed as an argument is
81127 ** an in-memory journal
81128 */
81129 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
81130   return pJfd->pMethods==&MemJournalMethods;
81131 }
81132 
81133 /*
81134 ** Return the number of bytes required to store a MemJournal file descriptor.
81135 */
81136 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
81137   return sizeof(MemJournal);
81138 }
81139 
81140 /************** End of memjournal.c ******************************************/
81141 /************** Begin file walker.c ******************************************/
81142 /*
81143 ** 2008 August 16
81144 **
81145 ** The author disclaims copyright to this source code.  In place of
81146 ** a legal notice, here is a blessing:
81147 **
81148 **    May you do good and not evil.
81149 **    May you find forgiveness for yourself and forgive others.
81150 **    May you share freely, never taking more than you give.
81151 **
81152 *************************************************************************
81153 ** This file contains routines used for walking the parser tree for
81154 ** an SQL statement.
81155 */
81156 /* #include <stdlib.h> */
81157 /* #include <string.h> */
81158 
81159 
81160 /*
81161 ** Walk an expression tree.  Invoke the callback once for each node
81162 ** of the expression, while descending.  (In other words, the callback
81163 ** is invoked before visiting children.)
81164 **
81165 ** The return value from the callback should be one of the WRC_*
81166 ** constants to specify how to proceed with the walk.
81167 **
81168 **    WRC_Continue      Continue descending down the tree.
81169 **
81170 **    WRC_Prune         Do not descend into child nodes.  But allow
81171 **                      the walk to continue with sibling nodes.
81172 **
81173 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
81174 **                      return the top-level walk call.
81175 **
81176 ** The return value from this routine is WRC_Abort to abandon the tree walk
81177 ** and WRC_Continue to continue.
81178 */
81179 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
81180   int rc;
81181   if( pExpr==0 ) return WRC_Continue;
81182   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
81183   testcase( ExprHasProperty(pExpr, EP_Reduced) );
81184   rc = pWalker->xExprCallback(pWalker, pExpr);
81185   if( rc==WRC_Continue
81186               && !ExprHasProperty(pExpr,EP_TokenOnly) ){
81187     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
81188     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
81189     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
81190       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
81191     }else{
81192       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
81193     }
81194   }
81195   return rc & WRC_Abort;
81196 }
81197 
81198 /*
81199 ** Call sqlite3WalkExpr() for every expression in list p or until
81200 ** an abort request is seen.
81201 */
81202 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
81203   int i;
81204   struct ExprList_item *pItem;
81205   if( p ){
81206     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
81207       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
81208     }
81209   }
81210   return WRC_Continue;
81211 }
81212 
81213 /*
81214 ** Walk all expressions associated with SELECT statement p.  Do
81215 ** not invoke the SELECT callback on p, but do (of course) invoke
81216 ** any expr callbacks and SELECT callbacks that come from subqueries.
81217 ** Return WRC_Abort or WRC_Continue.
81218 */
81219 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
81220   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
81221   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
81222   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
81223   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
81224   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
81225   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
81226   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
81227   return WRC_Continue;
81228 }
81229 
81230 /*
81231 ** Walk the parse trees associated with all subqueries in the
81232 ** FROM clause of SELECT statement p.  Do not invoke the select
81233 ** callback on p, but do invoke it on each FROM clause subquery
81234 ** and on any subqueries further down in the tree.  Return
81235 ** WRC_Abort or WRC_Continue;
81236 */
81237 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
81238   SrcList *pSrc;
81239   int i;
81240   struct SrcList_item *pItem;
81241 
81242   pSrc = p->pSrc;
81243   if( ALWAYS(pSrc) ){
81244     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
81245       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
81246         return WRC_Abort;
81247       }
81248     }
81249   }
81250   return WRC_Continue;
81251 }
81252 
81253 /*
81254 ** Call sqlite3WalkExpr() for every expression in Select statement p.
81255 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
81256 ** on the compound select chain, p->pPrior.
81257 **
81258 ** If it is not NULL, the xSelectCallback() callback is invoked before
81259 ** the walk of the expressions and FROM clause. The xSelectCallback2()
81260 ** method, if it is not NULL, is invoked following the walk of the
81261 ** expressions and FROM clause.
81262 **
81263 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
81264 ** there is an abort request.
81265 **
81266 ** If the Walker does not have an xSelectCallback() then this routine
81267 ** is a no-op returning WRC_Continue.
81268 */
81269 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
81270   int rc;
81271   if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
81272     return WRC_Continue;
81273   }
81274   rc = WRC_Continue;
81275   pWalker->walkerDepth++;
81276   while( p ){
81277     if( pWalker->xSelectCallback ){
81278        rc = pWalker->xSelectCallback(pWalker, p);
81279        if( rc ) break;
81280     }
81281     if( sqlite3WalkSelectExpr(pWalker, p)
81282      || sqlite3WalkSelectFrom(pWalker, p)
81283     ){
81284       pWalker->walkerDepth--;
81285       return WRC_Abort;
81286     }
81287     if( pWalker->xSelectCallback2 ){
81288       pWalker->xSelectCallback2(pWalker, p);
81289     }
81290     p = p->pPrior;
81291   }
81292   pWalker->walkerDepth--;
81293   return rc & WRC_Abort;
81294 }
81295 
81296 /************** End of walker.c **********************************************/
81297 /************** Begin file resolve.c *****************************************/
81298 /*
81299 ** 2008 August 18
81300 **
81301 ** The author disclaims copyright to this source code.  In place of
81302 ** a legal notice, here is a blessing:
81303 **
81304 **    May you do good and not evil.
81305 **    May you find forgiveness for yourself and forgive others.
81306 **    May you share freely, never taking more than you give.
81307 **
81308 *************************************************************************
81309 **
81310 ** This file contains routines used for walking the parser tree and
81311 ** resolve all identifiers by associating them with a particular
81312 ** table and column.
81313 */
81314 /* #include <stdlib.h> */
81315 /* #include <string.h> */
81316 
81317 /*
81318 ** Walk the expression tree pExpr and increase the aggregate function
81319 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
81320 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
81321 ** outer query into an inner subquery.
81322 **
81323 ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
81324 ** is a helper function - a callback for the tree walker.
81325 */
81326 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
81327   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
81328   return WRC_Continue;
81329 }
81330 static void incrAggFunctionDepth(Expr *pExpr, int N){
81331   if( N>0 ){
81332     Walker w;
81333     memset(&w, 0, sizeof(w));
81334     w.xExprCallback = incrAggDepth;
81335     w.u.n = N;
81336     sqlite3WalkExpr(&w, pExpr);
81337   }
81338 }
81339 
81340 /*
81341 ** Turn the pExpr expression into an alias for the iCol-th column of the
81342 ** result set in pEList.
81343 **
81344 ** If the result set column is a simple column reference, then this routine
81345 ** makes an exact copy.  But for any other kind of expression, this
81346 ** routine make a copy of the result set column as the argument to the
81347 ** TK_AS operator.  The TK_AS operator causes the expression to be
81348 ** evaluated just once and then reused for each alias.
81349 **
81350 ** The reason for suppressing the TK_AS term when the expression is a simple
81351 ** column reference is so that the column reference will be recognized as
81352 ** usable by indices within the WHERE clause processing logic.
81353 **
81354 ** The TK_AS operator is inhibited if zType[0]=='G'.  This means
81355 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
81356 **
81357 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
81358 **
81359 ** Is equivalent to:
81360 **
81361 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
81362 **
81363 ** The result of random()%5 in the GROUP BY clause is probably different
81364 ** from the result in the result-set.  On the other hand Standard SQL does
81365 ** not allow the GROUP BY clause to contain references to result-set columns.
81366 ** So this should never come up in well-formed queries.
81367 **
81368 ** If the reference is followed by a COLLATE operator, then make sure
81369 ** the COLLATE operator is preserved.  For example:
81370 **
81371 **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
81372 **
81373 ** Should be transformed into:
81374 **
81375 **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
81376 **
81377 ** The nSubquery parameter specifies how many levels of subquery the
81378 ** alias is removed from the original expression.  The usual value is
81379 ** zero but it might be more if the alias is contained within a subquery
81380 ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
81381 ** structures must be increased by the nSubquery amount.
81382 */
81383 static void resolveAlias(
81384   Parse *pParse,         /* Parsing context */
81385   ExprList *pEList,      /* A result set */
81386   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
81387   Expr *pExpr,           /* Transform this into an alias to the result set */
81388   const char *zType,     /* "GROUP" or "ORDER" or "" */
81389   int nSubquery          /* Number of subqueries that the label is moving */
81390 ){
81391   Expr *pOrig;           /* The iCol-th column of the result set */
81392   Expr *pDup;            /* Copy of pOrig */
81393   sqlite3 *db;           /* The database connection */
81394 
81395   assert( iCol>=0 && iCol<pEList->nExpr );
81396   pOrig = pEList->a[iCol].pExpr;
81397   assert( pOrig!=0 );
81398   db = pParse->db;
81399   pDup = sqlite3ExprDup(db, pOrig, 0);
81400   if( pDup==0 ) return;
81401   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
81402     incrAggFunctionDepth(pDup, nSubquery);
81403     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
81404     if( pDup==0 ) return;
81405     ExprSetProperty(pDup, EP_Skip);
81406     if( pEList->a[iCol].u.x.iAlias==0 ){
81407       pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
81408     }
81409     pDup->iTable = pEList->a[iCol].u.x.iAlias;
81410   }
81411   if( pExpr->op==TK_COLLATE ){
81412     pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
81413   }
81414 
81415   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
81416   ** prevents ExprDelete() from deleting the Expr structure itself,
81417   ** allowing it to be repopulated by the memcpy() on the following line.
81418   ** The pExpr->u.zToken might point into memory that will be freed by the
81419   ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
81420   ** make a copy of the token before doing the sqlite3DbFree().
81421   */
81422   ExprSetProperty(pExpr, EP_Static);
81423   sqlite3ExprDelete(db, pExpr);
81424   memcpy(pExpr, pDup, sizeof(*pExpr));
81425   if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
81426     assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
81427     pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
81428     pExpr->flags |= EP_MemToken;
81429   }
81430   sqlite3DbFree(db, pDup);
81431 }
81432 
81433 
81434 /*
81435 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
81436 **
81437 ** Return FALSE if the USING clause is NULL or if it does not contain
81438 ** zCol.
81439 */
81440 static int nameInUsingClause(IdList *pUsing, const char *zCol){
81441   if( pUsing ){
81442     int k;
81443     for(k=0; k<pUsing->nId; k++){
81444       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
81445     }
81446   }
81447   return 0;
81448 }
81449 
81450 /*
81451 ** Subqueries stores the original database, table and column names for their
81452 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
81453 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
81454 ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
81455 ** match anything.
81456 */
81457 SQLITE_PRIVATE int sqlite3MatchSpanName(
81458   const char *zSpan,
81459   const char *zCol,
81460   const char *zTab,
81461   const char *zDb
81462 ){
81463   int n;
81464   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
81465   if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
81466     return 0;
81467   }
81468   zSpan += n+1;
81469   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
81470   if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
81471     return 0;
81472   }
81473   zSpan += n+1;
81474   if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
81475     return 0;
81476   }
81477   return 1;
81478 }
81479 
81480 /*
81481 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
81482 ** that name in the set of source tables in pSrcList and make the pExpr
81483 ** expression node refer back to that source column.  The following changes
81484 ** are made to pExpr:
81485 **
81486 **    pExpr->iDb           Set the index in db->aDb[] of the database X
81487 **                         (even if X is implied).
81488 **    pExpr->iTable        Set to the cursor number for the table obtained
81489 **                         from pSrcList.
81490 **    pExpr->pTab          Points to the Table structure of X.Y (even if
81491 **                         X and/or Y are implied.)
81492 **    pExpr->iColumn       Set to the column number within the table.
81493 **    pExpr->op            Set to TK_COLUMN.
81494 **    pExpr->pLeft         Any expression this points to is deleted
81495 **    pExpr->pRight        Any expression this points to is deleted.
81496 **
81497 ** The zDb variable is the name of the database (the "X").  This value may be
81498 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
81499 ** can be used.  The zTable variable is the name of the table (the "Y").  This
81500 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
81501 ** means that the form of the name is Z and that columns from any table
81502 ** can be used.
81503 **
81504 ** If the name cannot be resolved unambiguously, leave an error message
81505 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
81506 */
81507 static int lookupName(
81508   Parse *pParse,       /* The parsing context */
81509   const char *zDb,     /* Name of the database containing table, or NULL */
81510   const char *zTab,    /* Name of table containing column, or NULL */
81511   const char *zCol,    /* Name of the column. */
81512   NameContext *pNC,    /* The name context used to resolve the name */
81513   Expr *pExpr          /* Make this EXPR node point to the selected column */
81514 ){
81515   int i, j;                         /* Loop counters */
81516   int cnt = 0;                      /* Number of matching column names */
81517   int cntTab = 0;                   /* Number of matching table names */
81518   int nSubquery = 0;                /* How many levels of subquery */
81519   sqlite3 *db = pParse->db;         /* The database connection */
81520   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
81521   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
81522   NameContext *pTopNC = pNC;        /* First namecontext in the list */
81523   Schema *pSchema = 0;              /* Schema of the expression */
81524   int isTrigger = 0;                /* True if resolved to a trigger column */
81525   Table *pTab = 0;                  /* Table hold the row */
81526   Column *pCol;                     /* A column of pTab */
81527 
81528   assert( pNC );     /* the name context cannot be NULL. */
81529   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
81530   assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
81531 
81532   /* Initialize the node to no-match */
81533   pExpr->iTable = -1;
81534   pExpr->pTab = 0;
81535   ExprSetVVAProperty(pExpr, EP_NoReduce);
81536 
81537   /* Translate the schema name in zDb into a pointer to the corresponding
81538   ** schema.  If not found, pSchema will remain NULL and nothing will match
81539   ** resulting in an appropriate error message toward the end of this routine
81540   */
81541   if( zDb ){
81542     testcase( pNC->ncFlags & NC_PartIdx );
81543     testcase( pNC->ncFlags & NC_IsCheck );
81544     if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
81545       /* Silently ignore database qualifiers inside CHECK constraints and
81546       ** partial indices.  Do not raise errors because that might break
81547       ** legacy and because it does not hurt anything to just ignore the
81548       ** database name. */
81549       zDb = 0;
81550     }else{
81551       for(i=0; i<db->nDb; i++){
81552         assert( db->aDb[i].zName );
81553         if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
81554           pSchema = db->aDb[i].pSchema;
81555           break;
81556         }
81557       }
81558     }
81559   }
81560 
81561   /* Start at the inner-most context and move outward until a match is found */
81562   while( pNC && cnt==0 ){
81563     ExprList *pEList;
81564     SrcList *pSrcList = pNC->pSrcList;
81565 
81566     if( pSrcList ){
81567       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
81568         pTab = pItem->pTab;
81569         assert( pTab!=0 && pTab->zName!=0 );
81570         assert( pTab->nCol>0 );
81571         if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
81572           int hit = 0;
81573           pEList = pItem->pSelect->pEList;
81574           for(j=0; j<pEList->nExpr; j++){
81575             if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
81576               cnt++;
81577               cntTab = 2;
81578               pMatch = pItem;
81579               pExpr->iColumn = j;
81580               hit = 1;
81581             }
81582           }
81583           if( hit || zTab==0 ) continue;
81584         }
81585         if( zDb && pTab->pSchema!=pSchema ){
81586           continue;
81587         }
81588         if( zTab ){
81589           const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
81590           assert( zTabName!=0 );
81591           if( sqlite3StrICmp(zTabName, zTab)!=0 ){
81592             continue;
81593           }
81594         }
81595         if( 0==(cntTab++) ){
81596           pMatch = pItem;
81597         }
81598         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
81599           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
81600             /* If there has been exactly one prior match and this match
81601             ** is for the right-hand table of a NATURAL JOIN or is in a
81602             ** USING clause, then skip this match.
81603             */
81604             if( cnt==1 ){
81605               if( pItem->jointype & JT_NATURAL ) continue;
81606               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
81607             }
81608             cnt++;
81609             pMatch = pItem;
81610             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
81611             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
81612             break;
81613           }
81614         }
81615       }
81616       if( pMatch ){
81617         pExpr->iTable = pMatch->iCursor;
81618         pExpr->pTab = pMatch->pTab;
81619         /* RIGHT JOIN not (yet) supported */
81620         assert( (pMatch->jointype & JT_RIGHT)==0 );
81621         if( (pMatch->jointype & JT_LEFT)!=0 ){
81622           ExprSetProperty(pExpr, EP_CanBeNull);
81623         }
81624         pSchema = pExpr->pTab->pSchema;
81625       }
81626     } /* if( pSrcList ) */
81627 
81628 #ifndef SQLITE_OMIT_TRIGGER
81629     /* If we have not already resolved the name, then maybe
81630     ** it is a new.* or old.* trigger argument reference
81631     */
81632     if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
81633       int op = pParse->eTriggerOp;
81634       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
81635       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
81636         pExpr->iTable = 1;
81637         pTab = pParse->pTriggerTab;
81638       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
81639         pExpr->iTable = 0;
81640         pTab = pParse->pTriggerTab;
81641       }else{
81642         pTab = 0;
81643       }
81644 
81645       if( pTab ){
81646         int iCol;
81647         pSchema = pTab->pSchema;
81648         cntTab++;
81649         for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
81650           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
81651             if( iCol==pTab->iPKey ){
81652               iCol = -1;
81653             }
81654             break;
81655           }
81656         }
81657         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
81658           /* IMP: R-51414-32910 */
81659           /* IMP: R-44911-55124 */
81660           iCol = -1;
81661         }
81662         if( iCol<pTab->nCol ){
81663           cnt++;
81664           if( iCol<0 ){
81665             pExpr->affinity = SQLITE_AFF_INTEGER;
81666           }else if( pExpr->iTable==0 ){
81667             testcase( iCol==31 );
81668             testcase( iCol==32 );
81669             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
81670           }else{
81671             testcase( iCol==31 );
81672             testcase( iCol==32 );
81673             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
81674           }
81675           pExpr->iColumn = (i16)iCol;
81676           pExpr->pTab = pTab;
81677           isTrigger = 1;
81678         }
81679       }
81680     }
81681 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
81682 
81683     /*
81684     ** Perhaps the name is a reference to the ROWID
81685     */
81686     if( cnt==0 && cntTab==1 && pMatch && sqlite3IsRowid(zCol)
81687      && HasRowid(pMatch->pTab) ){
81688       cnt = 1;
81689       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
81690       pExpr->affinity = SQLITE_AFF_INTEGER;
81691     }
81692 
81693     /*
81694     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
81695     ** might refer to an result-set alias.  This happens, for example, when
81696     ** we are resolving names in the WHERE clause of the following command:
81697     **
81698     **     SELECT a+b AS x FROM table WHERE x<10;
81699     **
81700     ** In cases like this, replace pExpr with a copy of the expression that
81701     ** forms the result set entry ("a+b" in the example) and return immediately.
81702     ** Note that the expression in the result set should have already been
81703     ** resolved by the time the WHERE clause is resolved.
81704     **
81705     ** The ability to use an output result-set column in the WHERE, GROUP BY,
81706     ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
81707     ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
81708     ** is supported for backwards compatibility only.  TO DO: Issue a warning
81709     ** on sqlite3_log() whenever the capability is used.
81710     */
81711     if( (pEList = pNC->pEList)!=0
81712      && zTab==0
81713      && cnt==0
81714     ){
81715       for(j=0; j<pEList->nExpr; j++){
81716         char *zAs = pEList->a[j].zName;
81717         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
81718           Expr *pOrig;
81719           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
81720           assert( pExpr->x.pList==0 );
81721           assert( pExpr->x.pSelect==0 );
81722           pOrig = pEList->a[j].pExpr;
81723           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
81724             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
81725             return WRC_Abort;
81726           }
81727           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
81728           cnt = 1;
81729           pMatch = 0;
81730           assert( zTab==0 && zDb==0 );
81731           goto lookupname_end;
81732         }
81733       }
81734     }
81735 
81736     /* Advance to the next name context.  The loop will exit when either
81737     ** we have a match (cnt>0) or when we run out of name contexts.
81738     */
81739     if( cnt==0 ){
81740       pNC = pNC->pNext;
81741       nSubquery++;
81742     }
81743   }
81744 
81745   /*
81746   ** If X and Y are NULL (in other words if only the column name Z is
81747   ** supplied) and the value of Z is enclosed in double-quotes, then
81748   ** Z is a string literal if it doesn't match any column names.  In that
81749   ** case, we need to return right away and not make any changes to
81750   ** pExpr.
81751   **
81752   ** Because no reference was made to outer contexts, the pNC->nRef
81753   ** fields are not changed in any context.
81754   */
81755   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
81756     pExpr->op = TK_STRING;
81757     pExpr->pTab = 0;
81758     return WRC_Prune;
81759   }
81760 
81761   /*
81762   ** cnt==0 means there was not match.  cnt>1 means there were two or
81763   ** more matches.  Either way, we have an error.
81764   */
81765   if( cnt!=1 ){
81766     const char *zErr;
81767     zErr = cnt==0 ? "no such column" : "ambiguous column name";
81768     if( zDb ){
81769       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
81770     }else if( zTab ){
81771       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
81772     }else{
81773       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
81774     }
81775     pParse->checkSchema = 1;
81776     pTopNC->nErr++;
81777   }
81778 
81779   /* If a column from a table in pSrcList is referenced, then record
81780   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
81781   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
81782   ** column number is greater than the number of bits in the bitmask
81783   ** then set the high-order bit of the bitmask.
81784   */
81785   if( pExpr->iColumn>=0 && pMatch!=0 ){
81786     int n = pExpr->iColumn;
81787     testcase( n==BMS-1 );
81788     if( n>=BMS ){
81789       n = BMS-1;
81790     }
81791     assert( pMatch->iCursor==pExpr->iTable );
81792     pMatch->colUsed |= ((Bitmask)1)<<n;
81793   }
81794 
81795   /* Clean up and return
81796   */
81797   sqlite3ExprDelete(db, pExpr->pLeft);
81798   pExpr->pLeft = 0;
81799   sqlite3ExprDelete(db, pExpr->pRight);
81800   pExpr->pRight = 0;
81801   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
81802 lookupname_end:
81803   if( cnt==1 ){
81804     assert( pNC!=0 );
81805     if( pExpr->op!=TK_AS ){
81806       sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
81807     }
81808     /* Increment the nRef value on all name contexts from TopNC up to
81809     ** the point where the name matched. */
81810     for(;;){
81811       assert( pTopNC!=0 );
81812       pTopNC->nRef++;
81813       if( pTopNC==pNC ) break;
81814       pTopNC = pTopNC->pNext;
81815     }
81816     return WRC_Prune;
81817   } else {
81818     return WRC_Abort;
81819   }
81820 }
81821 
81822 /*
81823 ** Allocate and return a pointer to an expression to load the column iCol
81824 ** from datasource iSrc in SrcList pSrc.
81825 */
81826 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
81827   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
81828   if( p ){
81829     struct SrcList_item *pItem = &pSrc->a[iSrc];
81830     p->pTab = pItem->pTab;
81831     p->iTable = pItem->iCursor;
81832     if( p->pTab->iPKey==iCol ){
81833       p->iColumn = -1;
81834     }else{
81835       p->iColumn = (ynVar)iCol;
81836       testcase( iCol==BMS );
81837       testcase( iCol==BMS-1 );
81838       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
81839     }
81840     ExprSetProperty(p, EP_Resolved);
81841   }
81842   return p;
81843 }
81844 
81845 /*
81846 ** Report an error that an expression is not valid for a partial index WHERE
81847 ** clause.
81848 */
81849 static void notValidPartIdxWhere(
81850   Parse *pParse,       /* Leave error message here */
81851   NameContext *pNC,    /* The name context */
81852   const char *zMsg     /* Type of error */
81853 ){
81854   if( (pNC->ncFlags & NC_PartIdx)!=0 ){
81855     sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
81856                     zMsg);
81857   }
81858 }
81859 
81860 #ifndef SQLITE_OMIT_CHECK
81861 /*
81862 ** Report an error that an expression is not valid for a CHECK constraint.
81863 */
81864 static void notValidCheckConstraint(
81865   Parse *pParse,       /* Leave error message here */
81866   NameContext *pNC,    /* The name context */
81867   const char *zMsg     /* Type of error */
81868 ){
81869   if( (pNC->ncFlags & NC_IsCheck)!=0 ){
81870     sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
81871   }
81872 }
81873 #else
81874 # define notValidCheckConstraint(P,N,M)
81875 #endif
81876 
81877 /*
81878 ** Expression p should encode a floating point value between 1.0 and 0.0.
81879 ** Return 1024 times this value.  Or return -1 if p is not a floating point
81880 ** value between 1.0 and 0.0.
81881 */
81882 static int exprProbability(Expr *p){
81883   double r = -1.0;
81884   if( p->op!=TK_FLOAT ) return -1;
81885   sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
81886   assert( r>=0.0 );
81887   if( r>1.0 ) return -1;
81888   return (int)(r*134217728.0);
81889 }
81890 
81891 /*
81892 ** This routine is callback for sqlite3WalkExpr().
81893 **
81894 ** Resolve symbolic names into TK_COLUMN operators for the current
81895 ** node in the expression tree.  Return 0 to continue the search down
81896 ** the tree or 2 to abort the tree walk.
81897 **
81898 ** This routine also does error checking and name resolution for
81899 ** function names.  The operator for aggregate functions is changed
81900 ** to TK_AGG_FUNCTION.
81901 */
81902 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
81903   NameContext *pNC;
81904   Parse *pParse;
81905 
81906   pNC = pWalker->u.pNC;
81907   assert( pNC!=0 );
81908   pParse = pNC->pParse;
81909   assert( pParse==pWalker->pParse );
81910 
81911   if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
81912   ExprSetProperty(pExpr, EP_Resolved);
81913 #ifndef NDEBUG
81914   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
81915     SrcList *pSrcList = pNC->pSrcList;
81916     int i;
81917     for(i=0; i<pNC->pSrcList->nSrc; i++){
81918       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
81919     }
81920   }
81921 #endif
81922   switch( pExpr->op ){
81923 
81924 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
81925     /* The special operator TK_ROW means use the rowid for the first
81926     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
81927     ** clause processing on UPDATE and DELETE statements.
81928     */
81929     case TK_ROW: {
81930       SrcList *pSrcList = pNC->pSrcList;
81931       struct SrcList_item *pItem;
81932       assert( pSrcList && pSrcList->nSrc==1 );
81933       pItem = pSrcList->a;
81934       pExpr->op = TK_COLUMN;
81935       pExpr->pTab = pItem->pTab;
81936       pExpr->iTable = pItem->iCursor;
81937       pExpr->iColumn = -1;
81938       pExpr->affinity = SQLITE_AFF_INTEGER;
81939       break;
81940     }
81941 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
81942           && !defined(SQLITE_OMIT_SUBQUERY) */
81943 
81944     /* A lone identifier is the name of a column.
81945     */
81946     case TK_ID: {
81947       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
81948     }
81949 
81950     /* A table name and column name:     ID.ID
81951     ** Or a database, table and column:  ID.ID.ID
81952     */
81953     case TK_DOT: {
81954       const char *zColumn;
81955       const char *zTable;
81956       const char *zDb;
81957       Expr *pRight;
81958 
81959       /* if( pSrcList==0 ) break; */
81960       pRight = pExpr->pRight;
81961       if( pRight->op==TK_ID ){
81962         zDb = 0;
81963         zTable = pExpr->pLeft->u.zToken;
81964         zColumn = pRight->u.zToken;
81965       }else{
81966         assert( pRight->op==TK_DOT );
81967         zDb = pExpr->pLeft->u.zToken;
81968         zTable = pRight->pLeft->u.zToken;
81969         zColumn = pRight->pRight->u.zToken;
81970       }
81971       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
81972     }
81973 
81974     /* Resolve function names
81975     */
81976     case TK_FUNCTION: {
81977       ExprList *pList = pExpr->x.pList;    /* The argument list */
81978       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
81979       int no_such_func = 0;       /* True if no such function exists */
81980       int wrong_num_args = 0;     /* True if wrong number of arguments */
81981       int is_agg = 0;             /* True if is an aggregate function */
81982       int auth;                   /* Authorization to use the function */
81983       int nId;                    /* Number of characters in function name */
81984       const char *zId;            /* The function name. */
81985       FuncDef *pDef;              /* Information about the function */
81986       u8 enc = ENC(pParse->db);   /* The database encoding */
81987 
81988       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
81989       notValidPartIdxWhere(pParse, pNC, "functions");
81990       zId = pExpr->u.zToken;
81991       nId = sqlite3Strlen30(zId);
81992       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
81993       if( pDef==0 ){
81994         pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
81995         if( pDef==0 ){
81996           no_such_func = 1;
81997         }else{
81998           wrong_num_args = 1;
81999         }
82000       }else{
82001         is_agg = pDef->xFunc==0;
82002         if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
82003           ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
82004           if( n==2 ){
82005             pExpr->iTable = exprProbability(pList->a[1].pExpr);
82006             if( pExpr->iTable<0 ){
82007               sqlite3ErrorMsg(pParse,
82008                 "second argument to likelihood() must be a "
82009                 "constant between 0.0 and 1.0");
82010               pNC->nErr++;
82011             }
82012           }else{
82013             /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
82014             ** equivalent to likelihood(X, 0.0625).
82015             ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
82016             ** short-hand for likelihood(X,0.0625).
82017             ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
82018             ** for likelihood(X,0.9375).
82019             ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
82020             ** to likelihood(X,0.9375). */
82021             /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
82022             pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
82023           }
82024         }
82025 #ifndef SQLITE_OMIT_AUTHORIZATION
82026         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
82027         if( auth!=SQLITE_OK ){
82028           if( auth==SQLITE_DENY ){
82029             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
82030                                     pDef->zName);
82031             pNC->nErr++;
82032           }
82033           pExpr->op = TK_NULL;
82034           return WRC_Prune;
82035         }
82036 #endif
82037         if( pDef->funcFlags & SQLITE_FUNC_CONSTANT ){
82038           ExprSetProperty(pExpr,EP_ConstFunc);
82039         }
82040       }
82041       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
82042         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
82043         pNC->nErr++;
82044         is_agg = 0;
82045       }else if( no_such_func && pParse->db->init.busy==0 ){
82046         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
82047         pNC->nErr++;
82048       }else if( wrong_num_args ){
82049         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
82050              nId, zId);
82051         pNC->nErr++;
82052       }
82053       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
82054       sqlite3WalkExprList(pWalker, pList);
82055       if( is_agg ){
82056         NameContext *pNC2 = pNC;
82057         pExpr->op = TK_AGG_FUNCTION;
82058         pExpr->op2 = 0;
82059         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
82060           pExpr->op2++;
82061           pNC2 = pNC2->pNext;
82062         }
82063         assert( pDef!=0 );
82064         if( pNC2 ){
82065           assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
82066           testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
82067           pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
82068 
82069         }
82070         pNC->ncFlags |= NC_AllowAgg;
82071       }
82072       /* FIX ME:  Compute pExpr->affinity based on the expected return
82073       ** type of the function
82074       */
82075       return WRC_Prune;
82076     }
82077 #ifndef SQLITE_OMIT_SUBQUERY
82078     case TK_SELECT:
82079     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
82080 #endif
82081     case TK_IN: {
82082       testcase( pExpr->op==TK_IN );
82083       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
82084         int nRef = pNC->nRef;
82085         notValidCheckConstraint(pParse, pNC, "subqueries");
82086         notValidPartIdxWhere(pParse, pNC, "subqueries");
82087         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
82088         assert( pNC->nRef>=nRef );
82089         if( nRef!=pNC->nRef ){
82090           ExprSetProperty(pExpr, EP_VarSelect);
82091         }
82092       }
82093       break;
82094     }
82095     case TK_VARIABLE: {
82096       notValidCheckConstraint(pParse, pNC, "parameters");
82097       notValidPartIdxWhere(pParse, pNC, "parameters");
82098       break;
82099     }
82100   }
82101   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
82102 }
82103 
82104 /*
82105 ** pEList is a list of expressions which are really the result set of the
82106 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
82107 ** This routine checks to see if pE is a simple identifier which corresponds
82108 ** to the AS-name of one of the terms of the expression list.  If it is,
82109 ** this routine return an integer between 1 and N where N is the number of
82110 ** elements in pEList, corresponding to the matching entry.  If there is
82111 ** no match, or if pE is not a simple identifier, then this routine
82112 ** return 0.
82113 **
82114 ** pEList has been resolved.  pE has not.
82115 */
82116 static int resolveAsName(
82117   Parse *pParse,     /* Parsing context for error messages */
82118   ExprList *pEList,  /* List of expressions to scan */
82119   Expr *pE           /* Expression we are trying to match */
82120 ){
82121   int i;             /* Loop counter */
82122 
82123   UNUSED_PARAMETER(pParse);
82124 
82125   if( pE->op==TK_ID ){
82126     char *zCol = pE->u.zToken;
82127     for(i=0; i<pEList->nExpr; i++){
82128       char *zAs = pEList->a[i].zName;
82129       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
82130         return i+1;
82131       }
82132     }
82133   }
82134   return 0;
82135 }
82136 
82137 /*
82138 ** pE is a pointer to an expression which is a single term in the
82139 ** ORDER BY of a compound SELECT.  The expression has not been
82140 ** name resolved.
82141 **
82142 ** At the point this routine is called, we already know that the
82143 ** ORDER BY term is not an integer index into the result set.  That
82144 ** case is handled by the calling routine.
82145 **
82146 ** Attempt to match pE against result set columns in the left-most
82147 ** SELECT statement.  Return the index i of the matching column,
82148 ** as an indication to the caller that it should sort by the i-th column.
82149 ** The left-most column is 1.  In other words, the value returned is the
82150 ** same integer value that would be used in the SQL statement to indicate
82151 ** the column.
82152 **
82153 ** If there is no match, return 0.  Return -1 if an error occurs.
82154 */
82155 static int resolveOrderByTermToExprList(
82156   Parse *pParse,     /* Parsing context for error messages */
82157   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
82158   Expr *pE           /* The specific ORDER BY term */
82159 ){
82160   int i;             /* Loop counter */
82161   ExprList *pEList;  /* The columns of the result set */
82162   NameContext nc;    /* Name context for resolving pE */
82163   sqlite3 *db;       /* Database connection */
82164   int rc;            /* Return code from subprocedures */
82165   u8 savedSuppErr;   /* Saved value of db->suppressErr */
82166 
82167   assert( sqlite3ExprIsInteger(pE, &i)==0 );
82168   pEList = pSelect->pEList;
82169 
82170   /* Resolve all names in the ORDER BY term expression
82171   */
82172   memset(&nc, 0, sizeof(nc));
82173   nc.pParse = pParse;
82174   nc.pSrcList = pSelect->pSrc;
82175   nc.pEList = pEList;
82176   nc.ncFlags = NC_AllowAgg;
82177   nc.nErr = 0;
82178   db = pParse->db;
82179   savedSuppErr = db->suppressErr;
82180   db->suppressErr = 1;
82181   rc = sqlite3ResolveExprNames(&nc, pE);
82182   db->suppressErr = savedSuppErr;
82183   if( rc ) return 0;
82184 
82185   /* Try to match the ORDER BY expression against an expression
82186   ** in the result set.  Return an 1-based index of the matching
82187   ** result-set entry.
82188   */
82189   for(i=0; i<pEList->nExpr; i++){
82190     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
82191       return i+1;
82192     }
82193   }
82194 
82195   /* If no match, return 0. */
82196   return 0;
82197 }
82198 
82199 /*
82200 ** Generate an ORDER BY or GROUP BY term out-of-range error.
82201 */
82202 static void resolveOutOfRangeError(
82203   Parse *pParse,         /* The error context into which to write the error */
82204   const char *zType,     /* "ORDER" or "GROUP" */
82205   int i,                 /* The index (1-based) of the term out of range */
82206   int mx                 /* Largest permissible value of i */
82207 ){
82208   sqlite3ErrorMsg(pParse,
82209     "%r %s BY term out of range - should be "
82210     "between 1 and %d", i, zType, mx);
82211 }
82212 
82213 /*
82214 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
82215 ** each term of the ORDER BY clause is a constant integer between 1
82216 ** and N where N is the number of columns in the compound SELECT.
82217 **
82218 ** ORDER BY terms that are already an integer between 1 and N are
82219 ** unmodified.  ORDER BY terms that are integers outside the range of
82220 ** 1 through N generate an error.  ORDER BY terms that are expressions
82221 ** are matched against result set expressions of compound SELECT
82222 ** beginning with the left-most SELECT and working toward the right.
82223 ** At the first match, the ORDER BY expression is transformed into
82224 ** the integer column number.
82225 **
82226 ** Return the number of errors seen.
82227 */
82228 static int resolveCompoundOrderBy(
82229   Parse *pParse,        /* Parsing context.  Leave error messages here */
82230   Select *pSelect       /* The SELECT statement containing the ORDER BY */
82231 ){
82232   int i;
82233   ExprList *pOrderBy;
82234   ExprList *pEList;
82235   sqlite3 *db;
82236   int moreToDo = 1;
82237 
82238   pOrderBy = pSelect->pOrderBy;
82239   if( pOrderBy==0 ) return 0;
82240   db = pParse->db;
82241 #if SQLITE_MAX_COLUMN
82242   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
82243     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
82244     return 1;
82245   }
82246 #endif
82247   for(i=0; i<pOrderBy->nExpr; i++){
82248     pOrderBy->a[i].done = 0;
82249   }
82250   pSelect->pNext = 0;
82251   while( pSelect->pPrior ){
82252     pSelect->pPrior->pNext = pSelect;
82253     pSelect = pSelect->pPrior;
82254   }
82255   while( pSelect && moreToDo ){
82256     struct ExprList_item *pItem;
82257     moreToDo = 0;
82258     pEList = pSelect->pEList;
82259     assert( pEList!=0 );
82260     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
82261       int iCol = -1;
82262       Expr *pE, *pDup;
82263       if( pItem->done ) continue;
82264       pE = sqlite3ExprSkipCollate(pItem->pExpr);
82265       if( sqlite3ExprIsInteger(pE, &iCol) ){
82266         if( iCol<=0 || iCol>pEList->nExpr ){
82267           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
82268           return 1;
82269         }
82270       }else{
82271         iCol = resolveAsName(pParse, pEList, pE);
82272         if( iCol==0 ){
82273           pDup = sqlite3ExprDup(db, pE, 0);
82274           if( !db->mallocFailed ){
82275             assert(pDup);
82276             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
82277           }
82278           sqlite3ExprDelete(db, pDup);
82279         }
82280       }
82281       if( iCol>0 ){
82282         /* Convert the ORDER BY term into an integer column number iCol,
82283         ** taking care to preserve the COLLATE clause if it exists */
82284         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
82285         if( pNew==0 ) return 1;
82286         pNew->flags |= EP_IntValue;
82287         pNew->u.iValue = iCol;
82288         if( pItem->pExpr==pE ){
82289           pItem->pExpr = pNew;
82290         }else{
82291           Expr *pParent = pItem->pExpr;
82292           assert( pParent->op==TK_COLLATE );
82293           while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
82294           assert( pParent->pLeft==pE );
82295           pParent->pLeft = pNew;
82296         }
82297         sqlite3ExprDelete(db, pE);
82298         pItem->u.x.iOrderByCol = (u16)iCol;
82299         pItem->done = 1;
82300       }else{
82301         moreToDo = 1;
82302       }
82303     }
82304     pSelect = pSelect->pNext;
82305   }
82306   for(i=0; i<pOrderBy->nExpr; i++){
82307     if( pOrderBy->a[i].done==0 ){
82308       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
82309             "column in the result set", i+1);
82310       return 1;
82311     }
82312   }
82313   return 0;
82314 }
82315 
82316 /*
82317 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
82318 ** the SELECT statement pSelect.  If any term is reference to a
82319 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
82320 ** field) then convert that term into a copy of the corresponding result set
82321 ** column.
82322 **
82323 ** If any errors are detected, add an error message to pParse and
82324 ** return non-zero.  Return zero if no errors are seen.
82325 */
82326 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
82327   Parse *pParse,        /* Parsing context.  Leave error messages here */
82328   Select *pSelect,      /* The SELECT statement containing the clause */
82329   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
82330   const char *zType     /* "ORDER" or "GROUP" */
82331 ){
82332   int i;
82333   sqlite3 *db = pParse->db;
82334   ExprList *pEList;
82335   struct ExprList_item *pItem;
82336 
82337   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
82338 #if SQLITE_MAX_COLUMN
82339   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
82340     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
82341     return 1;
82342   }
82343 #endif
82344   pEList = pSelect->pEList;
82345   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
82346   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
82347     if( pItem->u.x.iOrderByCol ){
82348       if( pItem->u.x.iOrderByCol>pEList->nExpr ){
82349         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
82350         return 1;
82351       }
82352       resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
82353                    zType,0);
82354     }
82355   }
82356   return 0;
82357 }
82358 
82359 /*
82360 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
82361 ** The Name context of the SELECT statement is pNC.  zType is either
82362 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
82363 **
82364 ** This routine resolves each term of the clause into an expression.
82365 ** If the order-by term is an integer I between 1 and N (where N is the
82366 ** number of columns in the result set of the SELECT) then the expression
82367 ** in the resolution is a copy of the I-th result-set expression.  If
82368 ** the order-by term is an identifier that corresponds to the AS-name of
82369 ** a result-set expression, then the term resolves to a copy of the
82370 ** result-set expression.  Otherwise, the expression is resolved in
82371 ** the usual way - using sqlite3ResolveExprNames().
82372 **
82373 ** This routine returns the number of errors.  If errors occur, then
82374 ** an appropriate error message might be left in pParse.  (OOM errors
82375 ** excepted.)
82376 */
82377 static int resolveOrderGroupBy(
82378   NameContext *pNC,     /* The name context of the SELECT statement */
82379   Select *pSelect,      /* The SELECT statement holding pOrderBy */
82380   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
82381   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
82382 ){
82383   int i, j;                      /* Loop counters */
82384   int iCol;                      /* Column number */
82385   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
82386   Parse *pParse;                 /* Parsing context */
82387   int nResult;                   /* Number of terms in the result set */
82388 
82389   if( pOrderBy==0 ) return 0;
82390   nResult = pSelect->pEList->nExpr;
82391   pParse = pNC->pParse;
82392   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
82393     Expr *pE = pItem->pExpr;
82394     Expr *pE2 = sqlite3ExprSkipCollate(pE);
82395     if( zType[0]!='G' ){
82396       iCol = resolveAsName(pParse, pSelect->pEList, pE2);
82397       if( iCol>0 ){
82398         /* If an AS-name match is found, mark this ORDER BY column as being
82399         ** a copy of the iCol-th result-set column.  The subsequent call to
82400         ** sqlite3ResolveOrderGroupBy() will convert the expression to a
82401         ** copy of the iCol-th result-set expression. */
82402         pItem->u.x.iOrderByCol = (u16)iCol;
82403         continue;
82404       }
82405     }
82406     if( sqlite3ExprIsInteger(pE2, &iCol) ){
82407       /* The ORDER BY term is an integer constant.  Again, set the column
82408       ** number so that sqlite3ResolveOrderGroupBy() will convert the
82409       ** order-by term to a copy of the result-set expression */
82410       if( iCol<1 || iCol>0xffff ){
82411         resolveOutOfRangeError(pParse, zType, i+1, nResult);
82412         return 1;
82413       }
82414       pItem->u.x.iOrderByCol = (u16)iCol;
82415       continue;
82416     }
82417 
82418     /* Otherwise, treat the ORDER BY term as an ordinary expression */
82419     pItem->u.x.iOrderByCol = 0;
82420     if( sqlite3ResolveExprNames(pNC, pE) ){
82421       return 1;
82422     }
82423     for(j=0; j<pSelect->pEList->nExpr; j++){
82424       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
82425         pItem->u.x.iOrderByCol = j+1;
82426       }
82427     }
82428   }
82429   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
82430 }
82431 
82432 /*
82433 ** Resolve names in the SELECT statement p and all of its descendants.
82434 */
82435 static int resolveSelectStep(Walker *pWalker, Select *p){
82436   NameContext *pOuterNC;  /* Context that contains this SELECT */
82437   NameContext sNC;        /* Name context of this SELECT */
82438   int isCompound;         /* True if p is a compound select */
82439   int nCompound;          /* Number of compound terms processed so far */
82440   Parse *pParse;          /* Parsing context */
82441   ExprList *pEList;       /* Result set expression list */
82442   int i;                  /* Loop counter */
82443   ExprList *pGroupBy;     /* The GROUP BY clause */
82444   Select *pLeftmost;      /* Left-most of SELECT of a compound */
82445   sqlite3 *db;            /* Database connection */
82446 
82447 
82448   assert( p!=0 );
82449   if( p->selFlags & SF_Resolved ){
82450     return WRC_Prune;
82451   }
82452   pOuterNC = pWalker->u.pNC;
82453   pParse = pWalker->pParse;
82454   db = pParse->db;
82455 
82456   /* Normally sqlite3SelectExpand() will be called first and will have
82457   ** already expanded this SELECT.  However, if this is a subquery within
82458   ** an expression, sqlite3ResolveExprNames() will be called without a
82459   ** prior call to sqlite3SelectExpand().  When that happens, let
82460   ** sqlite3SelectPrep() do all of the processing for this SELECT.
82461   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
82462   ** this routine in the correct order.
82463   */
82464   if( (p->selFlags & SF_Expanded)==0 ){
82465     sqlite3SelectPrep(pParse, p, pOuterNC);
82466     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
82467   }
82468 
82469   isCompound = p->pPrior!=0;
82470   nCompound = 0;
82471   pLeftmost = p;
82472   while( p ){
82473     assert( (p->selFlags & SF_Expanded)!=0 );
82474     assert( (p->selFlags & SF_Resolved)==0 );
82475     p->selFlags |= SF_Resolved;
82476 
82477     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
82478     ** are not allowed to refer to any names, so pass an empty NameContext.
82479     */
82480     memset(&sNC, 0, sizeof(sNC));
82481     sNC.pParse = pParse;
82482     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
82483         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
82484       return WRC_Abort;
82485     }
82486 
82487     /* If the SF_Converted flags is set, then this Select object was
82488     ** was created by the convertCompoundSelectToSubquery() function.
82489     ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
82490     ** as if it were part of the sub-query, not the parent. This block
82491     ** moves the pOrderBy down to the sub-query. It will be moved back
82492     ** after the names have been resolved.  */
82493     if( p->selFlags & SF_Converted ){
82494       Select *pSub = p->pSrc->a[0].pSelect;
82495       assert( p->pSrc->nSrc==1 && p->pOrderBy );
82496       assert( pSub->pPrior && pSub->pOrderBy==0 );
82497       pSub->pOrderBy = p->pOrderBy;
82498       p->pOrderBy = 0;
82499     }
82500 
82501     /* Recursively resolve names in all subqueries
82502     */
82503     for(i=0; i<p->pSrc->nSrc; i++){
82504       struct SrcList_item *pItem = &p->pSrc->a[i];
82505       if( pItem->pSelect ){
82506         NameContext *pNC;         /* Used to iterate name contexts */
82507         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
82508         const char *zSavedContext = pParse->zAuthContext;
82509 
82510         /* Count the total number of references to pOuterNC and all of its
82511         ** parent contexts. After resolving references to expressions in
82512         ** pItem->pSelect, check if this value has changed. If so, then
82513         ** SELECT statement pItem->pSelect must be correlated. Set the
82514         ** pItem->isCorrelated flag if this is the case. */
82515         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
82516 
82517         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
82518         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
82519         pParse->zAuthContext = zSavedContext;
82520         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
82521 
82522         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
82523         assert( pItem->isCorrelated==0 && nRef<=0 );
82524         pItem->isCorrelated = (nRef!=0);
82525       }
82526     }
82527 
82528     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
82529     ** resolve the result-set expression list.
82530     */
82531     sNC.ncFlags = NC_AllowAgg;
82532     sNC.pSrcList = p->pSrc;
82533     sNC.pNext = pOuterNC;
82534 
82535     /* Resolve names in the result set. */
82536     pEList = p->pEList;
82537     assert( pEList!=0 );
82538     for(i=0; i<pEList->nExpr; i++){
82539       Expr *pX = pEList->a[i].pExpr;
82540       if( sqlite3ResolveExprNames(&sNC, pX) ){
82541         return WRC_Abort;
82542       }
82543     }
82544 
82545     /* If there are no aggregate functions in the result-set, and no GROUP BY
82546     ** expression, do not allow aggregates in any of the other expressions.
82547     */
82548     assert( (p->selFlags & SF_Aggregate)==0 );
82549     pGroupBy = p->pGroupBy;
82550     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
82551       assert( NC_MinMaxAgg==SF_MinMaxAgg );
82552       p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
82553     }else{
82554       sNC.ncFlags &= ~NC_AllowAgg;
82555     }
82556 
82557     /* If a HAVING clause is present, then there must be a GROUP BY clause.
82558     */
82559     if( p->pHaving && !pGroupBy ){
82560       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
82561       return WRC_Abort;
82562     }
82563 
82564     /* Add the output column list to the name-context before parsing the
82565     ** other expressions in the SELECT statement. This is so that
82566     ** expressions in the WHERE clause (etc.) can refer to expressions by
82567     ** aliases in the result set.
82568     **
82569     ** Minor point: If this is the case, then the expression will be
82570     ** re-evaluated for each reference to it.
82571     */
82572     sNC.pEList = p->pEList;
82573     if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
82574     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
82575 
82576     /* The ORDER BY and GROUP BY clauses may not refer to terms in
82577     ** outer queries
82578     */
82579     sNC.pNext = 0;
82580     sNC.ncFlags |= NC_AllowAgg;
82581 
82582     /* If this is a converted compound query, move the ORDER BY clause from
82583     ** the sub-query back to the parent query. At this point each term
82584     ** within the ORDER BY clause has been transformed to an integer value.
82585     ** These integers will be replaced by copies of the corresponding result
82586     ** set expressions by the call to resolveOrderGroupBy() below.  */
82587     if( p->selFlags & SF_Converted ){
82588       Select *pSub = p->pSrc->a[0].pSelect;
82589       p->pOrderBy = pSub->pOrderBy;
82590       pSub->pOrderBy = 0;
82591     }
82592 
82593     /* Process the ORDER BY clause for singleton SELECT statements.
82594     ** The ORDER BY clause for compounds SELECT statements is handled
82595     ** below, after all of the result-sets for all of the elements of
82596     ** the compound have been resolved.
82597     **
82598     ** If there is an ORDER BY clause on a term of a compound-select other
82599     ** than the right-most term, then that is a syntax error.  But the error
82600     ** is not detected until much later, and so we need to go ahead and
82601     ** resolve those symbols on the incorrect ORDER BY for consistency.
82602     */
82603     if( isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
82604      && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
82605     ){
82606       return WRC_Abort;
82607     }
82608     if( db->mallocFailed ){
82609       return WRC_Abort;
82610     }
82611 
82612     /* Resolve the GROUP BY clause.  At the same time, make sure
82613     ** the GROUP BY clause does not contain aggregate functions.
82614     */
82615     if( pGroupBy ){
82616       struct ExprList_item *pItem;
82617 
82618       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
82619         return WRC_Abort;
82620       }
82621       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
82622         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
82623           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
82624               "the GROUP BY clause");
82625           return WRC_Abort;
82626         }
82627       }
82628     }
82629 
82630     /* Advance to the next term of the compound
82631     */
82632     p = p->pPrior;
82633     nCompound++;
82634   }
82635 
82636   /* Resolve the ORDER BY on a compound SELECT after all terms of
82637   ** the compound have been resolved.
82638   */
82639   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
82640     return WRC_Abort;
82641   }
82642 
82643   return WRC_Prune;
82644 }
82645 
82646 /*
82647 ** This routine walks an expression tree and resolves references to
82648 ** table columns and result-set columns.  At the same time, do error
82649 ** checking on function usage and set a flag if any aggregate functions
82650 ** are seen.
82651 **
82652 ** To resolve table columns references we look for nodes (or subtrees) of the
82653 ** form X.Y.Z or Y.Z or just Z where
82654 **
82655 **      X:   The name of a database.  Ex:  "main" or "temp" or
82656 **           the symbolic name assigned to an ATTACH-ed database.
82657 **
82658 **      Y:   The name of a table in a FROM clause.  Or in a trigger
82659 **           one of the special names "old" or "new".
82660 **
82661 **      Z:   The name of a column in table Y.
82662 **
82663 ** The node at the root of the subtree is modified as follows:
82664 **
82665 **    Expr.op        Changed to TK_COLUMN
82666 **    Expr.pTab      Points to the Table object for X.Y
82667 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
82668 **    Expr.iTable    The VDBE cursor number for X.Y
82669 **
82670 **
82671 ** To resolve result-set references, look for expression nodes of the
82672 ** form Z (with no X and Y prefix) where the Z matches the right-hand
82673 ** size of an AS clause in the result-set of a SELECT.  The Z expression
82674 ** is replaced by a copy of the left-hand side of the result-set expression.
82675 ** Table-name and function resolution occurs on the substituted expression
82676 ** tree.  For example, in:
82677 **
82678 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
82679 **
82680 ** The "x" term of the order by is replaced by "a+b" to render:
82681 **
82682 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
82683 **
82684 ** Function calls are checked to make sure that the function is
82685 ** defined and that the correct number of arguments are specified.
82686 ** If the function is an aggregate function, then the NC_HasAgg flag is
82687 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
82688 ** If an expression contains aggregate functions then the EP_Agg
82689 ** property on the expression is set.
82690 **
82691 ** An error message is left in pParse if anything is amiss.  The number
82692 ** if errors is returned.
82693 */
82694 SQLITE_PRIVATE int sqlite3ResolveExprNames(
82695   NameContext *pNC,       /* Namespace to resolve expressions in. */
82696   Expr *pExpr             /* The expression to be analyzed. */
82697 ){
82698   u16 savedHasAgg;
82699   Walker w;
82700 
82701   if( pExpr==0 ) return 0;
82702 #if SQLITE_MAX_EXPR_DEPTH>0
82703   {
82704     Parse *pParse = pNC->pParse;
82705     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
82706       return 1;
82707     }
82708     pParse->nHeight += pExpr->nHeight;
82709   }
82710 #endif
82711   savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
82712   pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
82713   memset(&w, 0, sizeof(w));
82714   w.xExprCallback = resolveExprStep;
82715   w.xSelectCallback = resolveSelectStep;
82716   w.pParse = pNC->pParse;
82717   w.u.pNC = pNC;
82718   sqlite3WalkExpr(&w, pExpr);
82719 #if SQLITE_MAX_EXPR_DEPTH>0
82720   pNC->pParse->nHeight -= pExpr->nHeight;
82721 #endif
82722   if( pNC->nErr>0 || w.pParse->nErr>0 ){
82723     ExprSetProperty(pExpr, EP_Error);
82724   }
82725   if( pNC->ncFlags & NC_HasAgg ){
82726     ExprSetProperty(pExpr, EP_Agg);
82727   }
82728   pNC->ncFlags |= savedHasAgg;
82729   return ExprHasProperty(pExpr, EP_Error);
82730 }
82731 
82732 
82733 /*
82734 ** Resolve all names in all expressions of a SELECT and in all
82735 ** decendents of the SELECT, including compounds off of p->pPrior,
82736 ** subqueries in expressions, and subqueries used as FROM clause
82737 ** terms.
82738 **
82739 ** See sqlite3ResolveExprNames() for a description of the kinds of
82740 ** transformations that occur.
82741 **
82742 ** All SELECT statements should have been expanded using
82743 ** sqlite3SelectExpand() prior to invoking this routine.
82744 */
82745 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
82746   Parse *pParse,         /* The parser context */
82747   Select *p,             /* The SELECT statement being coded. */
82748   NameContext *pOuterNC  /* Name context for parent SELECT statement */
82749 ){
82750   Walker w;
82751 
82752   assert( p!=0 );
82753   memset(&w, 0, sizeof(w));
82754   w.xExprCallback = resolveExprStep;
82755   w.xSelectCallback = resolveSelectStep;
82756   w.pParse = pParse;
82757   w.u.pNC = pOuterNC;
82758   sqlite3WalkSelect(&w, p);
82759 }
82760 
82761 /*
82762 ** Resolve names in expressions that can only reference a single table:
82763 **
82764 **    *   CHECK constraints
82765 **    *   WHERE clauses on partial indices
82766 **
82767 ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
82768 ** is set to -1 and the Expr.iColumn value is set to the column number.
82769 **
82770 ** Any errors cause an error message to be set in pParse.
82771 */
82772 SQLITE_PRIVATE void sqlite3ResolveSelfReference(
82773   Parse *pParse,      /* Parsing context */
82774   Table *pTab,        /* The table being referenced */
82775   int type,           /* NC_IsCheck or NC_PartIdx */
82776   Expr *pExpr,        /* Expression to resolve.  May be NULL. */
82777   ExprList *pList     /* Expression list to resolve.  May be NUL. */
82778 ){
82779   SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
82780   NameContext sNC;                /* Name context for pParse->pNewTable */
82781   int i;                          /* Loop counter */
82782 
82783   assert( type==NC_IsCheck || type==NC_PartIdx );
82784   memset(&sNC, 0, sizeof(sNC));
82785   memset(&sSrc, 0, sizeof(sSrc));
82786   sSrc.nSrc = 1;
82787   sSrc.a[0].zName = pTab->zName;
82788   sSrc.a[0].pTab = pTab;
82789   sSrc.a[0].iCursor = -1;
82790   sNC.pParse = pParse;
82791   sNC.pSrcList = &sSrc;
82792   sNC.ncFlags = type;
82793   if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
82794   if( pList ){
82795     for(i=0; i<pList->nExpr; i++){
82796       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
82797         return;
82798       }
82799     }
82800   }
82801 }
82802 
82803 /************** End of resolve.c *********************************************/
82804 /************** Begin file expr.c ********************************************/
82805 /*
82806 ** 2001 September 15
82807 **
82808 ** The author disclaims copyright to this source code.  In place of
82809 ** a legal notice, here is a blessing:
82810 **
82811 **    May you do good and not evil.
82812 **    May you find forgiveness for yourself and forgive others.
82813 **    May you share freely, never taking more than you give.
82814 **
82815 *************************************************************************
82816 ** This file contains routines used for analyzing expressions and
82817 ** for generating VDBE code that evaluates expressions in SQLite.
82818 */
82819 
82820 /*
82821 ** Return the 'affinity' of the expression pExpr if any.
82822 **
82823 ** If pExpr is a column, a reference to a column via an 'AS' alias,
82824 ** or a sub-select with a column as the return value, then the
82825 ** affinity of that column is returned. Otherwise, 0x00 is returned,
82826 ** indicating no affinity for the expression.
82827 **
82828 ** i.e. the WHERE clause expressions in the following statements all
82829 ** have an affinity:
82830 **
82831 ** CREATE TABLE t1(a);
82832 ** SELECT * FROM t1 WHERE a;
82833 ** SELECT a AS b FROM t1 WHERE b;
82834 ** SELECT * FROM t1 WHERE (select a from t1);
82835 */
82836 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
82837   int op;
82838   pExpr = sqlite3ExprSkipCollate(pExpr);
82839   if( pExpr->flags & EP_Generic ) return 0;
82840   op = pExpr->op;
82841   if( op==TK_SELECT ){
82842     assert( pExpr->flags&EP_xIsSelect );
82843     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
82844   }
82845 #ifndef SQLITE_OMIT_CAST
82846   if( op==TK_CAST ){
82847     assert( !ExprHasProperty(pExpr, EP_IntValue) );
82848     return sqlite3AffinityType(pExpr->u.zToken, 0);
82849   }
82850 #endif
82851   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
82852    && pExpr->pTab!=0
82853   ){
82854     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
82855     ** a TK_COLUMN but was previously evaluated and cached in a register */
82856     int j = pExpr->iColumn;
82857     if( j<0 ) return SQLITE_AFF_INTEGER;
82858     assert( pExpr->pTab && j<pExpr->pTab->nCol );
82859     return pExpr->pTab->aCol[j].affinity;
82860   }
82861   return pExpr->affinity;
82862 }
82863 
82864 /*
82865 ** Set the collating sequence for expression pExpr to be the collating
82866 ** sequence named by pToken.   Return a pointer to a new Expr node that
82867 ** implements the COLLATE operator.
82868 **
82869 ** If a memory allocation error occurs, that fact is recorded in pParse->db
82870 ** and the pExpr parameter is returned unchanged.
82871 */
82872 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
82873   Parse *pParse,           /* Parsing context */
82874   Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
82875   const Token *pCollName,  /* Name of collating sequence */
82876   int dequote              /* True to dequote pCollName */
82877 ){
82878   if( pCollName->n>0 ){
82879     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
82880     if( pNew ){
82881       pNew->pLeft = pExpr;
82882       pNew->flags |= EP_Collate|EP_Skip;
82883       pExpr = pNew;
82884     }
82885   }
82886   return pExpr;
82887 }
82888 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
82889   Token s;
82890   assert( zC!=0 );
82891   s.z = zC;
82892   s.n = sqlite3Strlen30(s.z);
82893   return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
82894 }
82895 
82896 /*
82897 ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
82898 ** or likelihood() function at the root of an expression.
82899 */
82900 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
82901   while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
82902     if( ExprHasProperty(pExpr, EP_Unlikely) ){
82903       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
82904       assert( pExpr->x.pList->nExpr>0 );
82905       assert( pExpr->op==TK_FUNCTION );
82906       pExpr = pExpr->x.pList->a[0].pExpr;
82907     }else{
82908       assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
82909       pExpr = pExpr->pLeft;
82910     }
82911   }
82912   return pExpr;
82913 }
82914 
82915 /*
82916 ** Return the collation sequence for the expression pExpr. If
82917 ** there is no defined collating sequence, return NULL.
82918 **
82919 ** The collating sequence might be determined by a COLLATE operator
82920 ** or by the presence of a column with a defined collating sequence.
82921 ** COLLATE operators take first precedence.  Left operands take
82922 ** precedence over right operands.
82923 */
82924 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
82925   sqlite3 *db = pParse->db;
82926   CollSeq *pColl = 0;
82927   Expr *p = pExpr;
82928   while( p ){
82929     int op = p->op;
82930     if( p->flags & EP_Generic ) break;
82931     if( op==TK_CAST || op==TK_UPLUS ){
82932       p = p->pLeft;
82933       continue;
82934     }
82935     if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
82936       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
82937       break;
82938     }
82939     if( (op==TK_AGG_COLUMN || op==TK_COLUMN
82940           || op==TK_REGISTER || op==TK_TRIGGER)
82941      && p->pTab!=0
82942     ){
82943       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
82944       ** a TK_COLUMN but was previously evaluated and cached in a register */
82945       int j = p->iColumn;
82946       if( j>=0 ){
82947         const char *zColl = p->pTab->aCol[j].zColl;
82948         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
82949       }
82950       break;
82951     }
82952     if( p->flags & EP_Collate ){
82953       if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
82954         p = p->pLeft;
82955       }else{
82956         Expr *pNext  = p->pRight;
82957         /* The Expr.x union is never used at the same time as Expr.pRight */
82958         assert( p->x.pList==0 || p->pRight==0 );
82959         /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
82960         ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
82961         ** least one EP_Collate. Thus the following two ALWAYS. */
82962         if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
82963           int i;
82964           for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
82965             if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
82966               pNext = p->x.pList->a[i].pExpr;
82967               break;
82968             }
82969           }
82970         }
82971         p = pNext;
82972       }
82973     }else{
82974       break;
82975     }
82976   }
82977   if( sqlite3CheckCollSeq(pParse, pColl) ){
82978     pColl = 0;
82979   }
82980   return pColl;
82981 }
82982 
82983 /*
82984 ** pExpr is an operand of a comparison operator.  aff2 is the
82985 ** type affinity of the other operand.  This routine returns the
82986 ** type affinity that should be used for the comparison operator.
82987 */
82988 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
82989   char aff1 = sqlite3ExprAffinity(pExpr);
82990   if( aff1 && aff2 ){
82991     /* Both sides of the comparison are columns. If one has numeric
82992     ** affinity, use that. Otherwise use no affinity.
82993     */
82994     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
82995       return SQLITE_AFF_NUMERIC;
82996     }else{
82997       return SQLITE_AFF_NONE;
82998     }
82999   }else if( !aff1 && !aff2 ){
83000     /* Neither side of the comparison is a column.  Compare the
83001     ** results directly.
83002     */
83003     return SQLITE_AFF_NONE;
83004   }else{
83005     /* One side is a column, the other is not. Use the columns affinity. */
83006     assert( aff1==0 || aff2==0 );
83007     return (aff1 + aff2);
83008   }
83009 }
83010 
83011 /*
83012 ** pExpr is a comparison operator.  Return the type affinity that should
83013 ** be applied to both operands prior to doing the comparison.
83014 */
83015 static char comparisonAffinity(Expr *pExpr){
83016   char aff;
83017   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
83018           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
83019           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
83020   assert( pExpr->pLeft );
83021   aff = sqlite3ExprAffinity(pExpr->pLeft);
83022   if( pExpr->pRight ){
83023     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
83024   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
83025     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
83026   }else if( !aff ){
83027     aff = SQLITE_AFF_NONE;
83028   }
83029   return aff;
83030 }
83031 
83032 /*
83033 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
83034 ** idx_affinity is the affinity of an indexed column. Return true
83035 ** if the index with affinity idx_affinity may be used to implement
83036 ** the comparison in pExpr.
83037 */
83038 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
83039   char aff = comparisonAffinity(pExpr);
83040   switch( aff ){
83041     case SQLITE_AFF_NONE:
83042       return 1;
83043     case SQLITE_AFF_TEXT:
83044       return idx_affinity==SQLITE_AFF_TEXT;
83045     default:
83046       return sqlite3IsNumericAffinity(idx_affinity);
83047   }
83048 }
83049 
83050 /*
83051 ** Return the P5 value that should be used for a binary comparison
83052 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
83053 */
83054 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
83055   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
83056   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
83057   return aff;
83058 }
83059 
83060 /*
83061 ** Return a pointer to the collation sequence that should be used by
83062 ** a binary comparison operator comparing pLeft and pRight.
83063 **
83064 ** If the left hand expression has a collating sequence type, then it is
83065 ** used. Otherwise the collation sequence for the right hand expression
83066 ** is used, or the default (BINARY) if neither expression has a collating
83067 ** type.
83068 **
83069 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
83070 ** it is not considered.
83071 */
83072 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
83073   Parse *pParse,
83074   Expr *pLeft,
83075   Expr *pRight
83076 ){
83077   CollSeq *pColl;
83078   assert( pLeft );
83079   if( pLeft->flags & EP_Collate ){
83080     pColl = sqlite3ExprCollSeq(pParse, pLeft);
83081   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
83082     pColl = sqlite3ExprCollSeq(pParse, pRight);
83083   }else{
83084     pColl = sqlite3ExprCollSeq(pParse, pLeft);
83085     if( !pColl ){
83086       pColl = sqlite3ExprCollSeq(pParse, pRight);
83087     }
83088   }
83089   return pColl;
83090 }
83091 
83092 /*
83093 ** Generate code for a comparison operator.
83094 */
83095 static int codeCompare(
83096   Parse *pParse,    /* The parsing (and code generating) context */
83097   Expr *pLeft,      /* The left operand */
83098   Expr *pRight,     /* The right operand */
83099   int opcode,       /* The comparison opcode */
83100   int in1, int in2, /* Register holding operands */
83101   int dest,         /* Jump here if true.  */
83102   int jumpIfNull    /* If true, jump if either operand is NULL */
83103 ){
83104   int p5;
83105   int addr;
83106   CollSeq *p4;
83107 
83108   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
83109   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
83110   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
83111                            (void*)p4, P4_COLLSEQ);
83112   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
83113   return addr;
83114 }
83115 
83116 #if SQLITE_MAX_EXPR_DEPTH>0
83117 /*
83118 ** Check that argument nHeight is less than or equal to the maximum
83119 ** expression depth allowed. If it is not, leave an error message in
83120 ** pParse.
83121 */
83122 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
83123   int rc = SQLITE_OK;
83124   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
83125   if( nHeight>mxHeight ){
83126     sqlite3ErrorMsg(pParse,
83127        "Expression tree is too large (maximum depth %d)", mxHeight
83128     );
83129     rc = SQLITE_ERROR;
83130   }
83131   return rc;
83132 }
83133 
83134 /* The following three functions, heightOfExpr(), heightOfExprList()
83135 ** and heightOfSelect(), are used to determine the maximum height
83136 ** of any expression tree referenced by the structure passed as the
83137 ** first argument.
83138 **
83139 ** If this maximum height is greater than the current value pointed
83140 ** to by pnHeight, the second parameter, then set *pnHeight to that
83141 ** value.
83142 */
83143 static void heightOfExpr(Expr *p, int *pnHeight){
83144   if( p ){
83145     if( p->nHeight>*pnHeight ){
83146       *pnHeight = p->nHeight;
83147     }
83148   }
83149 }
83150 static void heightOfExprList(ExprList *p, int *pnHeight){
83151   if( p ){
83152     int i;
83153     for(i=0; i<p->nExpr; i++){
83154       heightOfExpr(p->a[i].pExpr, pnHeight);
83155     }
83156   }
83157 }
83158 static void heightOfSelect(Select *p, int *pnHeight){
83159   if( p ){
83160     heightOfExpr(p->pWhere, pnHeight);
83161     heightOfExpr(p->pHaving, pnHeight);
83162     heightOfExpr(p->pLimit, pnHeight);
83163     heightOfExpr(p->pOffset, pnHeight);
83164     heightOfExprList(p->pEList, pnHeight);
83165     heightOfExprList(p->pGroupBy, pnHeight);
83166     heightOfExprList(p->pOrderBy, pnHeight);
83167     heightOfSelect(p->pPrior, pnHeight);
83168   }
83169 }
83170 
83171 /*
83172 ** Set the Expr.nHeight variable in the structure passed as an
83173 ** argument. An expression with no children, Expr.pList or
83174 ** Expr.pSelect member has a height of 1. Any other expression
83175 ** has a height equal to the maximum height of any other
83176 ** referenced Expr plus one.
83177 **
83178 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
83179 ** if appropriate.
83180 */
83181 static void exprSetHeight(Expr *p){
83182   int nHeight = 0;
83183   heightOfExpr(p->pLeft, &nHeight);
83184   heightOfExpr(p->pRight, &nHeight);
83185   if( ExprHasProperty(p, EP_xIsSelect) ){
83186     heightOfSelect(p->x.pSelect, &nHeight);
83187   }else if( p->x.pList ){
83188     heightOfExprList(p->x.pList, &nHeight);
83189     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
83190   }
83191   p->nHeight = nHeight + 1;
83192 }
83193 
83194 /*
83195 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
83196 ** the height is greater than the maximum allowed expression depth,
83197 ** leave an error in pParse.
83198 **
83199 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
83200 ** Expr.flags.
83201 */
83202 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
83203   if( pParse->nErr ) return;
83204   exprSetHeight(p);
83205   sqlite3ExprCheckHeight(pParse, p->nHeight);
83206 }
83207 
83208 /*
83209 ** Return the maximum height of any expression tree referenced
83210 ** by the select statement passed as an argument.
83211 */
83212 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
83213   int nHeight = 0;
83214   heightOfSelect(p, &nHeight);
83215   return nHeight;
83216 }
83217 #else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
83218 /*
83219 ** Propagate all EP_Propagate flags from the Expr.x.pList into
83220 ** Expr.flags.
83221 */
83222 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
83223   if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
83224     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
83225   }
83226 }
83227 #define exprSetHeight(y)
83228 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
83229 
83230 /*
83231 ** This routine is the core allocator for Expr nodes.
83232 **
83233 ** Construct a new expression node and return a pointer to it.  Memory
83234 ** for this node and for the pToken argument is a single allocation
83235 ** obtained from sqlite3DbMalloc().  The calling function
83236 ** is responsible for making sure the node eventually gets freed.
83237 **
83238 ** If dequote is true, then the token (if it exists) is dequoted.
83239 ** If dequote is false, no dequoting is performance.  The deQuote
83240 ** parameter is ignored if pToken is NULL or if the token does not
83241 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
83242 ** then the EP_DblQuoted flag is set on the expression node.
83243 **
83244 ** Special case:  If op==TK_INTEGER and pToken points to a string that
83245 ** can be translated into a 32-bit integer, then the token is not
83246 ** stored in u.zToken.  Instead, the integer values is written
83247 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
83248 ** is allocated to hold the integer text and the dequote flag is ignored.
83249 */
83250 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
83251   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
83252   int op,                 /* Expression opcode */
83253   const Token *pToken,    /* Token argument.  Might be NULL */
83254   int dequote             /* True to dequote */
83255 ){
83256   Expr *pNew;
83257   int nExtra = 0;
83258   int iValue = 0;
83259 
83260   if( pToken ){
83261     if( op!=TK_INTEGER || pToken->z==0
83262           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
83263       nExtra = pToken->n+1;
83264       assert( iValue>=0 );
83265     }
83266   }
83267   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
83268   if( pNew ){
83269     pNew->op = (u8)op;
83270     pNew->iAgg = -1;
83271     if( pToken ){
83272       if( nExtra==0 ){
83273         pNew->flags |= EP_IntValue;
83274         pNew->u.iValue = iValue;
83275       }else{
83276         int c;
83277         pNew->u.zToken = (char*)&pNew[1];
83278         assert( pToken->z!=0 || pToken->n==0 );
83279         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
83280         pNew->u.zToken[pToken->n] = 0;
83281         if( dequote && nExtra>=3
83282              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
83283           sqlite3Dequote(pNew->u.zToken);
83284           if( c=='"' ) pNew->flags |= EP_DblQuoted;
83285         }
83286       }
83287     }
83288 #if SQLITE_MAX_EXPR_DEPTH>0
83289     pNew->nHeight = 1;
83290 #endif
83291   }
83292   return pNew;
83293 }
83294 
83295 /*
83296 ** Allocate a new expression node from a zero-terminated token that has
83297 ** already been dequoted.
83298 */
83299 SQLITE_PRIVATE Expr *sqlite3Expr(
83300   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
83301   int op,                 /* Expression opcode */
83302   const char *zToken      /* Token argument.  Might be NULL */
83303 ){
83304   Token x;
83305   x.z = zToken;
83306   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
83307   return sqlite3ExprAlloc(db, op, &x, 0);
83308 }
83309 
83310 /*
83311 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
83312 **
83313 ** If pRoot==NULL that means that a memory allocation error has occurred.
83314 ** In that case, delete the subtrees pLeft and pRight.
83315 */
83316 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
83317   sqlite3 *db,
83318   Expr *pRoot,
83319   Expr *pLeft,
83320   Expr *pRight
83321 ){
83322   if( pRoot==0 ){
83323     assert( db->mallocFailed );
83324     sqlite3ExprDelete(db, pLeft);
83325     sqlite3ExprDelete(db, pRight);
83326   }else{
83327     if( pRight ){
83328       pRoot->pRight = pRight;
83329       pRoot->flags |= EP_Propagate & pRight->flags;
83330     }
83331     if( pLeft ){
83332       pRoot->pLeft = pLeft;
83333       pRoot->flags |= EP_Propagate & pLeft->flags;
83334     }
83335     exprSetHeight(pRoot);
83336   }
83337 }
83338 
83339 /*
83340 ** Allocate an Expr node which joins as many as two subtrees.
83341 **
83342 ** One or both of the subtrees can be NULL.  Return a pointer to the new
83343 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
83344 ** free the subtrees and return NULL.
83345 */
83346 SQLITE_PRIVATE Expr *sqlite3PExpr(
83347   Parse *pParse,          /* Parsing context */
83348   int op,                 /* Expression opcode */
83349   Expr *pLeft,            /* Left operand */
83350   Expr *pRight,           /* Right operand */
83351   const Token *pToken     /* Argument token */
83352 ){
83353   Expr *p;
83354   if( op==TK_AND && pLeft && pRight && pParse->nErr==0 ){
83355     /* Take advantage of short-circuit false optimization for AND */
83356     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
83357   }else{
83358     p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
83359     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
83360   }
83361   if( p ) {
83362     sqlite3ExprCheckHeight(pParse, p->nHeight);
83363   }
83364   return p;
83365 }
83366 
83367 /*
83368 ** If the expression is always either TRUE or FALSE (respectively),
83369 ** then return 1.  If one cannot determine the truth value of the
83370 ** expression at compile-time return 0.
83371 **
83372 ** This is an optimization.  If is OK to return 0 here even if
83373 ** the expression really is always false or false (a false negative).
83374 ** But it is a bug to return 1 if the expression might have different
83375 ** boolean values in different circumstances (a false positive.)
83376 **
83377 ** Note that if the expression is part of conditional for a
83378 ** LEFT JOIN, then we cannot determine at compile-time whether or not
83379 ** is it true or false, so always return 0.
83380 */
83381 static int exprAlwaysTrue(Expr *p){
83382   int v = 0;
83383   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
83384   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
83385   return v!=0;
83386 }
83387 static int exprAlwaysFalse(Expr *p){
83388   int v = 0;
83389   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
83390   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
83391   return v==0;
83392 }
83393 
83394 /*
83395 ** Join two expressions using an AND operator.  If either expression is
83396 ** NULL, then just return the other expression.
83397 **
83398 ** If one side or the other of the AND is known to be false, then instead
83399 ** of returning an AND expression, just return a constant expression with
83400 ** a value of false.
83401 */
83402 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
83403   if( pLeft==0 ){
83404     return pRight;
83405   }else if( pRight==0 ){
83406     return pLeft;
83407   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
83408     sqlite3ExprDelete(db, pLeft);
83409     sqlite3ExprDelete(db, pRight);
83410     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
83411   }else{
83412     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
83413     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
83414     return pNew;
83415   }
83416 }
83417 
83418 /*
83419 ** Construct a new expression node for a function with multiple
83420 ** arguments.
83421 */
83422 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
83423   Expr *pNew;
83424   sqlite3 *db = pParse->db;
83425   assert( pToken );
83426   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
83427   if( pNew==0 ){
83428     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
83429     return 0;
83430   }
83431   pNew->x.pList = pList;
83432   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
83433   sqlite3ExprSetHeightAndFlags(pParse, pNew);
83434   return pNew;
83435 }
83436 
83437 /*
83438 ** Assign a variable number to an expression that encodes a wildcard
83439 ** in the original SQL statement.
83440 **
83441 ** Wildcards consisting of a single "?" are assigned the next sequential
83442 ** variable number.
83443 **
83444 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
83445 ** sure "nnn" is not too be to avoid a denial of service attack when
83446 ** the SQL statement comes from an external source.
83447 **
83448 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
83449 ** as the previous instance of the same wildcard.  Or if this is the first
83450 ** instance of the wildcard, the next sequential variable number is
83451 ** assigned.
83452 */
83453 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
83454   sqlite3 *db = pParse->db;
83455   const char *z;
83456 
83457   if( pExpr==0 ) return;
83458   assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
83459   z = pExpr->u.zToken;
83460   assert( z!=0 );
83461   assert( z[0]!=0 );
83462   if( z[1]==0 ){
83463     /* Wildcard of the form "?".  Assign the next variable number */
83464     assert( z[0]=='?' );
83465     pExpr->iColumn = (ynVar)(++pParse->nVar);
83466   }else{
83467     ynVar x = 0;
83468     u32 n = sqlite3Strlen30(z);
83469     if( z[0]=='?' ){
83470       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
83471       ** use it as the variable number */
83472       i64 i;
83473       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
83474       pExpr->iColumn = x = (ynVar)i;
83475       testcase( i==0 );
83476       testcase( i==1 );
83477       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
83478       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
83479       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
83480         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
83481             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
83482         x = 0;
83483       }
83484       if( i>pParse->nVar ){
83485         pParse->nVar = (int)i;
83486       }
83487     }else{
83488       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
83489       ** number as the prior appearance of the same name, or if the name
83490       ** has never appeared before, reuse the same variable number
83491       */
83492       ynVar i;
83493       for(i=0; i<pParse->nzVar; i++){
83494         if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
83495           pExpr->iColumn = x = (ynVar)i+1;
83496           break;
83497         }
83498       }
83499       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
83500     }
83501     if( x>0 ){
83502       if( x>pParse->nzVar ){
83503         char **a;
83504         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
83505         if( a==0 ) return;  /* Error reported through db->mallocFailed */
83506         pParse->azVar = a;
83507         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
83508         pParse->nzVar = x;
83509       }
83510       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
83511         sqlite3DbFree(db, pParse->azVar[x-1]);
83512         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
83513       }
83514     }
83515   }
83516   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
83517     sqlite3ErrorMsg(pParse, "too many SQL variables");
83518   }
83519 }
83520 
83521 /*
83522 ** Recursively delete an expression tree.
83523 */
83524 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
83525   if( p==0 ) return;
83526   /* Sanity check: Assert that the IntValue is non-negative if it exists */
83527   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
83528   if( !ExprHasProperty(p, EP_TokenOnly) ){
83529     /* The Expr.x union is never used at the same time as Expr.pRight */
83530     assert( p->x.pList==0 || p->pRight==0 );
83531     sqlite3ExprDelete(db, p->pLeft);
83532     sqlite3ExprDelete(db, p->pRight);
83533     if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
83534     if( ExprHasProperty(p, EP_xIsSelect) ){
83535       sqlite3SelectDelete(db, p->x.pSelect);
83536     }else{
83537       sqlite3ExprListDelete(db, p->x.pList);
83538     }
83539   }
83540   if( !ExprHasProperty(p, EP_Static) ){
83541     sqlite3DbFree(db, p);
83542   }
83543 }
83544 
83545 /*
83546 ** Return the number of bytes allocated for the expression structure
83547 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
83548 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
83549 */
83550 static int exprStructSize(Expr *p){
83551   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
83552   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
83553   return EXPR_FULLSIZE;
83554 }
83555 
83556 /*
83557 ** The dupedExpr*Size() routines each return the number of bytes required
83558 ** to store a copy of an expression or expression tree.  They differ in
83559 ** how much of the tree is measured.
83560 **
83561 **     dupedExprStructSize()     Size of only the Expr structure
83562 **     dupedExprNodeSize()       Size of Expr + space for token
83563 **     dupedExprSize()           Expr + token + subtree components
83564 **
83565 ***************************************************************************
83566 **
83567 ** The dupedExprStructSize() function returns two values OR-ed together:
83568 ** (1) the space required for a copy of the Expr structure only and
83569 ** (2) the EP_xxx flags that indicate what the structure size should be.
83570 ** The return values is always one of:
83571 **
83572 **      EXPR_FULLSIZE
83573 **      EXPR_REDUCEDSIZE   | EP_Reduced
83574 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
83575 **
83576 ** The size of the structure can be found by masking the return value
83577 ** of this routine with 0xfff.  The flags can be found by masking the
83578 ** return value with EP_Reduced|EP_TokenOnly.
83579 **
83580 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
83581 ** (unreduced) Expr objects as they or originally constructed by the parser.
83582 ** During expression analysis, extra information is computed and moved into
83583 ** later parts of teh Expr object and that extra information might get chopped
83584 ** off if the expression is reduced.  Note also that it does not work to
83585 ** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
83586 ** to reduce a pristine expression tree from the parser.  The implementation
83587 ** of dupedExprStructSize() contain multiple assert() statements that attempt
83588 ** to enforce this constraint.
83589 */
83590 static int dupedExprStructSize(Expr *p, int flags){
83591   int nSize;
83592   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
83593   assert( EXPR_FULLSIZE<=0xfff );
83594   assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
83595   if( 0==(flags&EXPRDUP_REDUCE) ){
83596     nSize = EXPR_FULLSIZE;
83597   }else{
83598     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
83599     assert( !ExprHasProperty(p, EP_FromJoin) );
83600     assert( !ExprHasProperty(p, EP_MemToken) );
83601     assert( !ExprHasProperty(p, EP_NoReduce) );
83602     if( p->pLeft || p->x.pList ){
83603       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
83604     }else{
83605       assert( p->pRight==0 );
83606       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
83607     }
83608   }
83609   return nSize;
83610 }
83611 
83612 /*
83613 ** This function returns the space in bytes required to store the copy
83614 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
83615 ** string is defined.)
83616 */
83617 static int dupedExprNodeSize(Expr *p, int flags){
83618   int nByte = dupedExprStructSize(p, flags) & 0xfff;
83619   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
83620     nByte += sqlite3Strlen30(p->u.zToken)+1;
83621   }
83622   return ROUND8(nByte);
83623 }
83624 
83625 /*
83626 ** Return the number of bytes required to create a duplicate of the
83627 ** expression passed as the first argument. The second argument is a
83628 ** mask containing EXPRDUP_XXX flags.
83629 **
83630 ** The value returned includes space to create a copy of the Expr struct
83631 ** itself and the buffer referred to by Expr.u.zToken, if any.
83632 **
83633 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
83634 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
83635 ** and Expr.pRight variables (but not for any structures pointed to or
83636 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
83637 */
83638 static int dupedExprSize(Expr *p, int flags){
83639   int nByte = 0;
83640   if( p ){
83641     nByte = dupedExprNodeSize(p, flags);
83642     if( flags&EXPRDUP_REDUCE ){
83643       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
83644     }
83645   }
83646   return nByte;
83647 }
83648 
83649 /*
83650 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
83651 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
83652 ** to store the copy of expression p, the copies of p->u.zToken
83653 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
83654 ** if any. Before returning, *pzBuffer is set to the first byte past the
83655 ** portion of the buffer copied into by this function.
83656 */
83657 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
83658   Expr *pNew = 0;                      /* Value to return */
83659   if( p ){
83660     const int isReduced = (flags&EXPRDUP_REDUCE);
83661     u8 *zAlloc;
83662     u32 staticFlag = 0;
83663 
83664     assert( pzBuffer==0 || isReduced );
83665 
83666     /* Figure out where to write the new Expr structure. */
83667     if( pzBuffer ){
83668       zAlloc = *pzBuffer;
83669       staticFlag = EP_Static;
83670     }else{
83671       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
83672     }
83673     pNew = (Expr *)zAlloc;
83674 
83675     if( pNew ){
83676       /* Set nNewSize to the size allocated for the structure pointed to
83677       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
83678       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
83679       ** by the copy of the p->u.zToken string (if any).
83680       */
83681       const unsigned nStructSize = dupedExprStructSize(p, flags);
83682       const int nNewSize = nStructSize & 0xfff;
83683       int nToken;
83684       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
83685         nToken = sqlite3Strlen30(p->u.zToken) + 1;
83686       }else{
83687         nToken = 0;
83688       }
83689       if( isReduced ){
83690         assert( ExprHasProperty(p, EP_Reduced)==0 );
83691         memcpy(zAlloc, p, nNewSize);
83692       }else{
83693         int nSize = exprStructSize(p);
83694         memcpy(zAlloc, p, nSize);
83695         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
83696       }
83697 
83698       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
83699       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
83700       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
83701       pNew->flags |= staticFlag;
83702 
83703       /* Copy the p->u.zToken string, if any. */
83704       if( nToken ){
83705         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
83706         memcpy(zToken, p->u.zToken, nToken);
83707       }
83708 
83709       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
83710         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
83711         if( ExprHasProperty(p, EP_xIsSelect) ){
83712           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
83713         }else{
83714           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
83715         }
83716       }
83717 
83718       /* Fill in pNew->pLeft and pNew->pRight. */
83719       if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
83720         zAlloc += dupedExprNodeSize(p, flags);
83721         if( ExprHasProperty(pNew, EP_Reduced) ){
83722           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
83723           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
83724         }
83725         if( pzBuffer ){
83726           *pzBuffer = zAlloc;
83727         }
83728       }else{
83729         if( !ExprHasProperty(p, EP_TokenOnly) ){
83730           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
83731           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
83732         }
83733       }
83734 
83735     }
83736   }
83737   return pNew;
83738 }
83739 
83740 /*
83741 ** Create and return a deep copy of the object passed as the second
83742 ** argument. If an OOM condition is encountered, NULL is returned
83743 ** and the db->mallocFailed flag set.
83744 */
83745 #ifndef SQLITE_OMIT_CTE
83746 static With *withDup(sqlite3 *db, With *p){
83747   With *pRet = 0;
83748   if( p ){
83749     int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
83750     pRet = sqlite3DbMallocZero(db, nByte);
83751     if( pRet ){
83752       int i;
83753       pRet->nCte = p->nCte;
83754       for(i=0; i<p->nCte; i++){
83755         pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
83756         pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
83757         pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
83758       }
83759     }
83760   }
83761   return pRet;
83762 }
83763 #else
83764 # define withDup(x,y) 0
83765 #endif
83766 
83767 /*
83768 ** The following group of routines make deep copies of expressions,
83769 ** expression lists, ID lists, and select statements.  The copies can
83770 ** be deleted (by being passed to their respective ...Delete() routines)
83771 ** without effecting the originals.
83772 **
83773 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
83774 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
83775 ** by subsequent calls to sqlite*ListAppend() routines.
83776 **
83777 ** Any tables that the SrcList might point to are not duplicated.
83778 **
83779 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
83780 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
83781 ** truncated version of the usual Expr structure that will be stored as
83782 ** part of the in-memory representation of the database schema.
83783 */
83784 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
83785   return exprDup(db, p, flags, 0);
83786 }
83787 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
83788   ExprList *pNew;
83789   struct ExprList_item *pItem, *pOldItem;
83790   int i;
83791   if( p==0 ) return 0;
83792   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
83793   if( pNew==0 ) return 0;
83794   pNew->nExpr = i = p->nExpr;
83795   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
83796   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
83797   if( pItem==0 ){
83798     sqlite3DbFree(db, pNew);
83799     return 0;
83800   }
83801   pOldItem = p->a;
83802   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
83803     Expr *pOldExpr = pOldItem->pExpr;
83804     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
83805     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
83806     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
83807     pItem->sortOrder = pOldItem->sortOrder;
83808     pItem->done = 0;
83809     pItem->bSpanIsTab = pOldItem->bSpanIsTab;
83810     pItem->u = pOldItem->u;
83811   }
83812   return pNew;
83813 }
83814 
83815 /*
83816 ** If cursors, triggers, views and subqueries are all omitted from
83817 ** the build, then none of the following routines, except for
83818 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
83819 ** called with a NULL argument.
83820 */
83821 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
83822  || !defined(SQLITE_OMIT_SUBQUERY)
83823 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
83824   SrcList *pNew;
83825   int i;
83826   int nByte;
83827   if( p==0 ) return 0;
83828   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
83829   pNew = sqlite3DbMallocRaw(db, nByte );
83830   if( pNew==0 ) return 0;
83831   pNew->nSrc = pNew->nAlloc = p->nSrc;
83832   for(i=0; i<p->nSrc; i++){
83833     struct SrcList_item *pNewItem = &pNew->a[i];
83834     struct SrcList_item *pOldItem = &p->a[i];
83835     Table *pTab;
83836     pNewItem->pSchema = pOldItem->pSchema;
83837     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
83838     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
83839     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
83840     pNewItem->jointype = pOldItem->jointype;
83841     pNewItem->iCursor = pOldItem->iCursor;
83842     pNewItem->addrFillSub = pOldItem->addrFillSub;
83843     pNewItem->regReturn = pOldItem->regReturn;
83844     pNewItem->isCorrelated = pOldItem->isCorrelated;
83845     pNewItem->viaCoroutine = pOldItem->viaCoroutine;
83846     pNewItem->isRecursive = pOldItem->isRecursive;
83847     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
83848     pNewItem->notIndexed = pOldItem->notIndexed;
83849     pNewItem->pIndex = pOldItem->pIndex;
83850     pTab = pNewItem->pTab = pOldItem->pTab;
83851     if( pTab ){
83852       pTab->nRef++;
83853     }
83854     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
83855     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
83856     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
83857     pNewItem->colUsed = pOldItem->colUsed;
83858   }
83859   return pNew;
83860 }
83861 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
83862   IdList *pNew;
83863   int i;
83864   if( p==0 ) return 0;
83865   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
83866   if( pNew==0 ) return 0;
83867   pNew->nId = p->nId;
83868   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
83869   if( pNew->a==0 ){
83870     sqlite3DbFree(db, pNew);
83871     return 0;
83872   }
83873   /* Note that because the size of the allocation for p->a[] is not
83874   ** necessarily a power of two, sqlite3IdListAppend() may not be called
83875   ** on the duplicate created by this function. */
83876   for(i=0; i<p->nId; i++){
83877     struct IdList_item *pNewItem = &pNew->a[i];
83878     struct IdList_item *pOldItem = &p->a[i];
83879     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
83880     pNewItem->idx = pOldItem->idx;
83881   }
83882   return pNew;
83883 }
83884 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
83885   Select *pNew, *pPrior;
83886   if( p==0 ) return 0;
83887   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
83888   if( pNew==0 ) return 0;
83889   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
83890   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
83891   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
83892   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
83893   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
83894   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
83895   pNew->op = p->op;
83896   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
83897   if( pPrior ) pPrior->pNext = pNew;
83898   pNew->pNext = 0;
83899   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
83900   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
83901   pNew->iLimit = 0;
83902   pNew->iOffset = 0;
83903   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
83904   pNew->addrOpenEphm[0] = -1;
83905   pNew->addrOpenEphm[1] = -1;
83906   pNew->nSelectRow = p->nSelectRow;
83907   pNew->pWith = withDup(db, p->pWith);
83908   sqlite3SelectSetName(pNew, p->zSelName);
83909   return pNew;
83910 }
83911 #else
83912 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
83913   assert( p==0 );
83914   return 0;
83915 }
83916 #endif
83917 
83918 
83919 /*
83920 ** Add a new element to the end of an expression list.  If pList is
83921 ** initially NULL, then create a new expression list.
83922 **
83923 ** If a memory allocation error occurs, the entire list is freed and
83924 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
83925 ** that the new entry was successfully appended.
83926 */
83927 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
83928   Parse *pParse,          /* Parsing context */
83929   ExprList *pList,        /* List to which to append. Might be NULL */
83930   Expr *pExpr             /* Expression to be appended. Might be NULL */
83931 ){
83932   sqlite3 *db = pParse->db;
83933   if( pList==0 ){
83934     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
83935     if( pList==0 ){
83936       goto no_mem;
83937     }
83938     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
83939     if( pList->a==0 ) goto no_mem;
83940   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
83941     struct ExprList_item *a;
83942     assert( pList->nExpr>0 );
83943     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
83944     if( a==0 ){
83945       goto no_mem;
83946     }
83947     pList->a = a;
83948   }
83949   assert( pList->a!=0 );
83950   if( 1 ){
83951     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
83952     memset(pItem, 0, sizeof(*pItem));
83953     pItem->pExpr = pExpr;
83954   }
83955   return pList;
83956 
83957 no_mem:
83958   /* Avoid leaking memory if malloc has failed. */
83959   sqlite3ExprDelete(db, pExpr);
83960   sqlite3ExprListDelete(db, pList);
83961   return 0;
83962 }
83963 
83964 /*
83965 ** Set the ExprList.a[].zName element of the most recently added item
83966 ** on the expression list.
83967 **
83968 ** pList might be NULL following an OOM error.  But pName should never be
83969 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
83970 ** is set.
83971 */
83972 SQLITE_PRIVATE void sqlite3ExprListSetName(
83973   Parse *pParse,          /* Parsing context */
83974   ExprList *pList,        /* List to which to add the span. */
83975   Token *pName,           /* Name to be added */
83976   int dequote             /* True to cause the name to be dequoted */
83977 ){
83978   assert( pList!=0 || pParse->db->mallocFailed!=0 );
83979   if( pList ){
83980     struct ExprList_item *pItem;
83981     assert( pList->nExpr>0 );
83982     pItem = &pList->a[pList->nExpr-1];
83983     assert( pItem->zName==0 );
83984     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
83985     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
83986   }
83987 }
83988 
83989 /*
83990 ** Set the ExprList.a[].zSpan element of the most recently added item
83991 ** on the expression list.
83992 **
83993 ** pList might be NULL following an OOM error.  But pSpan should never be
83994 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
83995 ** is set.
83996 */
83997 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
83998   Parse *pParse,          /* Parsing context */
83999   ExprList *pList,        /* List to which to add the span. */
84000   ExprSpan *pSpan         /* The span to be added */
84001 ){
84002   sqlite3 *db = pParse->db;
84003   assert( pList!=0 || db->mallocFailed!=0 );
84004   if( pList ){
84005     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
84006     assert( pList->nExpr>0 );
84007     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
84008     sqlite3DbFree(db, pItem->zSpan);
84009     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
84010                                     (int)(pSpan->zEnd - pSpan->zStart));
84011   }
84012 }
84013 
84014 /*
84015 ** If the expression list pEList contains more than iLimit elements,
84016 ** leave an error message in pParse.
84017 */
84018 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
84019   Parse *pParse,
84020   ExprList *pEList,
84021   const char *zObject
84022 ){
84023   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
84024   testcase( pEList && pEList->nExpr==mx );
84025   testcase( pEList && pEList->nExpr==mx+1 );
84026   if( pEList && pEList->nExpr>mx ){
84027     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
84028   }
84029 }
84030 
84031 /*
84032 ** Delete an entire expression list.
84033 */
84034 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
84035   int i;
84036   struct ExprList_item *pItem;
84037   if( pList==0 ) return;
84038   assert( pList->a!=0 || pList->nExpr==0 );
84039   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
84040     sqlite3ExprDelete(db, pItem->pExpr);
84041     sqlite3DbFree(db, pItem->zName);
84042     sqlite3DbFree(db, pItem->zSpan);
84043   }
84044   sqlite3DbFree(db, pList->a);
84045   sqlite3DbFree(db, pList);
84046 }
84047 
84048 /*
84049 ** Return the bitwise-OR of all Expr.flags fields in the given
84050 ** ExprList.
84051 */
84052 SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
84053   int i;
84054   u32 m = 0;
84055   if( pList ){
84056     for(i=0; i<pList->nExpr; i++){
84057        Expr *pExpr = pList->a[i].pExpr;
84058        if( ALWAYS(pExpr) ) m |= pExpr->flags;
84059     }
84060   }
84061   return m;
84062 }
84063 
84064 /*
84065 ** These routines are Walker callbacks used to check expressions to
84066 ** see if they are "constant" for some definition of constant.  The
84067 ** Walker.eCode value determines the type of "constant" we are looking
84068 ** for.
84069 **
84070 ** These callback routines are used to implement the following:
84071 **
84072 **     sqlite3ExprIsConstant()                  pWalker->eCode==1
84073 **     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
84074 **     sqlite3ExprRefOneTableOnly()             pWalker->eCode==3
84075 **     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
84076 **
84077 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
84078 ** is found to not be a constant.
84079 **
84080 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
84081 ** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
84082 ** an existing schema and 4 when processing a new statement.  A bound
84083 ** parameter raises an error for new statements, but is silently converted
84084 ** to NULL for existing schemas.  This allows sqlite_master tables that
84085 ** contain a bound parameter because they were generated by older versions
84086 ** of SQLite to be parsed by newer versions of SQLite without raising a
84087 ** malformed schema error.
84088 */
84089 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
84090 
84091   /* If pWalker->eCode is 2 then any term of the expression that comes from
84092   ** the ON or USING clauses of a left join disqualifies the expression
84093   ** from being considered constant. */
84094   if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
84095     pWalker->eCode = 0;
84096     return WRC_Abort;
84097   }
84098 
84099   switch( pExpr->op ){
84100     /* Consider functions to be constant if all their arguments are constant
84101     ** and either pWalker->eCode==4 or 5 or the function has the
84102     ** SQLITE_FUNC_CONST flag. */
84103     case TK_FUNCTION:
84104       if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
84105         return WRC_Continue;
84106       }else{
84107         pWalker->eCode = 0;
84108         return WRC_Abort;
84109       }
84110     case TK_ID:
84111     case TK_COLUMN:
84112     case TK_AGG_FUNCTION:
84113     case TK_AGG_COLUMN:
84114       testcase( pExpr->op==TK_ID );
84115       testcase( pExpr->op==TK_COLUMN );
84116       testcase( pExpr->op==TK_AGG_FUNCTION );
84117       testcase( pExpr->op==TK_AGG_COLUMN );
84118       if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
84119         return WRC_Continue;
84120       }else{
84121         pWalker->eCode = 0;
84122         return WRC_Abort;
84123       }
84124     case TK_VARIABLE:
84125       if( pWalker->eCode==5 ){
84126         /* Silently convert bound parameters that appear inside of CREATE
84127         ** statements into a NULL when parsing the CREATE statement text out
84128         ** of the sqlite_master table */
84129         pExpr->op = TK_NULL;
84130       }else if( pWalker->eCode==4 ){
84131         /* A bound parameter in a CREATE statement that originates from
84132         ** sqlite3_prepare() causes an error */
84133         pWalker->eCode = 0;
84134         return WRC_Abort;
84135       }
84136       /* Fall through */
84137     default:
84138       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
84139       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
84140       return WRC_Continue;
84141   }
84142 }
84143 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
84144   UNUSED_PARAMETER(NotUsed);
84145   pWalker->eCode = 0;
84146   return WRC_Abort;
84147 }
84148 static int exprIsConst(Expr *p, int initFlag, int iCur){
84149   Walker w;
84150   memset(&w, 0, sizeof(w));
84151   w.eCode = initFlag;
84152   w.xExprCallback = exprNodeIsConstant;
84153   w.xSelectCallback = selectNodeIsConstant;
84154   w.u.iCur = iCur;
84155   sqlite3WalkExpr(&w, p);
84156   return w.eCode;
84157 }
84158 
84159 /*
84160 ** Walk an expression tree.  Return non-zero if the expression is constant
84161 ** and 0 if it involves variables or function calls.
84162 **
84163 ** For the purposes of this function, a double-quoted string (ex: "abc")
84164 ** is considered a variable but a single-quoted string (ex: 'abc') is
84165 ** a constant.
84166 */
84167 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
84168   return exprIsConst(p, 1, 0);
84169 }
84170 
84171 /*
84172 ** Walk an expression tree.  Return non-zero if the expression is constant
84173 ** that does no originate from the ON or USING clauses of a join.
84174 ** Return 0 if it involves variables or function calls or terms from
84175 ** an ON or USING clause.
84176 */
84177 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
84178   return exprIsConst(p, 2, 0);
84179 }
84180 
84181 /*
84182 ** Walk an expression tree.  Return non-zero if the expression constant
84183 ** for any single row of the table with cursor iCur.  In other words, the
84184 ** expression must not refer to any non-deterministic function nor any
84185 ** table other than iCur.
84186 */
84187 SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
84188   return exprIsConst(p, 3, iCur);
84189 }
84190 
84191 /*
84192 ** Walk an expression tree.  Return non-zero if the expression is constant
84193 ** or a function call with constant arguments.  Return and 0 if there
84194 ** are any variables.
84195 **
84196 ** For the purposes of this function, a double-quoted string (ex: "abc")
84197 ** is considered a variable but a single-quoted string (ex: 'abc') is
84198 ** a constant.
84199 */
84200 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
84201   assert( isInit==0 || isInit==1 );
84202   return exprIsConst(p, 4+isInit, 0);
84203 }
84204 
84205 /*
84206 ** If the expression p codes a constant integer that is small enough
84207 ** to fit in a 32-bit integer, return 1 and put the value of the integer
84208 ** in *pValue.  If the expression is not an integer or if it is too big
84209 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
84210 */
84211 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
84212   int rc = 0;
84213 
84214   /* If an expression is an integer literal that fits in a signed 32-bit
84215   ** integer, then the EP_IntValue flag will have already been set */
84216   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
84217            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
84218 
84219   if( p->flags & EP_IntValue ){
84220     *pValue = p->u.iValue;
84221     return 1;
84222   }
84223   switch( p->op ){
84224     case TK_UPLUS: {
84225       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
84226       break;
84227     }
84228     case TK_UMINUS: {
84229       int v;
84230       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
84231         assert( v!=(-2147483647-1) );
84232         *pValue = -v;
84233         rc = 1;
84234       }
84235       break;
84236     }
84237     default: break;
84238   }
84239   return rc;
84240 }
84241 
84242 /*
84243 ** Return FALSE if there is no chance that the expression can be NULL.
84244 **
84245 ** If the expression might be NULL or if the expression is too complex
84246 ** to tell return TRUE.
84247 **
84248 ** This routine is used as an optimization, to skip OP_IsNull opcodes
84249 ** when we know that a value cannot be NULL.  Hence, a false positive
84250 ** (returning TRUE when in fact the expression can never be NULL) might
84251 ** be a small performance hit but is otherwise harmless.  On the other
84252 ** hand, a false negative (returning FALSE when the result could be NULL)
84253 ** will likely result in an incorrect answer.  So when in doubt, return
84254 ** TRUE.
84255 */
84256 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
84257   u8 op;
84258   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
84259   op = p->op;
84260   if( op==TK_REGISTER ) op = p->op2;
84261   switch( op ){
84262     case TK_INTEGER:
84263     case TK_STRING:
84264     case TK_FLOAT:
84265     case TK_BLOB:
84266       return 0;
84267     case TK_COLUMN:
84268       assert( p->pTab!=0 );
84269       return ExprHasProperty(p, EP_CanBeNull) ||
84270              (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
84271     default:
84272       return 1;
84273   }
84274 }
84275 
84276 /*
84277 ** Return TRUE if the given expression is a constant which would be
84278 ** unchanged by OP_Affinity with the affinity given in the second
84279 ** argument.
84280 **
84281 ** This routine is used to determine if the OP_Affinity operation
84282 ** can be omitted.  When in doubt return FALSE.  A false negative
84283 ** is harmless.  A false positive, however, can result in the wrong
84284 ** answer.
84285 */
84286 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
84287   u8 op;
84288   if( aff==SQLITE_AFF_NONE ) return 1;
84289   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
84290   op = p->op;
84291   if( op==TK_REGISTER ) op = p->op2;
84292   switch( op ){
84293     case TK_INTEGER: {
84294       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
84295     }
84296     case TK_FLOAT: {
84297       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
84298     }
84299     case TK_STRING: {
84300       return aff==SQLITE_AFF_TEXT;
84301     }
84302     case TK_BLOB: {
84303       return 1;
84304     }
84305     case TK_COLUMN: {
84306       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
84307       return p->iColumn<0
84308           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
84309     }
84310     default: {
84311       return 0;
84312     }
84313   }
84314 }
84315 
84316 /*
84317 ** Return TRUE if the given string is a row-id column name.
84318 */
84319 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
84320   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
84321   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
84322   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
84323   return 0;
84324 }
84325 
84326 /*
84327 ** Return true if we are able to the IN operator optimization on a
84328 ** query of the form
84329 **
84330 **       x IN (SELECT ...)
84331 **
84332 ** Where the SELECT... clause is as specified by the parameter to this
84333 ** routine.
84334 **
84335 ** The Select object passed in has already been preprocessed and no
84336 ** errors have been found.
84337 */
84338 #ifndef SQLITE_OMIT_SUBQUERY
84339 static int isCandidateForInOpt(Select *p){
84340   SrcList *pSrc;
84341   ExprList *pEList;
84342   Table *pTab;
84343   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
84344   if( p->pPrior ) return 0;              /* Not a compound SELECT */
84345   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
84346     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
84347     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
84348     return 0; /* No DISTINCT keyword and no aggregate functions */
84349   }
84350   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
84351   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
84352   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
84353   if( p->pWhere ) return 0;              /* Has no WHERE clause */
84354   pSrc = p->pSrc;
84355   assert( pSrc!=0 );
84356   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
84357   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
84358   pTab = pSrc->a[0].pTab;
84359   if( NEVER(pTab==0) ) return 0;
84360   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
84361   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
84362   pEList = p->pEList;
84363   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
84364   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
84365   return 1;
84366 }
84367 #endif /* SQLITE_OMIT_SUBQUERY */
84368 
84369 /*
84370 ** Code an OP_Once instruction and allocate space for its flag. Return the
84371 ** address of the new instruction.
84372 */
84373 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
84374   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
84375   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
84376 }
84377 
84378 /*
84379 ** Generate code that checks the left-most column of index table iCur to see if
84380 ** it contains any NULL entries.  Cause the register at regHasNull to be set
84381 ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
84382 ** to be set to NULL if iCur contains one or more NULL values.
84383 */
84384 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
84385   int j1;
84386   sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
84387   j1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
84388   sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
84389   sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
84390   VdbeComment((v, "first_entry_in(%d)", iCur));
84391   sqlite3VdbeJumpHere(v, j1);
84392 }
84393 
84394 
84395 #ifndef SQLITE_OMIT_SUBQUERY
84396 /*
84397 ** The argument is an IN operator with a list (not a subquery) on the
84398 ** right-hand side.  Return TRUE if that list is constant.
84399 */
84400 static int sqlite3InRhsIsConstant(Expr *pIn){
84401   Expr *pLHS;
84402   int res;
84403   assert( !ExprHasProperty(pIn, EP_xIsSelect) );
84404   pLHS = pIn->pLeft;
84405   pIn->pLeft = 0;
84406   res = sqlite3ExprIsConstant(pIn);
84407   pIn->pLeft = pLHS;
84408   return res;
84409 }
84410 #endif
84411 
84412 /*
84413 ** This function is used by the implementation of the IN (...) operator.
84414 ** The pX parameter is the expression on the RHS of the IN operator, which
84415 ** might be either a list of expressions or a subquery.
84416 **
84417 ** The job of this routine is to find or create a b-tree object that can
84418 ** be used either to test for membership in the RHS set or to iterate through
84419 ** all members of the RHS set, skipping duplicates.
84420 **
84421 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
84422 ** and pX->iTable is set to the index of that cursor.
84423 **
84424 ** The returned value of this function indicates the b-tree type, as follows:
84425 **
84426 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
84427 **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
84428 **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
84429 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
84430 **                         populated epheremal table.
84431 **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
84432 **                         implemented as a sequence of comparisons.
84433 **
84434 ** An existing b-tree might be used if the RHS expression pX is a simple
84435 ** subquery such as:
84436 **
84437 **     SELECT <column> FROM <table>
84438 **
84439 ** If the RHS of the IN operator is a list or a more complex subquery, then
84440 ** an ephemeral table might need to be generated from the RHS and then
84441 ** pX->iTable made to point to the ephemeral table instead of an
84442 ** existing table.
84443 **
84444 ** The inFlags parameter must contain exactly one of the bits
84445 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
84446 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
84447 ** fast membership test.  When the IN_INDEX_LOOP bit is set, the
84448 ** IN index will be used to loop over all values of the RHS of the
84449 ** IN operator.
84450 **
84451 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
84452 ** through the set members) then the b-tree must not contain duplicates.
84453 ** An epheremal table must be used unless the selected <column> is guaranteed
84454 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
84455 ** has a UNIQUE constraint or UNIQUE index.
84456 **
84457 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
84458 ** for fast set membership tests) then an epheremal table must
84459 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
84460 ** be found with <column> as its left-most column.
84461 **
84462 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
84463 ** if the RHS of the IN operator is a list (not a subquery) then this
84464 ** routine might decide that creating an ephemeral b-tree for membership
84465 ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
84466 ** calling routine should implement the IN operator using a sequence
84467 ** of Eq or Ne comparison operations.
84468 **
84469 ** When the b-tree is being used for membership tests, the calling function
84470 ** might need to know whether or not the RHS side of the IN operator
84471 ** contains a NULL.  If prRhsHasNull is not a NULL pointer and
84472 ** if there is any chance that the (...) might contain a NULL value at
84473 ** runtime, then a register is allocated and the register number written
84474 ** to *prRhsHasNull. If there is no chance that the (...) contains a
84475 ** NULL value, then *prRhsHasNull is left unchanged.
84476 **
84477 ** If a register is allocated and its location stored in *prRhsHasNull, then
84478 ** the value in that register will be NULL if the b-tree contains one or more
84479 ** NULL values, and it will be some non-NULL value if the b-tree contains no
84480 ** NULL values.
84481 */
84482 #ifndef SQLITE_OMIT_SUBQUERY
84483 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
84484   Select *p;                            /* SELECT to the right of IN operator */
84485   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
84486   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
84487   int mustBeUnique;                     /* True if RHS must be unique */
84488   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
84489 
84490   assert( pX->op==TK_IN );
84491   mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
84492 
84493   /* Check to see if an existing table or index can be used to
84494   ** satisfy the query.  This is preferable to generating a new
84495   ** ephemeral table.
84496   */
84497   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
84498   if( pParse->nErr==0 && isCandidateForInOpt(p) ){
84499     sqlite3 *db = pParse->db;              /* Database connection */
84500     Table *pTab;                           /* Table <table>. */
84501     Expr *pExpr;                           /* Expression <column> */
84502     i16 iCol;                              /* Index of column <column> */
84503     i16 iDb;                               /* Database idx for pTab */
84504 
84505     assert( p );                        /* Because of isCandidateForInOpt(p) */
84506     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
84507     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
84508     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
84509     pTab = p->pSrc->a[0].pTab;
84510     pExpr = p->pEList->a[0].pExpr;
84511     iCol = (i16)pExpr->iColumn;
84512 
84513     /* Code an OP_Transaction and OP_TableLock for <table>. */
84514     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84515     sqlite3CodeVerifySchema(pParse, iDb);
84516     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
84517 
84518     /* This function is only called from two places. In both cases the vdbe
84519     ** has already been allocated. So assume sqlite3GetVdbe() is always
84520     ** successful here.
84521     */
84522     assert(v);
84523     if( iCol<0 ){
84524       int iAddr = sqlite3CodeOnce(pParse);
84525       VdbeCoverage(v);
84526 
84527       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
84528       eType = IN_INDEX_ROWID;
84529 
84530       sqlite3VdbeJumpHere(v, iAddr);
84531     }else{
84532       Index *pIdx;                         /* Iterator variable */
84533 
84534       /* The collation sequence used by the comparison. If an index is to
84535       ** be used in place of a temp-table, it must be ordered according
84536       ** to this collation sequence.  */
84537       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
84538 
84539       /* Check that the affinity that will be used to perform the
84540       ** comparison is the same as the affinity of the column. If
84541       ** it is not, it is not possible to use any index.
84542       */
84543       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
84544 
84545       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
84546         if( (pIdx->aiColumn[0]==iCol)
84547          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
84548          && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
84549         ){
84550           int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
84551           sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
84552           sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
84553           VdbeComment((v, "%s", pIdx->zName));
84554           assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
84555           eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
84556 
84557           if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
84558             *prRhsHasNull = ++pParse->nMem;
84559             sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
84560           }
84561           sqlite3VdbeJumpHere(v, iAddr);
84562         }
84563       }
84564     }
84565   }
84566 
84567   /* If no preexisting index is available for the IN clause
84568   ** and IN_INDEX_NOOP is an allowed reply
84569   ** and the RHS of the IN operator is a list, not a subquery
84570   ** and the RHS is not contant or has two or fewer terms,
84571   ** then it is not worth creating an ephemeral table to evaluate
84572   ** the IN operator so return IN_INDEX_NOOP.
84573   */
84574   if( eType==0
84575    && (inFlags & IN_INDEX_NOOP_OK)
84576    && !ExprHasProperty(pX, EP_xIsSelect)
84577    && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
84578   ){
84579     eType = IN_INDEX_NOOP;
84580   }
84581 
84582 
84583   if( eType==0 ){
84584     /* Could not find an existing table or index to use as the RHS b-tree.
84585     ** We will have to generate an ephemeral table to do the job.
84586     */
84587     u32 savedNQueryLoop = pParse->nQueryLoop;
84588     int rMayHaveNull = 0;
84589     eType = IN_INDEX_EPH;
84590     if( inFlags & IN_INDEX_LOOP ){
84591       pParse->nQueryLoop = 0;
84592       if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
84593         eType = IN_INDEX_ROWID;
84594       }
84595     }else if( prRhsHasNull ){
84596       *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
84597     }
84598     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
84599     pParse->nQueryLoop = savedNQueryLoop;
84600   }else{
84601     pX->iTable = iTab;
84602   }
84603   return eType;
84604 }
84605 #endif
84606 
84607 /*
84608 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
84609 ** or IN operators.  Examples:
84610 **
84611 **     (SELECT a FROM b)          -- subquery
84612 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
84613 **     x IN (4,5,11)              -- IN operator with list on right-hand side
84614 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
84615 **
84616 ** The pExpr parameter describes the expression that contains the IN
84617 ** operator or subquery.
84618 **
84619 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
84620 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
84621 ** to some integer key column of a table B-Tree. In this case, use an
84622 ** intkey B-Tree to store the set of IN(...) values instead of the usual
84623 ** (slower) variable length keys B-Tree.
84624 **
84625 ** If rMayHaveNull is non-zero, that means that the operation is an IN
84626 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
84627 ** All this routine does is initialize the register given by rMayHaveNull
84628 ** to NULL.  Calling routines will take care of changing this register
84629 ** value to non-NULL if the RHS is NULL-free.
84630 **
84631 ** For a SELECT or EXISTS operator, return the register that holds the
84632 ** result.  For IN operators or if an error occurs, the return value is 0.
84633 */
84634 #ifndef SQLITE_OMIT_SUBQUERY
84635 SQLITE_PRIVATE int sqlite3CodeSubselect(
84636   Parse *pParse,          /* Parsing context */
84637   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
84638   int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
84639   int isRowid             /* If true, LHS of IN operator is a rowid */
84640 ){
84641   int jmpIfDynamic = -1;                      /* One-time test address */
84642   int rReg = 0;                           /* Register storing resulting */
84643   Vdbe *v = sqlite3GetVdbe(pParse);
84644   if( NEVER(v==0) ) return 0;
84645   sqlite3ExprCachePush(pParse);
84646 
84647   /* This code must be run in its entirety every time it is encountered
84648   ** if any of the following is true:
84649   **
84650   **    *  The right-hand side is a correlated subquery
84651   **    *  The right-hand side is an expression list containing variables
84652   **    *  We are inside a trigger
84653   **
84654   ** If all of the above are false, then we can run this code just once
84655   ** save the results, and reuse the same result on subsequent invocations.
84656   */
84657   if( !ExprHasProperty(pExpr, EP_VarSelect) ){
84658     jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
84659   }
84660 
84661 #ifndef SQLITE_OMIT_EXPLAIN
84662   if( pParse->explain==2 ){
84663     char *zMsg = sqlite3MPrintf(
84664         pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ",
84665         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
84666     );
84667     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
84668   }
84669 #endif
84670 
84671   switch( pExpr->op ){
84672     case TK_IN: {
84673       char affinity;              /* Affinity of the LHS of the IN */
84674       int addr;                   /* Address of OP_OpenEphemeral instruction */
84675       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
84676       KeyInfo *pKeyInfo = 0;      /* Key information */
84677 
84678       affinity = sqlite3ExprAffinity(pLeft);
84679 
84680       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
84681       ** expression it is handled the same way.  An ephemeral table is
84682       ** filled with single-field index keys representing the results
84683       ** from the SELECT or the <exprlist>.
84684       **
84685       ** If the 'x' expression is a column value, or the SELECT...
84686       ** statement returns a column value, then the affinity of that
84687       ** column is used to build the index keys. If both 'x' and the
84688       ** SELECT... statement are columns, then numeric affinity is used
84689       ** if either column has NUMERIC or INTEGER affinity. If neither
84690       ** 'x' nor the SELECT... statement are columns, then numeric affinity
84691       ** is used.
84692       */
84693       pExpr->iTable = pParse->nTab++;
84694       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
84695       pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
84696 
84697       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
84698         /* Case 1:     expr IN (SELECT ...)
84699         **
84700         ** Generate code to write the results of the select into the temporary
84701         ** table allocated and opened above.
84702         */
84703         Select *pSelect = pExpr->x.pSelect;
84704         SelectDest dest;
84705         ExprList *pEList;
84706 
84707         assert( !isRowid );
84708         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
84709         dest.affSdst = (u8)affinity;
84710         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
84711         pSelect->iLimit = 0;
84712         testcase( pSelect->selFlags & SF_Distinct );
84713         testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
84714         if( sqlite3Select(pParse, pSelect, &dest) ){
84715           sqlite3KeyInfoUnref(pKeyInfo);
84716           return 0;
84717         }
84718         pEList = pSelect->pEList;
84719         assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
84720         assert( pEList!=0 );
84721         assert( pEList->nExpr>0 );
84722         assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
84723         pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
84724                                                          pEList->a[0].pExpr);
84725       }else if( ALWAYS(pExpr->x.pList!=0) ){
84726         /* Case 2:     expr IN (exprlist)
84727         **
84728         ** For each expression, build an index key from the evaluation and
84729         ** store it in the temporary table. If <expr> is a column, then use
84730         ** that columns affinity when building index keys. If <expr> is not
84731         ** a column, use numeric affinity.
84732         */
84733         int i;
84734         ExprList *pList = pExpr->x.pList;
84735         struct ExprList_item *pItem;
84736         int r1, r2, r3;
84737 
84738         if( !affinity ){
84739           affinity = SQLITE_AFF_NONE;
84740         }
84741         if( pKeyInfo ){
84742           assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
84743           pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
84744         }
84745 
84746         /* Loop through each expression in <exprlist>. */
84747         r1 = sqlite3GetTempReg(pParse);
84748         r2 = sqlite3GetTempReg(pParse);
84749         if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
84750         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
84751           Expr *pE2 = pItem->pExpr;
84752           int iValToIns;
84753 
84754           /* If the expression is not constant then we will need to
84755           ** disable the test that was generated above that makes sure
84756           ** this code only executes once.  Because for a non-constant
84757           ** expression we need to rerun this code each time.
84758           */
84759           if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
84760             sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
84761             jmpIfDynamic = -1;
84762           }
84763 
84764           /* Evaluate the expression and insert it into the temp table */
84765           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
84766             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
84767           }else{
84768             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
84769             if( isRowid ){
84770               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
84771                                 sqlite3VdbeCurrentAddr(v)+2);
84772               VdbeCoverage(v);
84773               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
84774             }else{
84775               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
84776               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
84777               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
84778             }
84779           }
84780         }
84781         sqlite3ReleaseTempReg(pParse, r1);
84782         sqlite3ReleaseTempReg(pParse, r2);
84783       }
84784       if( pKeyInfo ){
84785         sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
84786       }
84787       break;
84788     }
84789 
84790     case TK_EXISTS:
84791     case TK_SELECT:
84792     default: {
84793       /* If this has to be a scalar SELECT.  Generate code to put the
84794       ** value of this select in a memory cell and record the number
84795       ** of the memory cell in iColumn.  If this is an EXISTS, write
84796       ** an integer 0 (not exists) or 1 (exists) into a memory cell
84797       ** and record that memory cell in iColumn.
84798       */
84799       Select *pSel;                         /* SELECT statement to encode */
84800       SelectDest dest;                      /* How to deal with SELECt result */
84801 
84802       testcase( pExpr->op==TK_EXISTS );
84803       testcase( pExpr->op==TK_SELECT );
84804       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
84805 
84806       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
84807       pSel = pExpr->x.pSelect;
84808       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
84809       if( pExpr->op==TK_SELECT ){
84810         dest.eDest = SRT_Mem;
84811         dest.iSdst = dest.iSDParm;
84812         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
84813         VdbeComment((v, "Init subquery result"));
84814       }else{
84815         dest.eDest = SRT_Exists;
84816         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
84817         VdbeComment((v, "Init EXISTS result"));
84818       }
84819       sqlite3ExprDelete(pParse->db, pSel->pLimit);
84820       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
84821                                   &sqlite3IntTokens[1]);
84822       pSel->iLimit = 0;
84823       pSel->selFlags &= ~SF_MultiValue;
84824       if( sqlite3Select(pParse, pSel, &dest) ){
84825         return 0;
84826       }
84827       rReg = dest.iSDParm;
84828       ExprSetVVAProperty(pExpr, EP_NoReduce);
84829       break;
84830     }
84831   }
84832 
84833   if( rHasNullFlag ){
84834     sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
84835   }
84836 
84837   if( jmpIfDynamic>=0 ){
84838     sqlite3VdbeJumpHere(v, jmpIfDynamic);
84839   }
84840   sqlite3ExprCachePop(pParse);
84841 
84842   return rReg;
84843 }
84844 #endif /* SQLITE_OMIT_SUBQUERY */
84845 
84846 #ifndef SQLITE_OMIT_SUBQUERY
84847 /*
84848 ** Generate code for an IN expression.
84849 **
84850 **      x IN (SELECT ...)
84851 **      x IN (value, value, ...)
84852 **
84853 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
84854 ** is an array of zero or more values.  The expression is true if the LHS is
84855 ** contained within the RHS.  The value of the expression is unknown (NULL)
84856 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
84857 ** RHS contains one or more NULL values.
84858 **
84859 ** This routine generates code that jumps to destIfFalse if the LHS is not
84860 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
84861 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
84862 ** within the RHS then fall through.
84863 */
84864 static void sqlite3ExprCodeIN(
84865   Parse *pParse,        /* Parsing and code generating context */
84866   Expr *pExpr,          /* The IN expression */
84867   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
84868   int destIfNull        /* Jump here if the results are unknown due to NULLs */
84869 ){
84870   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
84871   char affinity;        /* Comparison affinity to use */
84872   int eType;            /* Type of the RHS */
84873   int r1;               /* Temporary use register */
84874   Vdbe *v;              /* Statement under construction */
84875 
84876   /* Compute the RHS.   After this step, the table with cursor
84877   ** pExpr->iTable will contains the values that make up the RHS.
84878   */
84879   v = pParse->pVdbe;
84880   assert( v!=0 );       /* OOM detected prior to this routine */
84881   VdbeNoopComment((v, "begin IN expr"));
84882   eType = sqlite3FindInIndex(pParse, pExpr,
84883                              IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
84884                              destIfFalse==destIfNull ? 0 : &rRhsHasNull);
84885 
84886   /* Figure out the affinity to use to create a key from the results
84887   ** of the expression. affinityStr stores a static string suitable for
84888   ** P4 of OP_MakeRecord.
84889   */
84890   affinity = comparisonAffinity(pExpr);
84891 
84892   /* Code the LHS, the <expr> from "<expr> IN (...)".
84893   */
84894   sqlite3ExprCachePush(pParse);
84895   r1 = sqlite3GetTempReg(pParse);
84896   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
84897 
84898   /* If sqlite3FindInIndex() did not find or create an index that is
84899   ** suitable for evaluating the IN operator, then evaluate using a
84900   ** sequence of comparisons.
84901   */
84902   if( eType==IN_INDEX_NOOP ){
84903     ExprList *pList = pExpr->x.pList;
84904     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
84905     int labelOk = sqlite3VdbeMakeLabel(v);
84906     int r2, regToFree;
84907     int regCkNull = 0;
84908     int ii;
84909     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
84910     if( destIfNull!=destIfFalse ){
84911       regCkNull = sqlite3GetTempReg(pParse);
84912       sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
84913     }
84914     for(ii=0; ii<pList->nExpr; ii++){
84915       r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
84916       if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
84917         sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
84918       }
84919       if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
84920         sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
84921                           (void*)pColl, P4_COLLSEQ);
84922         VdbeCoverageIf(v, ii<pList->nExpr-1);
84923         VdbeCoverageIf(v, ii==pList->nExpr-1);
84924         sqlite3VdbeChangeP5(v, affinity);
84925       }else{
84926         assert( destIfNull==destIfFalse );
84927         sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
84928                           (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
84929         sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
84930       }
84931       sqlite3ReleaseTempReg(pParse, regToFree);
84932     }
84933     if( regCkNull ){
84934       sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
84935       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
84936     }
84937     sqlite3VdbeResolveLabel(v, labelOk);
84938     sqlite3ReleaseTempReg(pParse, regCkNull);
84939   }else{
84940 
84941     /* If the LHS is NULL, then the result is either false or NULL depending
84942     ** on whether the RHS is empty or not, respectively.
84943     */
84944     if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
84945       if( destIfNull==destIfFalse ){
84946         /* Shortcut for the common case where the false and NULL outcomes are
84947         ** the same. */
84948         sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
84949       }else{
84950         int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
84951         sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
84952         VdbeCoverage(v);
84953         sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
84954         sqlite3VdbeJumpHere(v, addr1);
84955       }
84956     }
84957 
84958     if( eType==IN_INDEX_ROWID ){
84959       /* In this case, the RHS is the ROWID of table b-tree
84960       */
84961       sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
84962       sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
84963       VdbeCoverage(v);
84964     }else{
84965       /* In this case, the RHS is an index b-tree.
84966       */
84967       sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
84968 
84969       /* If the set membership test fails, then the result of the
84970       ** "x IN (...)" expression must be either 0 or NULL. If the set
84971       ** contains no NULL values, then the result is 0. If the set
84972       ** contains one or more NULL values, then the result of the
84973       ** expression is also NULL.
84974       */
84975       assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
84976       if( rRhsHasNull==0 ){
84977         /* This branch runs if it is known at compile time that the RHS
84978         ** cannot contain NULL values. This happens as the result
84979         ** of a "NOT NULL" constraint in the database schema.
84980         **
84981         ** Also run this branch if NULL is equivalent to FALSE
84982         ** for this particular IN operator.
84983         */
84984         sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
84985         VdbeCoverage(v);
84986       }else{
84987         /* In this branch, the RHS of the IN might contain a NULL and
84988         ** the presence of a NULL on the RHS makes a difference in the
84989         ** outcome.
84990         */
84991         int j1;
84992 
84993         /* First check to see if the LHS is contained in the RHS.  If so,
84994         ** then the answer is TRUE the presence of NULLs in the RHS does
84995         ** not matter.  If the LHS is not contained in the RHS, then the
84996         ** answer is NULL if the RHS contains NULLs and the answer is
84997         ** FALSE if the RHS is NULL-free.
84998         */
84999         j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
85000         VdbeCoverage(v);
85001         sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
85002         VdbeCoverage(v);
85003         sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
85004         sqlite3VdbeJumpHere(v, j1);
85005       }
85006     }
85007   }
85008   sqlite3ReleaseTempReg(pParse, r1);
85009   sqlite3ExprCachePop(pParse);
85010   VdbeComment((v, "end IN expr"));
85011 }
85012 #endif /* SQLITE_OMIT_SUBQUERY */
85013 
85014 /*
85015 ** Duplicate an 8-byte value
85016 */
85017 static char *dup8bytes(Vdbe *v, const char *in){
85018   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
85019   if( out ){
85020     memcpy(out, in, 8);
85021   }
85022   return out;
85023 }
85024 
85025 #ifndef SQLITE_OMIT_FLOATING_POINT
85026 /*
85027 ** Generate an instruction that will put the floating point
85028 ** value described by z[0..n-1] into register iMem.
85029 **
85030 ** The z[] string will probably not be zero-terminated.  But the
85031 ** z[n] character is guaranteed to be something that does not look
85032 ** like the continuation of the number.
85033 */
85034 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
85035   if( ALWAYS(z!=0) ){
85036     double value;
85037     char *zV;
85038     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
85039     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
85040     if( negateFlag ) value = -value;
85041     zV = dup8bytes(v, (char*)&value);
85042     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
85043   }
85044 }
85045 #endif
85046 
85047 
85048 /*
85049 ** Generate an instruction that will put the integer describe by
85050 ** text z[0..n-1] into register iMem.
85051 **
85052 ** Expr.u.zToken is always UTF8 and zero-terminated.
85053 */
85054 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
85055   Vdbe *v = pParse->pVdbe;
85056   if( pExpr->flags & EP_IntValue ){
85057     int i = pExpr->u.iValue;
85058     assert( i>=0 );
85059     if( negFlag ) i = -i;
85060     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
85061   }else{
85062     int c;
85063     i64 value;
85064     const char *z = pExpr->u.zToken;
85065     assert( z!=0 );
85066     c = sqlite3DecOrHexToI64(z, &value);
85067     if( c==0 || (c==2 && negFlag) ){
85068       char *zV;
85069       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
85070       zV = dup8bytes(v, (char*)&value);
85071       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
85072     }else{
85073 #ifdef SQLITE_OMIT_FLOATING_POINT
85074       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
85075 #else
85076 #ifndef SQLITE_OMIT_HEX_INTEGER
85077       if( sqlite3_strnicmp(z,"0x",2)==0 ){
85078         sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
85079       }else
85080 #endif
85081       {
85082         codeReal(v, z, negFlag, iMem);
85083       }
85084 #endif
85085     }
85086   }
85087 }
85088 
85089 /*
85090 ** Clear a cache entry.
85091 */
85092 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
85093   if( p->tempReg ){
85094     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
85095       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
85096     }
85097     p->tempReg = 0;
85098   }
85099 }
85100 
85101 
85102 /*
85103 ** Record in the column cache that a particular column from a
85104 ** particular table is stored in a particular register.
85105 */
85106 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
85107   int i;
85108   int minLru;
85109   int idxLru;
85110   struct yColCache *p;
85111 
85112   /* Unless an error has occurred, register numbers are always positive. */
85113   assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
85114   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
85115 
85116   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
85117   ** for testing only - to verify that SQLite always gets the same answer
85118   ** with and without the column cache.
85119   */
85120   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
85121 
85122   /* First replace any existing entry.
85123   **
85124   ** Actually, the way the column cache is currently used, we are guaranteed
85125   ** that the object will never already be in cache.  Verify this guarantee.
85126   */
85127 #ifndef NDEBUG
85128   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
85129     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
85130   }
85131 #endif
85132 
85133   /* Find an empty slot and replace it */
85134   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
85135     if( p->iReg==0 ){
85136       p->iLevel = pParse->iCacheLevel;
85137       p->iTable = iTab;
85138       p->iColumn = iCol;
85139       p->iReg = iReg;
85140       p->tempReg = 0;
85141       p->lru = pParse->iCacheCnt++;
85142       return;
85143     }
85144   }
85145 
85146   /* Replace the last recently used */
85147   minLru = 0x7fffffff;
85148   idxLru = -1;
85149   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
85150     if( p->lru<minLru ){
85151       idxLru = i;
85152       minLru = p->lru;
85153     }
85154   }
85155   if( ALWAYS(idxLru>=0) ){
85156     p = &pParse->aColCache[idxLru];
85157     p->iLevel = pParse->iCacheLevel;
85158     p->iTable = iTab;
85159     p->iColumn = iCol;
85160     p->iReg = iReg;
85161     p->tempReg = 0;
85162     p->lru = pParse->iCacheCnt++;
85163     return;
85164   }
85165 }
85166 
85167 /*
85168 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
85169 ** Purge the range of registers from the column cache.
85170 */
85171 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
85172   int i;
85173   int iLast = iReg + nReg - 1;
85174   struct yColCache *p;
85175   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
85176     int r = p->iReg;
85177     if( r>=iReg && r<=iLast ){
85178       cacheEntryClear(pParse, p);
85179       p->iReg = 0;
85180     }
85181   }
85182 }
85183 
85184 /*
85185 ** Remember the current column cache context.  Any new entries added
85186 ** added to the column cache after this call are removed when the
85187 ** corresponding pop occurs.
85188 */
85189 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
85190   pParse->iCacheLevel++;
85191 #ifdef SQLITE_DEBUG
85192   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
85193     printf("PUSH to %d\n", pParse->iCacheLevel);
85194   }
85195 #endif
85196 }
85197 
85198 /*
85199 ** Remove from the column cache any entries that were added since the
85200 ** the previous sqlite3ExprCachePush operation.  In other words, restore
85201 ** the cache to the state it was in prior the most recent Push.
85202 */
85203 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
85204   int i;
85205   struct yColCache *p;
85206   assert( pParse->iCacheLevel>=1 );
85207   pParse->iCacheLevel--;
85208 #ifdef SQLITE_DEBUG
85209   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
85210     printf("POP  to %d\n", pParse->iCacheLevel);
85211   }
85212 #endif
85213   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
85214     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
85215       cacheEntryClear(pParse, p);
85216       p->iReg = 0;
85217     }
85218   }
85219 }
85220 
85221 /*
85222 ** When a cached column is reused, make sure that its register is
85223 ** no longer available as a temp register.  ticket #3879:  that same
85224 ** register might be in the cache in multiple places, so be sure to
85225 ** get them all.
85226 */
85227 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
85228   int i;
85229   struct yColCache *p;
85230   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
85231     if( p->iReg==iReg ){
85232       p->tempReg = 0;
85233     }
85234   }
85235 }
85236 
85237 /*
85238 ** Generate code to extract the value of the iCol-th column of a table.
85239 */
85240 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
85241   Vdbe *v,        /* The VDBE under construction */
85242   Table *pTab,    /* The table containing the value */
85243   int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
85244   int iCol,       /* Index of the column to extract */
85245   int regOut      /* Extract the value into this register */
85246 ){
85247   if( iCol<0 || iCol==pTab->iPKey ){
85248     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
85249   }else{
85250     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
85251     int x = iCol;
85252     if( !HasRowid(pTab) ){
85253       x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
85254     }
85255     sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
85256   }
85257   if( iCol>=0 ){
85258     sqlite3ColumnDefault(v, pTab, iCol, regOut);
85259   }
85260 }
85261 
85262 /*
85263 ** Generate code that will extract the iColumn-th column from
85264 ** table pTab and store the column value in a register.  An effort
85265 ** is made to store the column value in register iReg, but this is
85266 ** not guaranteed.  The location of the column value is returned.
85267 **
85268 ** There must be an open cursor to pTab in iTable when this routine
85269 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
85270 */
85271 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
85272   Parse *pParse,   /* Parsing and code generating context */
85273   Table *pTab,     /* Description of the table we are reading from */
85274   int iColumn,     /* Index of the table column */
85275   int iTable,      /* The cursor pointing to the table */
85276   int iReg,        /* Store results here */
85277   u8 p5            /* P5 value for OP_Column */
85278 ){
85279   Vdbe *v = pParse->pVdbe;
85280   int i;
85281   struct yColCache *p;
85282 
85283   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
85284     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
85285       p->lru = pParse->iCacheCnt++;
85286       sqlite3ExprCachePinRegister(pParse, p->iReg);
85287       return p->iReg;
85288     }
85289   }
85290   assert( v!=0 );
85291   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
85292   if( p5 ){
85293     sqlite3VdbeChangeP5(v, p5);
85294   }else{
85295     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
85296   }
85297   return iReg;
85298 }
85299 
85300 /*
85301 ** Clear all column cache entries.
85302 */
85303 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
85304   int i;
85305   struct yColCache *p;
85306 
85307 #if SQLITE_DEBUG
85308   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
85309     printf("CLEAR\n");
85310   }
85311 #endif
85312   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
85313     if( p->iReg ){
85314       cacheEntryClear(pParse, p);
85315       p->iReg = 0;
85316     }
85317   }
85318 }
85319 
85320 /*
85321 ** Record the fact that an affinity change has occurred on iCount
85322 ** registers starting with iStart.
85323 */
85324 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
85325   sqlite3ExprCacheRemove(pParse, iStart, iCount);
85326 }
85327 
85328 /*
85329 ** Generate code to move content from registers iFrom...iFrom+nReg-1
85330 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
85331 */
85332 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
85333   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
85334   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
85335   sqlite3ExprCacheRemove(pParse, iFrom, nReg);
85336 }
85337 
85338 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
85339 /*
85340 ** Return true if any register in the range iFrom..iTo (inclusive)
85341 ** is used as part of the column cache.
85342 **
85343 ** This routine is used within assert() and testcase() macros only
85344 ** and does not appear in a normal build.
85345 */
85346 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
85347   int i;
85348   struct yColCache *p;
85349   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
85350     int r = p->iReg;
85351     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
85352   }
85353   return 0;
85354 }
85355 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
85356 
85357 /*
85358 ** Convert an expression node to a TK_REGISTER
85359 */
85360 static void exprToRegister(Expr *p, int iReg){
85361   p->op2 = p->op;
85362   p->op = TK_REGISTER;
85363   p->iTable = iReg;
85364   ExprClearProperty(p, EP_Skip);
85365 }
85366 
85367 /*
85368 ** Generate code into the current Vdbe to evaluate the given
85369 ** expression.  Attempt to store the results in register "target".
85370 ** Return the register where results are stored.
85371 **
85372 ** With this routine, there is no guarantee that results will
85373 ** be stored in target.  The result might be stored in some other
85374 ** register if it is convenient to do so.  The calling function
85375 ** must check the return code and move the results to the desired
85376 ** register.
85377 */
85378 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
85379   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
85380   int op;                   /* The opcode being coded */
85381   int inReg = target;       /* Results stored in register inReg */
85382   int regFree1 = 0;         /* If non-zero free this temporary register */
85383   int regFree2 = 0;         /* If non-zero free this temporary register */
85384   int r1, r2, r3, r4;       /* Various register numbers */
85385   sqlite3 *db = pParse->db; /* The database connection */
85386   Expr tempX;               /* Temporary expression node */
85387 
85388   assert( target>0 && target<=pParse->nMem );
85389   if( v==0 ){
85390     assert( pParse->db->mallocFailed );
85391     return 0;
85392   }
85393 
85394   if( pExpr==0 ){
85395     op = TK_NULL;
85396   }else{
85397     op = pExpr->op;
85398   }
85399   switch( op ){
85400     case TK_AGG_COLUMN: {
85401       AggInfo *pAggInfo = pExpr->pAggInfo;
85402       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
85403       if( !pAggInfo->directMode ){
85404         assert( pCol->iMem>0 );
85405         inReg = pCol->iMem;
85406         break;
85407       }else if( pAggInfo->useSortingIdx ){
85408         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
85409                               pCol->iSorterColumn, target);
85410         break;
85411       }
85412       /* Otherwise, fall thru into the TK_COLUMN case */
85413     }
85414     case TK_COLUMN: {
85415       int iTab = pExpr->iTable;
85416       if( iTab<0 ){
85417         if( pParse->ckBase>0 ){
85418           /* Generating CHECK constraints or inserting into partial index */
85419           inReg = pExpr->iColumn + pParse->ckBase;
85420           break;
85421         }else{
85422           /* Deleting from a partial index */
85423           iTab = pParse->iPartIdxTab;
85424         }
85425       }
85426       inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
85427                                pExpr->iColumn, iTab, target,
85428                                pExpr->op2);
85429       break;
85430     }
85431     case TK_INTEGER: {
85432       codeInteger(pParse, pExpr, 0, target);
85433       break;
85434     }
85435 #ifndef SQLITE_OMIT_FLOATING_POINT
85436     case TK_FLOAT: {
85437       assert( !ExprHasProperty(pExpr, EP_IntValue) );
85438       codeReal(v, pExpr->u.zToken, 0, target);
85439       break;
85440     }
85441 #endif
85442     case TK_STRING: {
85443       assert( !ExprHasProperty(pExpr, EP_IntValue) );
85444       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
85445       break;
85446     }
85447     case TK_NULL: {
85448       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
85449       break;
85450     }
85451 #ifndef SQLITE_OMIT_BLOB_LITERAL
85452     case TK_BLOB: {
85453       int n;
85454       const char *z;
85455       char *zBlob;
85456       assert( !ExprHasProperty(pExpr, EP_IntValue) );
85457       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
85458       assert( pExpr->u.zToken[1]=='\'' );
85459       z = &pExpr->u.zToken[2];
85460       n = sqlite3Strlen30(z) - 1;
85461       assert( z[n]=='\'' );
85462       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
85463       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
85464       break;
85465     }
85466 #endif
85467     case TK_VARIABLE: {
85468       assert( !ExprHasProperty(pExpr, EP_IntValue) );
85469       assert( pExpr->u.zToken!=0 );
85470       assert( pExpr->u.zToken[0]!=0 );
85471       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
85472       if( pExpr->u.zToken[1]!=0 ){
85473         assert( pExpr->u.zToken[0]=='?'
85474              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
85475         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
85476       }
85477       break;
85478     }
85479     case TK_REGISTER: {
85480       inReg = pExpr->iTable;
85481       break;
85482     }
85483     case TK_AS: {
85484       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
85485       break;
85486     }
85487 #ifndef SQLITE_OMIT_CAST
85488     case TK_CAST: {
85489       /* Expressions of the form:   CAST(pLeft AS token) */
85490       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
85491       if( inReg!=target ){
85492         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
85493         inReg = target;
85494       }
85495       sqlite3VdbeAddOp2(v, OP_Cast, target,
85496                         sqlite3AffinityType(pExpr->u.zToken, 0));
85497       testcase( usedAsColumnCache(pParse, inReg, inReg) );
85498       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
85499       break;
85500     }
85501 #endif /* SQLITE_OMIT_CAST */
85502     case TK_LT:
85503     case TK_LE:
85504     case TK_GT:
85505     case TK_GE:
85506     case TK_NE:
85507     case TK_EQ: {
85508       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
85509       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
85510       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
85511                   r1, r2, inReg, SQLITE_STOREP2);
85512       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
85513       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
85514       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
85515       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
85516       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
85517       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
85518       testcase( regFree1==0 );
85519       testcase( regFree2==0 );
85520       break;
85521     }
85522     case TK_IS:
85523     case TK_ISNOT: {
85524       testcase( op==TK_IS );
85525       testcase( op==TK_ISNOT );
85526       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
85527       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
85528       op = (op==TK_IS) ? TK_EQ : TK_NE;
85529       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
85530                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
85531       VdbeCoverageIf(v, op==TK_EQ);
85532       VdbeCoverageIf(v, op==TK_NE);
85533       testcase( regFree1==0 );
85534       testcase( regFree2==0 );
85535       break;
85536     }
85537     case TK_AND:
85538     case TK_OR:
85539     case TK_PLUS:
85540     case TK_STAR:
85541     case TK_MINUS:
85542     case TK_REM:
85543     case TK_BITAND:
85544     case TK_BITOR:
85545     case TK_SLASH:
85546     case TK_LSHIFT:
85547     case TK_RSHIFT:
85548     case TK_CONCAT: {
85549       assert( TK_AND==OP_And );            testcase( op==TK_AND );
85550       assert( TK_OR==OP_Or );              testcase( op==TK_OR );
85551       assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
85552       assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
85553       assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
85554       assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
85555       assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
85556       assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
85557       assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
85558       assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
85559       assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
85560       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
85561       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
85562       sqlite3VdbeAddOp3(v, op, r2, r1, target);
85563       testcase( regFree1==0 );
85564       testcase( regFree2==0 );
85565       break;
85566     }
85567     case TK_UMINUS: {
85568       Expr *pLeft = pExpr->pLeft;
85569       assert( pLeft );
85570       if( pLeft->op==TK_INTEGER ){
85571         codeInteger(pParse, pLeft, 1, target);
85572 #ifndef SQLITE_OMIT_FLOATING_POINT
85573       }else if( pLeft->op==TK_FLOAT ){
85574         assert( !ExprHasProperty(pExpr, EP_IntValue) );
85575         codeReal(v, pLeft->u.zToken, 1, target);
85576 #endif
85577       }else{
85578         tempX.op = TK_INTEGER;
85579         tempX.flags = EP_IntValue|EP_TokenOnly;
85580         tempX.u.iValue = 0;
85581         r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
85582         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
85583         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
85584         testcase( regFree2==0 );
85585       }
85586       inReg = target;
85587       break;
85588     }
85589     case TK_BITNOT:
85590     case TK_NOT: {
85591       assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
85592       assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
85593       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
85594       testcase( regFree1==0 );
85595       inReg = target;
85596       sqlite3VdbeAddOp2(v, op, r1, inReg);
85597       break;
85598     }
85599     case TK_ISNULL:
85600     case TK_NOTNULL: {
85601       int addr;
85602       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
85603       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
85604       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
85605       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
85606       testcase( regFree1==0 );
85607       addr = sqlite3VdbeAddOp1(v, op, r1);
85608       VdbeCoverageIf(v, op==TK_ISNULL);
85609       VdbeCoverageIf(v, op==TK_NOTNULL);
85610       sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
85611       sqlite3VdbeJumpHere(v, addr);
85612       break;
85613     }
85614     case TK_AGG_FUNCTION: {
85615       AggInfo *pInfo = pExpr->pAggInfo;
85616       if( pInfo==0 ){
85617         assert( !ExprHasProperty(pExpr, EP_IntValue) );
85618         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
85619       }else{
85620         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
85621       }
85622       break;
85623     }
85624     case TK_FUNCTION: {
85625       ExprList *pFarg;       /* List of function arguments */
85626       int nFarg;             /* Number of function arguments */
85627       FuncDef *pDef;         /* The function definition object */
85628       int nId;               /* Length of the function name in bytes */
85629       const char *zId;       /* The function name */
85630       u32 constMask = 0;     /* Mask of function arguments that are constant */
85631       int i;                 /* Loop counter */
85632       u8 enc = ENC(db);      /* The text encoding used by this database */
85633       CollSeq *pColl = 0;    /* A collating sequence */
85634 
85635       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
85636       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
85637         pFarg = 0;
85638       }else{
85639         pFarg = pExpr->x.pList;
85640       }
85641       nFarg = pFarg ? pFarg->nExpr : 0;
85642       assert( !ExprHasProperty(pExpr, EP_IntValue) );
85643       zId = pExpr->u.zToken;
85644       nId = sqlite3Strlen30(zId);
85645       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
85646       if( pDef==0 || pDef->xFunc==0 ){
85647         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
85648         break;
85649       }
85650 
85651       /* Attempt a direct implementation of the built-in COALESCE() and
85652       ** IFNULL() functions.  This avoids unnecessary evaluation of
85653       ** arguments past the first non-NULL argument.
85654       */
85655       if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
85656         int endCoalesce = sqlite3VdbeMakeLabel(v);
85657         assert( nFarg>=2 );
85658         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
85659         for(i=1; i<nFarg; i++){
85660           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
85661           VdbeCoverage(v);
85662           sqlite3ExprCacheRemove(pParse, target, 1);
85663           sqlite3ExprCachePush(pParse);
85664           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
85665           sqlite3ExprCachePop(pParse);
85666         }
85667         sqlite3VdbeResolveLabel(v, endCoalesce);
85668         break;
85669       }
85670 
85671       /* The UNLIKELY() function is a no-op.  The result is the value
85672       ** of the first argument.
85673       */
85674       if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
85675         assert( nFarg>=1 );
85676         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
85677         break;
85678       }
85679 
85680       for(i=0; i<nFarg; i++){
85681         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
85682           testcase( i==31 );
85683           constMask |= MASKBIT32(i);
85684         }
85685         if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
85686           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
85687         }
85688       }
85689       if( pFarg ){
85690         if( constMask ){
85691           r1 = pParse->nMem+1;
85692           pParse->nMem += nFarg;
85693         }else{
85694           r1 = sqlite3GetTempRange(pParse, nFarg);
85695         }
85696 
85697         /* For length() and typeof() functions with a column argument,
85698         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
85699         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
85700         ** loading.
85701         */
85702         if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
85703           u8 exprOp;
85704           assert( nFarg==1 );
85705           assert( pFarg->a[0].pExpr!=0 );
85706           exprOp = pFarg->a[0].pExpr->op;
85707           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
85708             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
85709             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
85710             testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
85711             pFarg->a[0].pExpr->op2 =
85712                   pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
85713           }
85714         }
85715 
85716         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
85717         sqlite3ExprCodeExprList(pParse, pFarg, r1,
85718                                 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
85719         sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
85720       }else{
85721         r1 = 0;
85722       }
85723 #ifndef SQLITE_OMIT_VIRTUALTABLE
85724       /* Possibly overload the function if the first argument is
85725       ** a virtual table column.
85726       **
85727       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
85728       ** second argument, not the first, as the argument to test to
85729       ** see if it is a column in a virtual table.  This is done because
85730       ** the left operand of infix functions (the operand we want to
85731       ** control overloading) ends up as the second argument to the
85732       ** function.  The expression "A glob B" is equivalent to
85733       ** "glob(B,A).  We want to use the A in "A glob B" to test
85734       ** for function overloading.  But we use the B term in "glob(B,A)".
85735       */
85736       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
85737         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
85738       }else if( nFarg>0 ){
85739         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
85740       }
85741 #endif
85742       if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
85743         if( !pColl ) pColl = db->pDfltColl;
85744         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
85745       }
85746       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
85747                         (char*)pDef, P4_FUNCDEF);
85748       sqlite3VdbeChangeP5(v, (u8)nFarg);
85749       if( nFarg && constMask==0 ){
85750         sqlite3ReleaseTempRange(pParse, r1, nFarg);
85751       }
85752       break;
85753     }
85754 #ifndef SQLITE_OMIT_SUBQUERY
85755     case TK_EXISTS:
85756     case TK_SELECT: {
85757       testcase( op==TK_EXISTS );
85758       testcase( op==TK_SELECT );
85759       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
85760       break;
85761     }
85762     case TK_IN: {
85763       int destIfFalse = sqlite3VdbeMakeLabel(v);
85764       int destIfNull = sqlite3VdbeMakeLabel(v);
85765       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
85766       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
85767       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
85768       sqlite3VdbeResolveLabel(v, destIfFalse);
85769       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
85770       sqlite3VdbeResolveLabel(v, destIfNull);
85771       break;
85772     }
85773 #endif /* SQLITE_OMIT_SUBQUERY */
85774 
85775 
85776     /*
85777     **    x BETWEEN y AND z
85778     **
85779     ** This is equivalent to
85780     **
85781     **    x>=y AND x<=z
85782     **
85783     ** X is stored in pExpr->pLeft.
85784     ** Y is stored in pExpr->pList->a[0].pExpr.
85785     ** Z is stored in pExpr->pList->a[1].pExpr.
85786     */
85787     case TK_BETWEEN: {
85788       Expr *pLeft = pExpr->pLeft;
85789       struct ExprList_item *pLItem = pExpr->x.pList->a;
85790       Expr *pRight = pLItem->pExpr;
85791 
85792       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
85793       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
85794       testcase( regFree1==0 );
85795       testcase( regFree2==0 );
85796       r3 = sqlite3GetTempReg(pParse);
85797       r4 = sqlite3GetTempReg(pParse);
85798       codeCompare(pParse, pLeft, pRight, OP_Ge,
85799                   r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
85800       pLItem++;
85801       pRight = pLItem->pExpr;
85802       sqlite3ReleaseTempReg(pParse, regFree2);
85803       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
85804       testcase( regFree2==0 );
85805       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
85806       VdbeCoverage(v);
85807       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
85808       sqlite3ReleaseTempReg(pParse, r3);
85809       sqlite3ReleaseTempReg(pParse, r4);
85810       break;
85811     }
85812     case TK_COLLATE:
85813     case TK_UPLUS: {
85814       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
85815       break;
85816     }
85817 
85818     case TK_TRIGGER: {
85819       /* If the opcode is TK_TRIGGER, then the expression is a reference
85820       ** to a column in the new.* or old.* pseudo-tables available to
85821       ** trigger programs. In this case Expr.iTable is set to 1 for the
85822       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
85823       ** is set to the column of the pseudo-table to read, or to -1 to
85824       ** read the rowid field.
85825       **
85826       ** The expression is implemented using an OP_Param opcode. The p1
85827       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
85828       ** to reference another column of the old.* pseudo-table, where
85829       ** i is the index of the column. For a new.rowid reference, p1 is
85830       ** set to (n+1), where n is the number of columns in each pseudo-table.
85831       ** For a reference to any other column in the new.* pseudo-table, p1
85832       ** is set to (n+2+i), where n and i are as defined previously. For
85833       ** example, if the table on which triggers are being fired is
85834       ** declared as:
85835       **
85836       **   CREATE TABLE t1(a, b);
85837       **
85838       ** Then p1 is interpreted as follows:
85839       **
85840       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
85841       **   p1==1   ->    old.a         p1==4   ->    new.a
85842       **   p1==2   ->    old.b         p1==5   ->    new.b
85843       */
85844       Table *pTab = pExpr->pTab;
85845       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
85846 
85847       assert( pExpr->iTable==0 || pExpr->iTable==1 );
85848       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
85849       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
85850       assert( p1>=0 && p1<(pTab->nCol*2+2) );
85851 
85852       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
85853       VdbeComment((v, "%s.%s -> $%d",
85854         (pExpr->iTable ? "new" : "old"),
85855         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
85856         target
85857       ));
85858 
85859 #ifndef SQLITE_OMIT_FLOATING_POINT
85860       /* If the column has REAL affinity, it may currently be stored as an
85861       ** integer. Use OP_RealAffinity to make sure it is really real.
85862       **
85863       ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
85864       ** floating point when extracting it from the record.  */
85865       if( pExpr->iColumn>=0
85866        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
85867       ){
85868         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
85869       }
85870 #endif
85871       break;
85872     }
85873 
85874 
85875     /*
85876     ** Form A:
85877     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
85878     **
85879     ** Form B:
85880     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
85881     **
85882     ** Form A is can be transformed into the equivalent form B as follows:
85883     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
85884     **        WHEN x=eN THEN rN ELSE y END
85885     **
85886     ** X (if it exists) is in pExpr->pLeft.
85887     ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
85888     ** odd.  The Y is also optional.  If the number of elements in x.pList
85889     ** is even, then Y is omitted and the "otherwise" result is NULL.
85890     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
85891     **
85892     ** The result of the expression is the Ri for the first matching Ei,
85893     ** or if there is no matching Ei, the ELSE term Y, or if there is
85894     ** no ELSE term, NULL.
85895     */
85896     default: assert( op==TK_CASE ); {
85897       int endLabel;                     /* GOTO label for end of CASE stmt */
85898       int nextCase;                     /* GOTO label for next WHEN clause */
85899       int nExpr;                        /* 2x number of WHEN terms */
85900       int i;                            /* Loop counter */
85901       ExprList *pEList;                 /* List of WHEN terms */
85902       struct ExprList_item *aListelem;  /* Array of WHEN terms */
85903       Expr opCompare;                   /* The X==Ei expression */
85904       Expr *pX;                         /* The X expression */
85905       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
85906       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
85907 
85908       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
85909       assert(pExpr->x.pList->nExpr > 0);
85910       pEList = pExpr->x.pList;
85911       aListelem = pEList->a;
85912       nExpr = pEList->nExpr;
85913       endLabel = sqlite3VdbeMakeLabel(v);
85914       if( (pX = pExpr->pLeft)!=0 ){
85915         tempX = *pX;
85916         testcase( pX->op==TK_COLUMN );
85917         exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
85918         testcase( regFree1==0 );
85919         opCompare.op = TK_EQ;
85920         opCompare.pLeft = &tempX;
85921         pTest = &opCompare;
85922         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
85923         ** The value in regFree1 might get SCopy-ed into the file result.
85924         ** So make sure that the regFree1 register is not reused for other
85925         ** purposes and possibly overwritten.  */
85926         regFree1 = 0;
85927       }
85928       for(i=0; i<nExpr-1; i=i+2){
85929         sqlite3ExprCachePush(pParse);
85930         if( pX ){
85931           assert( pTest!=0 );
85932           opCompare.pRight = aListelem[i].pExpr;
85933         }else{
85934           pTest = aListelem[i].pExpr;
85935         }
85936         nextCase = sqlite3VdbeMakeLabel(v);
85937         testcase( pTest->op==TK_COLUMN );
85938         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
85939         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
85940         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
85941         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
85942         sqlite3ExprCachePop(pParse);
85943         sqlite3VdbeResolveLabel(v, nextCase);
85944       }
85945       if( (nExpr&1)!=0 ){
85946         sqlite3ExprCachePush(pParse);
85947         sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
85948         sqlite3ExprCachePop(pParse);
85949       }else{
85950         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
85951       }
85952       assert( db->mallocFailed || pParse->nErr>0
85953            || pParse->iCacheLevel==iCacheLevel );
85954       sqlite3VdbeResolveLabel(v, endLabel);
85955       break;
85956     }
85957 #ifndef SQLITE_OMIT_TRIGGER
85958     case TK_RAISE: {
85959       assert( pExpr->affinity==OE_Rollback
85960            || pExpr->affinity==OE_Abort
85961            || pExpr->affinity==OE_Fail
85962            || pExpr->affinity==OE_Ignore
85963       );
85964       if( !pParse->pTriggerTab ){
85965         sqlite3ErrorMsg(pParse,
85966                        "RAISE() may only be used within a trigger-program");
85967         return 0;
85968       }
85969       if( pExpr->affinity==OE_Abort ){
85970         sqlite3MayAbort(pParse);
85971       }
85972       assert( !ExprHasProperty(pExpr, EP_IntValue) );
85973       if( pExpr->affinity==OE_Ignore ){
85974         sqlite3VdbeAddOp4(
85975             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
85976         VdbeCoverage(v);
85977       }else{
85978         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
85979                               pExpr->affinity, pExpr->u.zToken, 0, 0);
85980       }
85981 
85982       break;
85983     }
85984 #endif
85985   }
85986   sqlite3ReleaseTempReg(pParse, regFree1);
85987   sqlite3ReleaseTempReg(pParse, regFree2);
85988   return inReg;
85989 }
85990 
85991 /*
85992 ** Factor out the code of the given expression to initialization time.
85993 */
85994 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
85995   Parse *pParse,    /* Parsing context */
85996   Expr *pExpr,      /* The expression to code when the VDBE initializes */
85997   int regDest,      /* Store the value in this register */
85998   u8 reusable       /* True if this expression is reusable */
85999 ){
86000   ExprList *p;
86001   assert( ConstFactorOk(pParse) );
86002   p = pParse->pConstExpr;
86003   pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
86004   p = sqlite3ExprListAppend(pParse, p, pExpr);
86005   if( p ){
86006      struct ExprList_item *pItem = &p->a[p->nExpr-1];
86007      pItem->u.iConstExprReg = regDest;
86008      pItem->reusable = reusable;
86009   }
86010   pParse->pConstExpr = p;
86011 }
86012 
86013 /*
86014 ** Generate code to evaluate an expression and store the results
86015 ** into a register.  Return the register number where the results
86016 ** are stored.
86017 **
86018 ** If the register is a temporary register that can be deallocated,
86019 ** then write its number into *pReg.  If the result register is not
86020 ** a temporary, then set *pReg to zero.
86021 **
86022 ** If pExpr is a constant, then this routine might generate this
86023 ** code to fill the register in the initialization section of the
86024 ** VDBE program, in order to factor it out of the evaluation loop.
86025 */
86026 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
86027   int r2;
86028   pExpr = sqlite3ExprSkipCollate(pExpr);
86029   if( ConstFactorOk(pParse)
86030    && pExpr->op!=TK_REGISTER
86031    && sqlite3ExprIsConstantNotJoin(pExpr)
86032   ){
86033     ExprList *p = pParse->pConstExpr;
86034     int i;
86035     *pReg  = 0;
86036     if( p ){
86037       struct ExprList_item *pItem;
86038       for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
86039         if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
86040           return pItem->u.iConstExprReg;
86041         }
86042       }
86043     }
86044     r2 = ++pParse->nMem;
86045     sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
86046   }else{
86047     int r1 = sqlite3GetTempReg(pParse);
86048     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
86049     if( r2==r1 ){
86050       *pReg = r1;
86051     }else{
86052       sqlite3ReleaseTempReg(pParse, r1);
86053       *pReg = 0;
86054     }
86055   }
86056   return r2;
86057 }
86058 
86059 /*
86060 ** Generate code that will evaluate expression pExpr and store the
86061 ** results in register target.  The results are guaranteed to appear
86062 ** in register target.
86063 */
86064 SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
86065   int inReg;
86066 
86067   assert( target>0 && target<=pParse->nMem );
86068   if( pExpr && pExpr->op==TK_REGISTER ){
86069     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
86070   }else{
86071     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
86072     assert( pParse->pVdbe || pParse->db->mallocFailed );
86073     if( inReg!=target && pParse->pVdbe ){
86074       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
86075     }
86076   }
86077 }
86078 
86079 /*
86080 ** Generate code that will evaluate expression pExpr and store the
86081 ** results in register target.  The results are guaranteed to appear
86082 ** in register target.  If the expression is constant, then this routine
86083 ** might choose to code the expression at initialization time.
86084 */
86085 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
86086   if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
86087     sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
86088   }else{
86089     sqlite3ExprCode(pParse, pExpr, target);
86090   }
86091 }
86092 
86093 /*
86094 ** Generate code that evaluates the given expression and puts the result
86095 ** in register target.
86096 **
86097 ** Also make a copy of the expression results into another "cache" register
86098 ** and modify the expression so that the next time it is evaluated,
86099 ** the result is a copy of the cache register.
86100 **
86101 ** This routine is used for expressions that are used multiple
86102 ** times.  They are evaluated once and the results of the expression
86103 ** are reused.
86104 */
86105 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
86106   Vdbe *v = pParse->pVdbe;
86107   int iMem;
86108 
86109   assert( target>0 );
86110   assert( pExpr->op!=TK_REGISTER );
86111   sqlite3ExprCode(pParse, pExpr, target);
86112   iMem = ++pParse->nMem;
86113   sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
86114   exprToRegister(pExpr, iMem);
86115 }
86116 
86117 #ifdef SQLITE_DEBUG
86118 /*
86119 ** Generate a human-readable explanation of an expression tree.
86120 */
86121 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
86122   const char *zBinOp = 0;   /* Binary operator */
86123   const char *zUniOp = 0;   /* Unary operator */
86124   pView = sqlite3TreeViewPush(pView, moreToFollow);
86125   if( pExpr==0 ){
86126     sqlite3TreeViewLine(pView, "nil");
86127     sqlite3TreeViewPop(pView);
86128     return;
86129   }
86130   switch( pExpr->op ){
86131     case TK_AGG_COLUMN: {
86132       sqlite3TreeViewLine(pView, "AGG{%d:%d}",
86133             pExpr->iTable, pExpr->iColumn);
86134       break;
86135     }
86136     case TK_COLUMN: {
86137       if( pExpr->iTable<0 ){
86138         /* This only happens when coding check constraints */
86139         sqlite3TreeViewLine(pView, "COLUMN(%d)", pExpr->iColumn);
86140       }else{
86141         sqlite3TreeViewLine(pView, "{%d:%d}",
86142                              pExpr->iTable, pExpr->iColumn);
86143       }
86144       break;
86145     }
86146     case TK_INTEGER: {
86147       if( pExpr->flags & EP_IntValue ){
86148         sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
86149       }else{
86150         sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
86151       }
86152       break;
86153     }
86154 #ifndef SQLITE_OMIT_FLOATING_POINT
86155     case TK_FLOAT: {
86156       sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
86157       break;
86158     }
86159 #endif
86160     case TK_STRING: {
86161       sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
86162       break;
86163     }
86164     case TK_NULL: {
86165       sqlite3TreeViewLine(pView,"NULL");
86166       break;
86167     }
86168 #ifndef SQLITE_OMIT_BLOB_LITERAL
86169     case TK_BLOB: {
86170       sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
86171       break;
86172     }
86173 #endif
86174     case TK_VARIABLE: {
86175       sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
86176                           pExpr->u.zToken, pExpr->iColumn);
86177       break;
86178     }
86179     case TK_REGISTER: {
86180       sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
86181       break;
86182     }
86183     case TK_AS: {
86184       sqlite3TreeViewLine(pView,"AS %Q", pExpr->u.zToken);
86185       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
86186       break;
86187     }
86188     case TK_ID: {
86189       sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
86190       break;
86191     }
86192 #ifndef SQLITE_OMIT_CAST
86193     case TK_CAST: {
86194       /* Expressions of the form:   CAST(pLeft AS token) */
86195       sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
86196       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
86197       break;
86198     }
86199 #endif /* SQLITE_OMIT_CAST */
86200     case TK_LT:      zBinOp = "LT";     break;
86201     case TK_LE:      zBinOp = "LE";     break;
86202     case TK_GT:      zBinOp = "GT";     break;
86203     case TK_GE:      zBinOp = "GE";     break;
86204     case TK_NE:      zBinOp = "NE";     break;
86205     case TK_EQ:      zBinOp = "EQ";     break;
86206     case TK_IS:      zBinOp = "IS";     break;
86207     case TK_ISNOT:   zBinOp = "ISNOT";  break;
86208     case TK_AND:     zBinOp = "AND";    break;
86209     case TK_OR:      zBinOp = "OR";     break;
86210     case TK_PLUS:    zBinOp = "ADD";    break;
86211     case TK_STAR:    zBinOp = "MUL";    break;
86212     case TK_MINUS:   zBinOp = "SUB";    break;
86213     case TK_REM:     zBinOp = "REM";    break;
86214     case TK_BITAND:  zBinOp = "BITAND"; break;
86215     case TK_BITOR:   zBinOp = "BITOR";  break;
86216     case TK_SLASH:   zBinOp = "DIV";    break;
86217     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
86218     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
86219     case TK_CONCAT:  zBinOp = "CONCAT"; break;
86220     case TK_DOT:     zBinOp = "DOT";    break;
86221 
86222     case TK_UMINUS:  zUniOp = "UMINUS"; break;
86223     case TK_UPLUS:   zUniOp = "UPLUS";  break;
86224     case TK_BITNOT:  zUniOp = "BITNOT"; break;
86225     case TK_NOT:     zUniOp = "NOT";    break;
86226     case TK_ISNULL:  zUniOp = "ISNULL"; break;
86227     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
86228 
86229     case TK_COLLATE: {
86230       sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
86231       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
86232       break;
86233     }
86234 
86235     case TK_AGG_FUNCTION:
86236     case TK_FUNCTION: {
86237       ExprList *pFarg;       /* List of function arguments */
86238       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
86239         pFarg = 0;
86240       }else{
86241         pFarg = pExpr->x.pList;
86242       }
86243       if( pExpr->op==TK_AGG_FUNCTION ){
86244         sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
86245                              pExpr->op2, pExpr->u.zToken);
86246       }else{
86247         sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
86248       }
86249       if( pFarg ){
86250         sqlite3TreeViewExprList(pView, pFarg, 0, 0);
86251       }
86252       break;
86253     }
86254 #ifndef SQLITE_OMIT_SUBQUERY
86255     case TK_EXISTS: {
86256       sqlite3TreeViewLine(pView, "EXISTS-expr");
86257       sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
86258       break;
86259     }
86260     case TK_SELECT: {
86261       sqlite3TreeViewLine(pView, "SELECT-expr");
86262       sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
86263       break;
86264     }
86265     case TK_IN: {
86266       sqlite3TreeViewLine(pView, "IN");
86267       sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
86268       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
86269         sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
86270       }else{
86271         sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
86272       }
86273       break;
86274     }
86275 #endif /* SQLITE_OMIT_SUBQUERY */
86276 
86277     /*
86278     **    x BETWEEN y AND z
86279     **
86280     ** This is equivalent to
86281     **
86282     **    x>=y AND x<=z
86283     **
86284     ** X is stored in pExpr->pLeft.
86285     ** Y is stored in pExpr->pList->a[0].pExpr.
86286     ** Z is stored in pExpr->pList->a[1].pExpr.
86287     */
86288     case TK_BETWEEN: {
86289       Expr *pX = pExpr->pLeft;
86290       Expr *pY = pExpr->x.pList->a[0].pExpr;
86291       Expr *pZ = pExpr->x.pList->a[1].pExpr;
86292       sqlite3TreeViewLine(pView, "BETWEEN");
86293       sqlite3TreeViewExpr(pView, pX, 1);
86294       sqlite3TreeViewExpr(pView, pY, 1);
86295       sqlite3TreeViewExpr(pView, pZ, 0);
86296       break;
86297     }
86298     case TK_TRIGGER: {
86299       /* If the opcode is TK_TRIGGER, then the expression is a reference
86300       ** to a column in the new.* or old.* pseudo-tables available to
86301       ** trigger programs. In this case Expr.iTable is set to 1 for the
86302       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
86303       ** is set to the column of the pseudo-table to read, or to -1 to
86304       ** read the rowid field.
86305       */
86306       sqlite3TreeViewLine(pView, "%s(%d)",
86307           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
86308       break;
86309     }
86310     case TK_CASE: {
86311       sqlite3TreeViewLine(pView, "CASE");
86312       sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
86313       sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
86314       break;
86315     }
86316 #ifndef SQLITE_OMIT_TRIGGER
86317     case TK_RAISE: {
86318       const char *zType = "unk";
86319       switch( pExpr->affinity ){
86320         case OE_Rollback:   zType = "rollback";  break;
86321         case OE_Abort:      zType = "abort";     break;
86322         case OE_Fail:       zType = "fail";      break;
86323         case OE_Ignore:     zType = "ignore";    break;
86324       }
86325       sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
86326       break;
86327     }
86328 #endif
86329     default: {
86330       sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
86331       break;
86332     }
86333   }
86334   if( zBinOp ){
86335     sqlite3TreeViewLine(pView, "%s", zBinOp);
86336     sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
86337     sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
86338   }else if( zUniOp ){
86339     sqlite3TreeViewLine(pView, "%s", zUniOp);
86340     sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
86341   }
86342   sqlite3TreeViewPop(pView);
86343 }
86344 #endif /* SQLITE_DEBUG */
86345 
86346 #ifdef SQLITE_DEBUG
86347 /*
86348 ** Generate a human-readable explanation of an expression list.
86349 */
86350 SQLITE_PRIVATE void sqlite3TreeViewExprList(
86351   TreeView *pView,
86352   const ExprList *pList,
86353   u8 moreToFollow,
86354   const char *zLabel
86355 ){
86356   int i;
86357   pView = sqlite3TreeViewPush(pView, moreToFollow);
86358   if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
86359   if( pList==0 ){
86360     sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
86361   }else{
86362     sqlite3TreeViewLine(pView, "%s", zLabel);
86363     for(i=0; i<pList->nExpr; i++){
86364       sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
86365 #if 0
86366      if( pList->a[i].zName ){
86367         sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
86368       }
86369       if( pList->a[i].bSpanIsTab ){
86370         sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
86371       }
86372 #endif
86373     }
86374   }
86375   sqlite3TreeViewPop(pView);
86376 }
86377 #endif /* SQLITE_DEBUG */
86378 
86379 /*
86380 ** Generate code that pushes the value of every element of the given
86381 ** expression list into a sequence of registers beginning at target.
86382 **
86383 ** Return the number of elements evaluated.
86384 **
86385 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
86386 ** filled using OP_SCopy.  OP_Copy must be used instead.
86387 **
86388 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
86389 ** factored out into initialization code.
86390 */
86391 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
86392   Parse *pParse,     /* Parsing context */
86393   ExprList *pList,   /* The expression list to be coded */
86394   int target,        /* Where to write results */
86395   u8 flags           /* SQLITE_ECEL_* flags */
86396 ){
86397   struct ExprList_item *pItem;
86398   int i, n;
86399   u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
86400   assert( pList!=0 );
86401   assert( target>0 );
86402   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
86403   n = pList->nExpr;
86404   if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
86405   for(pItem=pList->a, i=0; i<n; i++, pItem++){
86406     Expr *pExpr = pItem->pExpr;
86407     if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
86408       sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
86409     }else{
86410       int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
86411       if( inReg!=target+i ){
86412         VdbeOp *pOp;
86413         Vdbe *v = pParse->pVdbe;
86414         if( copyOp==OP_Copy
86415          && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
86416          && pOp->p1+pOp->p3+1==inReg
86417          && pOp->p2+pOp->p3+1==target+i
86418         ){
86419           pOp->p3++;
86420         }else{
86421           sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
86422         }
86423       }
86424     }
86425   }
86426   return n;
86427 }
86428 
86429 /*
86430 ** Generate code for a BETWEEN operator.
86431 **
86432 **    x BETWEEN y AND z
86433 **
86434 ** The above is equivalent to
86435 **
86436 **    x>=y AND x<=z
86437 **
86438 ** Code it as such, taking care to do the common subexpression
86439 ** elimination of x.
86440 */
86441 static void exprCodeBetween(
86442   Parse *pParse,    /* Parsing and code generating context */
86443   Expr *pExpr,      /* The BETWEEN expression */
86444   int dest,         /* Jump here if the jump is taken */
86445   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
86446   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
86447 ){
86448   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
86449   Expr compLeft;    /* The  x>=y  term */
86450   Expr compRight;   /* The  x<=z  term */
86451   Expr exprX;       /* The  x  subexpression */
86452   int regFree1 = 0; /* Temporary use register */
86453 
86454   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
86455   exprX = *pExpr->pLeft;
86456   exprAnd.op = TK_AND;
86457   exprAnd.pLeft = &compLeft;
86458   exprAnd.pRight = &compRight;
86459   compLeft.op = TK_GE;
86460   compLeft.pLeft = &exprX;
86461   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
86462   compRight.op = TK_LE;
86463   compRight.pLeft = &exprX;
86464   compRight.pRight = pExpr->x.pList->a[1].pExpr;
86465   exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
86466   if( jumpIfTrue ){
86467     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
86468   }else{
86469     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
86470   }
86471   sqlite3ReleaseTempReg(pParse, regFree1);
86472 
86473   /* Ensure adequate test coverage */
86474   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
86475   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
86476   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
86477   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
86478   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
86479   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
86480   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
86481   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
86482 }
86483 
86484 /*
86485 ** Generate code for a boolean expression such that a jump is made
86486 ** to the label "dest" if the expression is true but execution
86487 ** continues straight thru if the expression is false.
86488 **
86489 ** If the expression evaluates to NULL (neither true nor false), then
86490 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
86491 **
86492 ** This code depends on the fact that certain token values (ex: TK_EQ)
86493 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
86494 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
86495 ** the make process cause these values to align.  Assert()s in the code
86496 ** below verify that the numbers are aligned correctly.
86497 */
86498 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
86499   Vdbe *v = pParse->pVdbe;
86500   int op = 0;
86501   int regFree1 = 0;
86502   int regFree2 = 0;
86503   int r1, r2;
86504 
86505   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
86506   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
86507   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
86508   op = pExpr->op;
86509   switch( op ){
86510     case TK_AND: {
86511       int d2 = sqlite3VdbeMakeLabel(v);
86512       testcase( jumpIfNull==0 );
86513       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
86514       sqlite3ExprCachePush(pParse);
86515       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
86516       sqlite3VdbeResolveLabel(v, d2);
86517       sqlite3ExprCachePop(pParse);
86518       break;
86519     }
86520     case TK_OR: {
86521       testcase( jumpIfNull==0 );
86522       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
86523       sqlite3ExprCachePush(pParse);
86524       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
86525       sqlite3ExprCachePop(pParse);
86526       break;
86527     }
86528     case TK_NOT: {
86529       testcase( jumpIfNull==0 );
86530       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
86531       break;
86532     }
86533     case TK_LT:
86534     case TK_LE:
86535     case TK_GT:
86536     case TK_GE:
86537     case TK_NE:
86538     case TK_EQ: {
86539       testcase( jumpIfNull==0 );
86540       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
86541       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
86542       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
86543                   r1, r2, dest, jumpIfNull);
86544       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
86545       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
86546       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
86547       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
86548       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
86549       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
86550       testcase( regFree1==0 );
86551       testcase( regFree2==0 );
86552       break;
86553     }
86554     case TK_IS:
86555     case TK_ISNOT: {
86556       testcase( op==TK_IS );
86557       testcase( op==TK_ISNOT );
86558       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
86559       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
86560       op = (op==TK_IS) ? TK_EQ : TK_NE;
86561       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
86562                   r1, r2, dest, SQLITE_NULLEQ);
86563       VdbeCoverageIf(v, op==TK_EQ);
86564       VdbeCoverageIf(v, op==TK_NE);
86565       testcase( regFree1==0 );
86566       testcase( regFree2==0 );
86567       break;
86568     }
86569     case TK_ISNULL:
86570     case TK_NOTNULL: {
86571       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
86572       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
86573       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
86574       sqlite3VdbeAddOp2(v, op, r1, dest);
86575       VdbeCoverageIf(v, op==TK_ISNULL);
86576       VdbeCoverageIf(v, op==TK_NOTNULL);
86577       testcase( regFree1==0 );
86578       break;
86579     }
86580     case TK_BETWEEN: {
86581       testcase( jumpIfNull==0 );
86582       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
86583       break;
86584     }
86585 #ifndef SQLITE_OMIT_SUBQUERY
86586     case TK_IN: {
86587       int destIfFalse = sqlite3VdbeMakeLabel(v);
86588       int destIfNull = jumpIfNull ? dest : destIfFalse;
86589       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
86590       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
86591       sqlite3VdbeResolveLabel(v, destIfFalse);
86592       break;
86593     }
86594 #endif
86595     default: {
86596       if( exprAlwaysTrue(pExpr) ){
86597         sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
86598       }else if( exprAlwaysFalse(pExpr) ){
86599         /* No-op */
86600       }else{
86601         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
86602         sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
86603         VdbeCoverage(v);
86604         testcase( regFree1==0 );
86605         testcase( jumpIfNull==0 );
86606       }
86607       break;
86608     }
86609   }
86610   sqlite3ReleaseTempReg(pParse, regFree1);
86611   sqlite3ReleaseTempReg(pParse, regFree2);
86612 }
86613 
86614 /*
86615 ** Generate code for a boolean expression such that a jump is made
86616 ** to the label "dest" if the expression is false but execution
86617 ** continues straight thru if the expression is true.
86618 **
86619 ** If the expression evaluates to NULL (neither true nor false) then
86620 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
86621 ** is 0.
86622 */
86623 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
86624   Vdbe *v = pParse->pVdbe;
86625   int op = 0;
86626   int regFree1 = 0;
86627   int regFree2 = 0;
86628   int r1, r2;
86629 
86630   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
86631   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
86632   if( pExpr==0 )    return;
86633 
86634   /* The value of pExpr->op and op are related as follows:
86635   **
86636   **       pExpr->op            op
86637   **       ---------          ----------
86638   **       TK_ISNULL          OP_NotNull
86639   **       TK_NOTNULL         OP_IsNull
86640   **       TK_NE              OP_Eq
86641   **       TK_EQ              OP_Ne
86642   **       TK_GT              OP_Le
86643   **       TK_LE              OP_Gt
86644   **       TK_GE              OP_Lt
86645   **       TK_LT              OP_Ge
86646   **
86647   ** For other values of pExpr->op, op is undefined and unused.
86648   ** The value of TK_ and OP_ constants are arranged such that we
86649   ** can compute the mapping above using the following expression.
86650   ** Assert()s verify that the computation is correct.
86651   */
86652   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
86653 
86654   /* Verify correct alignment of TK_ and OP_ constants
86655   */
86656   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
86657   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
86658   assert( pExpr->op!=TK_NE || op==OP_Eq );
86659   assert( pExpr->op!=TK_EQ || op==OP_Ne );
86660   assert( pExpr->op!=TK_LT || op==OP_Ge );
86661   assert( pExpr->op!=TK_LE || op==OP_Gt );
86662   assert( pExpr->op!=TK_GT || op==OP_Le );
86663   assert( pExpr->op!=TK_GE || op==OP_Lt );
86664 
86665   switch( pExpr->op ){
86666     case TK_AND: {
86667       testcase( jumpIfNull==0 );
86668       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
86669       sqlite3ExprCachePush(pParse);
86670       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
86671       sqlite3ExprCachePop(pParse);
86672       break;
86673     }
86674     case TK_OR: {
86675       int d2 = sqlite3VdbeMakeLabel(v);
86676       testcase( jumpIfNull==0 );
86677       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
86678       sqlite3ExprCachePush(pParse);
86679       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
86680       sqlite3VdbeResolveLabel(v, d2);
86681       sqlite3ExprCachePop(pParse);
86682       break;
86683     }
86684     case TK_NOT: {
86685       testcase( jumpIfNull==0 );
86686       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
86687       break;
86688     }
86689     case TK_LT:
86690     case TK_LE:
86691     case TK_GT:
86692     case TK_GE:
86693     case TK_NE:
86694     case TK_EQ: {
86695       testcase( jumpIfNull==0 );
86696       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
86697       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
86698       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
86699                   r1, r2, dest, jumpIfNull);
86700       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
86701       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
86702       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
86703       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
86704       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
86705       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
86706       testcase( regFree1==0 );
86707       testcase( regFree2==0 );
86708       break;
86709     }
86710     case TK_IS:
86711     case TK_ISNOT: {
86712       testcase( pExpr->op==TK_IS );
86713       testcase( pExpr->op==TK_ISNOT );
86714       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
86715       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
86716       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
86717       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
86718                   r1, r2, dest, SQLITE_NULLEQ);
86719       VdbeCoverageIf(v, op==TK_EQ);
86720       VdbeCoverageIf(v, op==TK_NE);
86721       testcase( regFree1==0 );
86722       testcase( regFree2==0 );
86723       break;
86724     }
86725     case TK_ISNULL:
86726     case TK_NOTNULL: {
86727       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
86728       sqlite3VdbeAddOp2(v, op, r1, dest);
86729       testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
86730       testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
86731       testcase( regFree1==0 );
86732       break;
86733     }
86734     case TK_BETWEEN: {
86735       testcase( jumpIfNull==0 );
86736       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
86737       break;
86738     }
86739 #ifndef SQLITE_OMIT_SUBQUERY
86740     case TK_IN: {
86741       if( jumpIfNull ){
86742         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
86743       }else{
86744         int destIfNull = sqlite3VdbeMakeLabel(v);
86745         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
86746         sqlite3VdbeResolveLabel(v, destIfNull);
86747       }
86748       break;
86749     }
86750 #endif
86751     default: {
86752       if( exprAlwaysFalse(pExpr) ){
86753         sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
86754       }else if( exprAlwaysTrue(pExpr) ){
86755         /* no-op */
86756       }else{
86757         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
86758         sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
86759         VdbeCoverage(v);
86760         testcase( regFree1==0 );
86761         testcase( jumpIfNull==0 );
86762       }
86763       break;
86764     }
86765   }
86766   sqlite3ReleaseTempReg(pParse, regFree1);
86767   sqlite3ReleaseTempReg(pParse, regFree2);
86768 }
86769 
86770 /*
86771 ** Do a deep comparison of two expression trees.  Return 0 if the two
86772 ** expressions are completely identical.  Return 1 if they differ only
86773 ** by a COLLATE operator at the top level.  Return 2 if there are differences
86774 ** other than the top-level COLLATE operator.
86775 **
86776 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
86777 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
86778 **
86779 ** The pA side might be using TK_REGISTER.  If that is the case and pB is
86780 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
86781 **
86782 ** Sometimes this routine will return 2 even if the two expressions
86783 ** really are equivalent.  If we cannot prove that the expressions are
86784 ** identical, we return 2 just to be safe.  So if this routine
86785 ** returns 2, then you do not really know for certain if the two
86786 ** expressions are the same.  But if you get a 0 or 1 return, then you
86787 ** can be sure the expressions are the same.  In the places where
86788 ** this routine is used, it does not hurt to get an extra 2 - that
86789 ** just might result in some slightly slower code.  But returning
86790 ** an incorrect 0 or 1 could lead to a malfunction.
86791 */
86792 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
86793   u32 combinedFlags;
86794   if( pA==0 || pB==0 ){
86795     return pB==pA ? 0 : 2;
86796   }
86797   combinedFlags = pA->flags | pB->flags;
86798   if( combinedFlags & EP_IntValue ){
86799     if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
86800       return 0;
86801     }
86802     return 2;
86803   }
86804   if( pA->op!=pB->op ){
86805     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
86806       return 1;
86807     }
86808     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
86809       return 1;
86810     }
86811     return 2;
86812   }
86813   if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
86814     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
86815       return pA->op==TK_COLLATE ? 1 : 2;
86816     }
86817   }
86818   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
86819   if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
86820     if( combinedFlags & EP_xIsSelect ) return 2;
86821     if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
86822     if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
86823     if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
86824     if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
86825       if( pA->iColumn!=pB->iColumn ) return 2;
86826       if( pA->iTable!=pB->iTable
86827        && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
86828     }
86829   }
86830   return 0;
86831 }
86832 
86833 /*
86834 ** Compare two ExprList objects.  Return 0 if they are identical and
86835 ** non-zero if they differ in any way.
86836 **
86837 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
86838 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
86839 **
86840 ** This routine might return non-zero for equivalent ExprLists.  The
86841 ** only consequence will be disabled optimizations.  But this routine
86842 ** must never return 0 if the two ExprList objects are different, or
86843 ** a malfunction will result.
86844 **
86845 ** Two NULL pointers are considered to be the same.  But a NULL pointer
86846 ** always differs from a non-NULL pointer.
86847 */
86848 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
86849   int i;
86850   if( pA==0 && pB==0 ) return 0;
86851   if( pA==0 || pB==0 ) return 1;
86852   if( pA->nExpr!=pB->nExpr ) return 1;
86853   for(i=0; i<pA->nExpr; i++){
86854     Expr *pExprA = pA->a[i].pExpr;
86855     Expr *pExprB = pB->a[i].pExpr;
86856     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
86857     if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
86858   }
86859   return 0;
86860 }
86861 
86862 /*
86863 ** Return true if we can prove the pE2 will always be true if pE1 is
86864 ** true.  Return false if we cannot complete the proof or if pE2 might
86865 ** be false.  Examples:
86866 **
86867 **     pE1: x==5       pE2: x==5             Result: true
86868 **     pE1: x>0        pE2: x==5             Result: false
86869 **     pE1: x=21       pE2: x=21 OR y=43     Result: true
86870 **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
86871 **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
86872 **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
86873 **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
86874 **
86875 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
86876 ** Expr.iTable<0 then assume a table number given by iTab.
86877 **
86878 ** When in doubt, return false.  Returning true might give a performance
86879 ** improvement.  Returning false might cause a performance reduction, but
86880 ** it will always give the correct answer and is hence always safe.
86881 */
86882 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
86883   if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
86884     return 1;
86885   }
86886   if( pE2->op==TK_OR
86887    && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
86888              || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
86889   ){
86890     return 1;
86891   }
86892   if( pE2->op==TK_NOTNULL
86893    && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
86894    && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
86895   ){
86896     return 1;
86897   }
86898   return 0;
86899 }
86900 
86901 /*
86902 ** An instance of the following structure is used by the tree walker
86903 ** to count references to table columns in the arguments of an
86904 ** aggregate function, in order to implement the
86905 ** sqlite3FunctionThisSrc() routine.
86906 */
86907 struct SrcCount {
86908   SrcList *pSrc;   /* One particular FROM clause in a nested query */
86909   int nThis;       /* Number of references to columns in pSrcList */
86910   int nOther;      /* Number of references to columns in other FROM clauses */
86911 };
86912 
86913 /*
86914 ** Count the number of references to columns.
86915 */
86916 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
86917   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
86918   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
86919   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
86920   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
86921   ** NEVER() will need to be removed. */
86922   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
86923     int i;
86924     struct SrcCount *p = pWalker->u.pSrcCount;
86925     SrcList *pSrc = p->pSrc;
86926     int nSrc = pSrc ? pSrc->nSrc : 0;
86927     for(i=0; i<nSrc; i++){
86928       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
86929     }
86930     if( i<nSrc ){
86931       p->nThis++;
86932     }else{
86933       p->nOther++;
86934     }
86935   }
86936   return WRC_Continue;
86937 }
86938 
86939 /*
86940 ** Determine if any of the arguments to the pExpr Function reference
86941 ** pSrcList.  Return true if they do.  Also return true if the function
86942 ** has no arguments or has only constant arguments.  Return false if pExpr
86943 ** references columns but not columns of tables found in pSrcList.
86944 */
86945 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
86946   Walker w;
86947   struct SrcCount cnt;
86948   assert( pExpr->op==TK_AGG_FUNCTION );
86949   memset(&w, 0, sizeof(w));
86950   w.xExprCallback = exprSrcCount;
86951   w.u.pSrcCount = &cnt;
86952   cnt.pSrc = pSrcList;
86953   cnt.nThis = 0;
86954   cnt.nOther = 0;
86955   sqlite3WalkExprList(&w, pExpr->x.pList);
86956   return cnt.nThis>0 || cnt.nOther==0;
86957 }
86958 
86959 /*
86960 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
86961 ** the new element.  Return a negative number if malloc fails.
86962 */
86963 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
86964   int i;
86965   pInfo->aCol = sqlite3ArrayAllocate(
86966        db,
86967        pInfo->aCol,
86968        sizeof(pInfo->aCol[0]),
86969        &pInfo->nColumn,
86970        &i
86971   );
86972   return i;
86973 }
86974 
86975 /*
86976 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
86977 ** the new element.  Return a negative number if malloc fails.
86978 */
86979 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
86980   int i;
86981   pInfo->aFunc = sqlite3ArrayAllocate(
86982        db,
86983        pInfo->aFunc,
86984        sizeof(pInfo->aFunc[0]),
86985        &pInfo->nFunc,
86986        &i
86987   );
86988   return i;
86989 }
86990 
86991 /*
86992 ** This is the xExprCallback for a tree walker.  It is used to
86993 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
86994 ** for additional information.
86995 */
86996 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
86997   int i;
86998   NameContext *pNC = pWalker->u.pNC;
86999   Parse *pParse = pNC->pParse;
87000   SrcList *pSrcList = pNC->pSrcList;
87001   AggInfo *pAggInfo = pNC->pAggInfo;
87002 
87003   switch( pExpr->op ){
87004     case TK_AGG_COLUMN:
87005     case TK_COLUMN: {
87006       testcase( pExpr->op==TK_AGG_COLUMN );
87007       testcase( pExpr->op==TK_COLUMN );
87008       /* Check to see if the column is in one of the tables in the FROM
87009       ** clause of the aggregate query */
87010       if( ALWAYS(pSrcList!=0) ){
87011         struct SrcList_item *pItem = pSrcList->a;
87012         for(i=0; i<pSrcList->nSrc; i++, pItem++){
87013           struct AggInfo_col *pCol;
87014           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
87015           if( pExpr->iTable==pItem->iCursor ){
87016             /* If we reach this point, it means that pExpr refers to a table
87017             ** that is in the FROM clause of the aggregate query.
87018             **
87019             ** Make an entry for the column in pAggInfo->aCol[] if there
87020             ** is not an entry there already.
87021             */
87022             int k;
87023             pCol = pAggInfo->aCol;
87024             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
87025               if( pCol->iTable==pExpr->iTable &&
87026                   pCol->iColumn==pExpr->iColumn ){
87027                 break;
87028               }
87029             }
87030             if( (k>=pAggInfo->nColumn)
87031              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
87032             ){
87033               pCol = &pAggInfo->aCol[k];
87034               pCol->pTab = pExpr->pTab;
87035               pCol->iTable = pExpr->iTable;
87036               pCol->iColumn = pExpr->iColumn;
87037               pCol->iMem = ++pParse->nMem;
87038               pCol->iSorterColumn = -1;
87039               pCol->pExpr = pExpr;
87040               if( pAggInfo->pGroupBy ){
87041                 int j, n;
87042                 ExprList *pGB = pAggInfo->pGroupBy;
87043                 struct ExprList_item *pTerm = pGB->a;
87044                 n = pGB->nExpr;
87045                 for(j=0; j<n; j++, pTerm++){
87046                   Expr *pE = pTerm->pExpr;
87047                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
87048                       pE->iColumn==pExpr->iColumn ){
87049                     pCol->iSorterColumn = j;
87050                     break;
87051                   }
87052                 }
87053               }
87054               if( pCol->iSorterColumn<0 ){
87055                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
87056               }
87057             }
87058             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
87059             ** because it was there before or because we just created it).
87060             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
87061             ** pAggInfo->aCol[] entry.
87062             */
87063             ExprSetVVAProperty(pExpr, EP_NoReduce);
87064             pExpr->pAggInfo = pAggInfo;
87065             pExpr->op = TK_AGG_COLUMN;
87066             pExpr->iAgg = (i16)k;
87067             break;
87068           } /* endif pExpr->iTable==pItem->iCursor */
87069         } /* end loop over pSrcList */
87070       }
87071       return WRC_Prune;
87072     }
87073     case TK_AGG_FUNCTION: {
87074       if( (pNC->ncFlags & NC_InAggFunc)==0
87075        && pWalker->walkerDepth==pExpr->op2
87076       ){
87077         /* Check to see if pExpr is a duplicate of another aggregate
87078         ** function that is already in the pAggInfo structure
87079         */
87080         struct AggInfo_func *pItem = pAggInfo->aFunc;
87081         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
87082           if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
87083             break;
87084           }
87085         }
87086         if( i>=pAggInfo->nFunc ){
87087           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
87088           */
87089           u8 enc = ENC(pParse->db);
87090           i = addAggInfoFunc(pParse->db, pAggInfo);
87091           if( i>=0 ){
87092             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
87093             pItem = &pAggInfo->aFunc[i];
87094             pItem->pExpr = pExpr;
87095             pItem->iMem = ++pParse->nMem;
87096             assert( !ExprHasProperty(pExpr, EP_IntValue) );
87097             pItem->pFunc = sqlite3FindFunction(pParse->db,
87098                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
87099                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
87100             if( pExpr->flags & EP_Distinct ){
87101               pItem->iDistinct = pParse->nTab++;
87102             }else{
87103               pItem->iDistinct = -1;
87104             }
87105           }
87106         }
87107         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
87108         */
87109         assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
87110         ExprSetVVAProperty(pExpr, EP_NoReduce);
87111         pExpr->iAgg = (i16)i;
87112         pExpr->pAggInfo = pAggInfo;
87113         return WRC_Prune;
87114       }else{
87115         return WRC_Continue;
87116       }
87117     }
87118   }
87119   return WRC_Continue;
87120 }
87121 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
87122   UNUSED_PARAMETER(pWalker);
87123   UNUSED_PARAMETER(pSelect);
87124   return WRC_Continue;
87125 }
87126 
87127 /*
87128 ** Analyze the pExpr expression looking for aggregate functions and
87129 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
87130 ** points to.  Additional entries are made on the AggInfo object as
87131 ** necessary.
87132 **
87133 ** This routine should only be called after the expression has been
87134 ** analyzed by sqlite3ResolveExprNames().
87135 */
87136 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
87137   Walker w;
87138   memset(&w, 0, sizeof(w));
87139   w.xExprCallback = analyzeAggregate;
87140   w.xSelectCallback = analyzeAggregatesInSelect;
87141   w.u.pNC = pNC;
87142   assert( pNC->pSrcList!=0 );
87143   sqlite3WalkExpr(&w, pExpr);
87144 }
87145 
87146 /*
87147 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
87148 ** expression list.  Return the number of errors.
87149 **
87150 ** If an error is found, the analysis is cut short.
87151 */
87152 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
87153   struct ExprList_item *pItem;
87154   int i;
87155   if( pList ){
87156     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
87157       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
87158     }
87159   }
87160 }
87161 
87162 /*
87163 ** Allocate a single new register for use to hold some intermediate result.
87164 */
87165 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
87166   if( pParse->nTempReg==0 ){
87167     return ++pParse->nMem;
87168   }
87169   return pParse->aTempReg[--pParse->nTempReg];
87170 }
87171 
87172 /*
87173 ** Deallocate a register, making available for reuse for some other
87174 ** purpose.
87175 **
87176 ** If a register is currently being used by the column cache, then
87177 ** the deallocation is deferred until the column cache line that uses
87178 ** the register becomes stale.
87179 */
87180 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
87181   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
87182     int i;
87183     struct yColCache *p;
87184     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
87185       if( p->iReg==iReg ){
87186         p->tempReg = 1;
87187         return;
87188       }
87189     }
87190     pParse->aTempReg[pParse->nTempReg++] = iReg;
87191   }
87192 }
87193 
87194 /*
87195 ** Allocate or deallocate a block of nReg consecutive registers
87196 */
87197 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
87198   int i, n;
87199   i = pParse->iRangeReg;
87200   n = pParse->nRangeReg;
87201   if( nReg<=n ){
87202     assert( !usedAsColumnCache(pParse, i, i+n-1) );
87203     pParse->iRangeReg += nReg;
87204     pParse->nRangeReg -= nReg;
87205   }else{
87206     i = pParse->nMem+1;
87207     pParse->nMem += nReg;
87208   }
87209   return i;
87210 }
87211 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
87212   sqlite3ExprCacheRemove(pParse, iReg, nReg);
87213   if( nReg>pParse->nRangeReg ){
87214     pParse->nRangeReg = nReg;
87215     pParse->iRangeReg = iReg;
87216   }
87217 }
87218 
87219 /*
87220 ** Mark all temporary registers as being unavailable for reuse.
87221 */
87222 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
87223   pParse->nTempReg = 0;
87224   pParse->nRangeReg = 0;
87225 }
87226 
87227 /************** End of expr.c ************************************************/
87228 /************** Begin file alter.c *******************************************/
87229 /*
87230 ** 2005 February 15
87231 **
87232 ** The author disclaims copyright to this source code.  In place of
87233 ** a legal notice, here is a blessing:
87234 **
87235 **    May you do good and not evil.
87236 **    May you find forgiveness for yourself and forgive others.
87237 **    May you share freely, never taking more than you give.
87238 **
87239 *************************************************************************
87240 ** This file contains C code routines that used to generate VDBE code
87241 ** that implements the ALTER TABLE command.
87242 */
87243 
87244 /*
87245 ** The code in this file only exists if we are not omitting the
87246 ** ALTER TABLE logic from the build.
87247 */
87248 #ifndef SQLITE_OMIT_ALTERTABLE
87249 
87250 
87251 /*
87252 ** This function is used by SQL generated to implement the
87253 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
87254 ** CREATE INDEX command. The second is a table name. The table name in
87255 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
87256 ** argument and the result returned. Examples:
87257 **
87258 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
87259 **     -> 'CREATE TABLE def(a, b, c)'
87260 **
87261 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
87262 **     -> 'CREATE INDEX i ON def(a, b, c)'
87263 */
87264 static void renameTableFunc(
87265   sqlite3_context *context,
87266   int NotUsed,
87267   sqlite3_value **argv
87268 ){
87269   unsigned char const *zSql = sqlite3_value_text(argv[0]);
87270   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
87271 
87272   int token;
87273   Token tname;
87274   unsigned char const *zCsr = zSql;
87275   int len = 0;
87276   char *zRet;
87277 
87278   sqlite3 *db = sqlite3_context_db_handle(context);
87279 
87280   UNUSED_PARAMETER(NotUsed);
87281 
87282   /* The principle used to locate the table name in the CREATE TABLE
87283   ** statement is that the table name is the first non-space token that
87284   ** is immediately followed by a TK_LP or TK_USING token.
87285   */
87286   if( zSql ){
87287     do {
87288       if( !*zCsr ){
87289         /* Ran out of input before finding an opening bracket. Return NULL. */
87290         return;
87291       }
87292 
87293       /* Store the token that zCsr points to in tname. */
87294       tname.z = (char*)zCsr;
87295       tname.n = len;
87296 
87297       /* Advance zCsr to the next token. Store that token type in 'token',
87298       ** and its length in 'len' (to be used next iteration of this loop).
87299       */
87300       do {
87301         zCsr += len;
87302         len = sqlite3GetToken(zCsr, &token);
87303       } while( token==TK_SPACE );
87304       assert( len>0 );
87305     } while( token!=TK_LP && token!=TK_USING );
87306 
87307     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
87308        zSql, zTableName, tname.z+tname.n);
87309     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
87310   }
87311 }
87312 
87313 /*
87314 ** This C function implements an SQL user function that is used by SQL code
87315 ** generated by the ALTER TABLE ... RENAME command to modify the definition
87316 ** of any foreign key constraints that use the table being renamed as the
87317 ** parent table. It is passed three arguments:
87318 **
87319 **   1) The complete text of the CREATE TABLE statement being modified,
87320 **   2) The old name of the table being renamed, and
87321 **   3) The new name of the table being renamed.
87322 **
87323 ** It returns the new CREATE TABLE statement. For example:
87324 **
87325 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
87326 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
87327 */
87328 #ifndef SQLITE_OMIT_FOREIGN_KEY
87329 static void renameParentFunc(
87330   sqlite3_context *context,
87331   int NotUsed,
87332   sqlite3_value **argv
87333 ){
87334   sqlite3 *db = sqlite3_context_db_handle(context);
87335   char *zOutput = 0;
87336   char *zResult;
87337   unsigned char const *zInput = sqlite3_value_text(argv[0]);
87338   unsigned char const *zOld = sqlite3_value_text(argv[1]);
87339   unsigned char const *zNew = sqlite3_value_text(argv[2]);
87340 
87341   unsigned const char *z;         /* Pointer to token */
87342   int n;                          /* Length of token z */
87343   int token;                      /* Type of token */
87344 
87345   UNUSED_PARAMETER(NotUsed);
87346   if( zInput==0 || zOld==0 ) return;
87347   for(z=zInput; *z; z=z+n){
87348     n = sqlite3GetToken(z, &token);
87349     if( token==TK_REFERENCES ){
87350       char *zParent;
87351       do {
87352         z += n;
87353         n = sqlite3GetToken(z, &token);
87354       }while( token==TK_SPACE );
87355 
87356       if( token==TK_ILLEGAL ) break;
87357       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
87358       if( zParent==0 ) break;
87359       sqlite3Dequote(zParent);
87360       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
87361         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
87362             (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
87363         );
87364         sqlite3DbFree(db, zOutput);
87365         zOutput = zOut;
87366         zInput = &z[n];
87367       }
87368       sqlite3DbFree(db, zParent);
87369     }
87370   }
87371 
87372   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
87373   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
87374   sqlite3DbFree(db, zOutput);
87375 }
87376 #endif
87377 
87378 #ifndef SQLITE_OMIT_TRIGGER
87379 /* This function is used by SQL generated to implement the
87380 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
87381 ** statement. The second is a table name. The table name in the CREATE
87382 ** TRIGGER statement is replaced with the third argument and the result
87383 ** returned. This is analagous to renameTableFunc() above, except for CREATE
87384 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
87385 */
87386 static void renameTriggerFunc(
87387   sqlite3_context *context,
87388   int NotUsed,
87389   sqlite3_value **argv
87390 ){
87391   unsigned char const *zSql = sqlite3_value_text(argv[0]);
87392   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
87393 
87394   int token;
87395   Token tname;
87396   int dist = 3;
87397   unsigned char const *zCsr = zSql;
87398   int len = 0;
87399   char *zRet;
87400   sqlite3 *db = sqlite3_context_db_handle(context);
87401 
87402   UNUSED_PARAMETER(NotUsed);
87403 
87404   /* The principle used to locate the table name in the CREATE TRIGGER
87405   ** statement is that the table name is the first token that is immediately
87406   ** preceded by either TK_ON or TK_DOT and immediately followed by one
87407   ** of TK_WHEN, TK_BEGIN or TK_FOR.
87408   */
87409   if( zSql ){
87410     do {
87411 
87412       if( !*zCsr ){
87413         /* Ran out of input before finding the table name. Return NULL. */
87414         return;
87415       }
87416 
87417       /* Store the token that zCsr points to in tname. */
87418       tname.z = (char*)zCsr;
87419       tname.n = len;
87420 
87421       /* Advance zCsr to the next token. Store that token type in 'token',
87422       ** and its length in 'len' (to be used next iteration of this loop).
87423       */
87424       do {
87425         zCsr += len;
87426         len = sqlite3GetToken(zCsr, &token);
87427       }while( token==TK_SPACE );
87428       assert( len>0 );
87429 
87430       /* Variable 'dist' stores the number of tokens read since the most
87431       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
87432       ** token is read and 'dist' equals 2, the condition stated above
87433       ** to be met.
87434       **
87435       ** Note that ON cannot be a database, table or column name, so
87436       ** there is no need to worry about syntax like
87437       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
87438       */
87439       dist++;
87440       if( token==TK_DOT || token==TK_ON ){
87441         dist = 0;
87442       }
87443     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
87444 
87445     /* Variable tname now contains the token that is the old table-name
87446     ** in the CREATE TRIGGER statement.
87447     */
87448     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
87449        zSql, zTableName, tname.z+tname.n);
87450     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
87451   }
87452 }
87453 #endif   /* !SQLITE_OMIT_TRIGGER */
87454 
87455 /*
87456 ** Register built-in functions used to help implement ALTER TABLE
87457 */
87458 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
87459   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
87460     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
87461 #ifndef SQLITE_OMIT_TRIGGER
87462     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
87463 #endif
87464 #ifndef SQLITE_OMIT_FOREIGN_KEY
87465     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
87466 #endif
87467   };
87468   int i;
87469   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
87470   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
87471 
87472   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
87473     sqlite3FuncDefInsert(pHash, &aFunc[i]);
87474   }
87475 }
87476 
87477 /*
87478 ** This function is used to create the text of expressions of the form:
87479 **
87480 **   name=<constant1> OR name=<constant2> OR ...
87481 **
87482 ** If argument zWhere is NULL, then a pointer string containing the text
87483 ** "name=<constant>" is returned, where <constant> is the quoted version
87484 ** of the string passed as argument zConstant. The returned buffer is
87485 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
87486 ** caller to ensure that it is eventually freed.
87487 **
87488 ** If argument zWhere is not NULL, then the string returned is
87489 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
87490 ** In this case zWhere is passed to sqlite3DbFree() before returning.
87491 **
87492 */
87493 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
87494   char *zNew;
87495   if( !zWhere ){
87496     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
87497   }else{
87498     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
87499     sqlite3DbFree(db, zWhere);
87500   }
87501   return zNew;
87502 }
87503 
87504 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
87505 /*
87506 ** Generate the text of a WHERE expression which can be used to select all
87507 ** tables that have foreign key constraints that refer to table pTab (i.e.
87508 ** constraints for which pTab is the parent table) from the sqlite_master
87509 ** table.
87510 */
87511 static char *whereForeignKeys(Parse *pParse, Table *pTab){
87512   FKey *p;
87513   char *zWhere = 0;
87514   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
87515     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
87516   }
87517   return zWhere;
87518 }
87519 #endif
87520 
87521 /*
87522 ** Generate the text of a WHERE expression which can be used to select all
87523 ** temporary triggers on table pTab from the sqlite_temp_master table. If
87524 ** table pTab has no temporary triggers, or is itself stored in the
87525 ** temporary database, NULL is returned.
87526 */
87527 static char *whereTempTriggers(Parse *pParse, Table *pTab){
87528   Trigger *pTrig;
87529   char *zWhere = 0;
87530   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
87531 
87532   /* If the table is not located in the temp-db (in which case NULL is
87533   ** returned, loop through the tables list of triggers. For each trigger
87534   ** that is not part of the temp-db schema, add a clause to the WHERE
87535   ** expression being built up in zWhere.
87536   */
87537   if( pTab->pSchema!=pTempSchema ){
87538     sqlite3 *db = pParse->db;
87539     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
87540       if( pTrig->pSchema==pTempSchema ){
87541         zWhere = whereOrName(db, zWhere, pTrig->zName);
87542       }
87543     }
87544   }
87545   if( zWhere ){
87546     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
87547     sqlite3DbFree(pParse->db, zWhere);
87548     zWhere = zNew;
87549   }
87550   return zWhere;
87551 }
87552 
87553 /*
87554 ** Generate code to drop and reload the internal representation of table
87555 ** pTab from the database, including triggers and temporary triggers.
87556 ** Argument zName is the name of the table in the database schema at
87557 ** the time the generated code is executed. This can be different from
87558 ** pTab->zName if this function is being called to code part of an
87559 ** "ALTER TABLE RENAME TO" statement.
87560 */
87561 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
87562   Vdbe *v;
87563   char *zWhere;
87564   int iDb;                   /* Index of database containing pTab */
87565 #ifndef SQLITE_OMIT_TRIGGER
87566   Trigger *pTrig;
87567 #endif
87568 
87569   v = sqlite3GetVdbe(pParse);
87570   if( NEVER(v==0) ) return;
87571   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
87572   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
87573   assert( iDb>=0 );
87574 
87575 #ifndef SQLITE_OMIT_TRIGGER
87576   /* Drop any table triggers from the internal schema. */
87577   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
87578     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
87579     assert( iTrigDb==iDb || iTrigDb==1 );
87580     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
87581   }
87582 #endif
87583 
87584   /* Drop the table and index from the internal schema.  */
87585   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
87586 
87587   /* Reload the table, index and permanent trigger schemas. */
87588   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
87589   if( !zWhere ) return;
87590   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
87591 
87592 #ifndef SQLITE_OMIT_TRIGGER
87593   /* Now, if the table is not stored in the temp database, reload any temp
87594   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
87595   */
87596   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
87597     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
87598   }
87599 #endif
87600 }
87601 
87602 /*
87603 ** Parameter zName is the name of a table that is about to be altered
87604 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
87605 ** If the table is a system table, this function leaves an error message
87606 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
87607 **
87608 ** Or, if zName is not a system table, zero is returned.
87609 */
87610 static int isSystemTable(Parse *pParse, const char *zName){
87611   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
87612     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
87613     return 1;
87614   }
87615   return 0;
87616 }
87617 
87618 /*
87619 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
87620 ** command.
87621 */
87622 SQLITE_PRIVATE void sqlite3AlterRenameTable(
87623   Parse *pParse,            /* Parser context. */
87624   SrcList *pSrc,            /* The table to rename. */
87625   Token *pName              /* The new table name. */
87626 ){
87627   int iDb;                  /* Database that contains the table */
87628   char *zDb;                /* Name of database iDb */
87629   Table *pTab;              /* Table being renamed */
87630   char *zName = 0;          /* NULL-terminated version of pName */
87631   sqlite3 *db = pParse->db; /* Database connection */
87632   int nTabName;             /* Number of UTF-8 characters in zTabName */
87633   const char *zTabName;     /* Original name of the table */
87634   Vdbe *v;
87635 #ifndef SQLITE_OMIT_TRIGGER
87636   char *zWhere = 0;         /* Where clause to locate temp triggers */
87637 #endif
87638   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
87639   int savedDbFlags;         /* Saved value of db->flags */
87640 
87641   savedDbFlags = db->flags;
87642   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
87643   assert( pSrc->nSrc==1 );
87644   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
87645 
87646   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
87647   if( !pTab ) goto exit_rename_table;
87648   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
87649   zDb = db->aDb[iDb].zName;
87650   db->flags |= SQLITE_PreferBuiltin;
87651 
87652   /* Get a NULL terminated version of the new table name. */
87653   zName = sqlite3NameFromToken(db, pName);
87654   if( !zName ) goto exit_rename_table;
87655 
87656   /* Check that a table or index named 'zName' does not already exist
87657   ** in database iDb. If so, this is an error.
87658   */
87659   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
87660     sqlite3ErrorMsg(pParse,
87661         "there is already another table or index with this name: %s", zName);
87662     goto exit_rename_table;
87663   }
87664 
87665   /* Make sure it is not a system table being altered, or a reserved name
87666   ** that the table is being renamed to.
87667   */
87668   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
87669     goto exit_rename_table;
87670   }
87671   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
87672     exit_rename_table;
87673   }
87674 
87675 #ifndef SQLITE_OMIT_VIEW
87676   if( pTab->pSelect ){
87677     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
87678     goto exit_rename_table;
87679   }
87680 #endif
87681 
87682 #ifndef SQLITE_OMIT_AUTHORIZATION
87683   /* Invoke the authorization callback. */
87684   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
87685     goto exit_rename_table;
87686   }
87687 #endif
87688 
87689 #ifndef SQLITE_OMIT_VIRTUALTABLE
87690   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
87691     goto exit_rename_table;
87692   }
87693   if( IsVirtual(pTab) ){
87694     pVTab = sqlite3GetVTable(db, pTab);
87695     if( pVTab->pVtab->pModule->xRename==0 ){
87696       pVTab = 0;
87697     }
87698   }
87699 #endif
87700 
87701   /* Begin a transaction for database iDb.
87702   ** Then modify the schema cookie (since the ALTER TABLE modifies the
87703   ** schema). Open a statement transaction if the table is a virtual
87704   ** table.
87705   */
87706   v = sqlite3GetVdbe(pParse);
87707   if( v==0 ){
87708     goto exit_rename_table;
87709   }
87710   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
87711   sqlite3ChangeCookie(pParse, iDb);
87712 
87713   /* If this is a virtual table, invoke the xRename() function if
87714   ** one is defined. The xRename() callback will modify the names
87715   ** of any resources used by the v-table implementation (including other
87716   ** SQLite tables) that are identified by the name of the virtual table.
87717   */
87718 #ifndef SQLITE_OMIT_VIRTUALTABLE
87719   if( pVTab ){
87720     int i = ++pParse->nMem;
87721     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
87722     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
87723     sqlite3MayAbort(pParse);
87724   }
87725 #endif
87726 
87727   /* figure out how many UTF-8 characters are in zName */
87728   zTabName = pTab->zName;
87729   nTabName = sqlite3Utf8CharLen(zTabName, -1);
87730 
87731 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
87732   if( db->flags&SQLITE_ForeignKeys ){
87733     /* If foreign-key support is enabled, rewrite the CREATE TABLE
87734     ** statements corresponding to all child tables of foreign key constraints
87735     ** for which the renamed table is the parent table.  */
87736     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
87737       sqlite3NestedParse(pParse,
87738           "UPDATE \"%w\".%s SET "
87739               "sql = sqlite_rename_parent(sql, %Q, %Q) "
87740               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
87741       sqlite3DbFree(db, zWhere);
87742     }
87743   }
87744 #endif
87745 
87746   /* Modify the sqlite_master table to use the new table name. */
87747   sqlite3NestedParse(pParse,
87748       "UPDATE %Q.%s SET "
87749 #ifdef SQLITE_OMIT_TRIGGER
87750           "sql = sqlite_rename_table(sql, %Q), "
87751 #else
87752           "sql = CASE "
87753             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
87754             "ELSE sqlite_rename_table(sql, %Q) END, "
87755 #endif
87756           "tbl_name = %Q, "
87757           "name = CASE "
87758             "WHEN type='table' THEN %Q "
87759             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
87760              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
87761             "ELSE name END "
87762       "WHERE tbl_name=%Q COLLATE nocase AND "
87763           "(type='table' OR type='index' OR type='trigger');",
87764       zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
87765 #ifndef SQLITE_OMIT_TRIGGER
87766       zName,
87767 #endif
87768       zName, nTabName, zTabName
87769   );
87770 
87771 #ifndef SQLITE_OMIT_AUTOINCREMENT
87772   /* If the sqlite_sequence table exists in this database, then update
87773   ** it with the new table name.
87774   */
87775   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
87776     sqlite3NestedParse(pParse,
87777         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
87778         zDb, zName, pTab->zName);
87779   }
87780 #endif
87781 
87782 #ifndef SQLITE_OMIT_TRIGGER
87783   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
87784   ** table. Don't do this if the table being ALTERed is itself located in
87785   ** the temp database.
87786   */
87787   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
87788     sqlite3NestedParse(pParse,
87789         "UPDATE sqlite_temp_master SET "
87790             "sql = sqlite_rename_trigger(sql, %Q), "
87791             "tbl_name = %Q "
87792             "WHERE %s;", zName, zName, zWhere);
87793     sqlite3DbFree(db, zWhere);
87794   }
87795 #endif
87796 
87797 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
87798   if( db->flags&SQLITE_ForeignKeys ){
87799     FKey *p;
87800     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
87801       Table *pFrom = p->pFrom;
87802       if( pFrom!=pTab ){
87803         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
87804       }
87805     }
87806   }
87807 #endif
87808 
87809   /* Drop and reload the internal table schema. */
87810   reloadTableSchema(pParse, pTab, zName);
87811 
87812 exit_rename_table:
87813   sqlite3SrcListDelete(db, pSrc);
87814   sqlite3DbFree(db, zName);
87815   db->flags = savedDbFlags;
87816 }
87817 
87818 
87819 /*
87820 ** Generate code to make sure the file format number is at least minFormat.
87821 ** The generated code will increase the file format number if necessary.
87822 */
87823 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
87824   Vdbe *v;
87825   v = sqlite3GetVdbe(pParse);
87826   /* The VDBE should have been allocated before this routine is called.
87827   ** If that allocation failed, we would have quit before reaching this
87828   ** point */
87829   if( ALWAYS(v) ){
87830     int r1 = sqlite3GetTempReg(pParse);
87831     int r2 = sqlite3GetTempReg(pParse);
87832     int j1;
87833     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
87834     sqlite3VdbeUsesBtree(v, iDb);
87835     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
87836     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
87837     sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
87838     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
87839     sqlite3VdbeJumpHere(v, j1);
87840     sqlite3ReleaseTempReg(pParse, r1);
87841     sqlite3ReleaseTempReg(pParse, r2);
87842   }
87843 }
87844 
87845 /*
87846 ** This function is called after an "ALTER TABLE ... ADD" statement
87847 ** has been parsed. Argument pColDef contains the text of the new
87848 ** column definition.
87849 **
87850 ** The Table structure pParse->pNewTable was extended to include
87851 ** the new column during parsing.
87852 */
87853 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
87854   Table *pNew;              /* Copy of pParse->pNewTable */
87855   Table *pTab;              /* Table being altered */
87856   int iDb;                  /* Database number */
87857   const char *zDb;          /* Database name */
87858   const char *zTab;         /* Table name */
87859   char *zCol;               /* Null-terminated column definition */
87860   Column *pCol;             /* The new column */
87861   Expr *pDflt;              /* Default value for the new column */
87862   sqlite3 *db;              /* The database connection; */
87863 
87864   db = pParse->db;
87865   if( pParse->nErr || db->mallocFailed ) return;
87866   pNew = pParse->pNewTable;
87867   assert( pNew );
87868 
87869   assert( sqlite3BtreeHoldsAllMutexes(db) );
87870   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
87871   zDb = db->aDb[iDb].zName;
87872   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
87873   pCol = &pNew->aCol[pNew->nCol-1];
87874   pDflt = pCol->pDflt;
87875   pTab = sqlite3FindTable(db, zTab, zDb);
87876   assert( pTab );
87877 
87878 #ifndef SQLITE_OMIT_AUTHORIZATION
87879   /* Invoke the authorization callback. */
87880   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
87881     return;
87882   }
87883 #endif
87884 
87885   /* If the default value for the new column was specified with a
87886   ** literal NULL, then set pDflt to 0. This simplifies checking
87887   ** for an SQL NULL default below.
87888   */
87889   if( pDflt && pDflt->op==TK_NULL ){
87890     pDflt = 0;
87891   }
87892 
87893   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
87894   ** If there is a NOT NULL constraint, then the default value for the
87895   ** column must not be NULL.
87896   */
87897   if( pCol->colFlags & COLFLAG_PRIMKEY ){
87898     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
87899     return;
87900   }
87901   if( pNew->pIndex ){
87902     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
87903     return;
87904   }
87905   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
87906     sqlite3ErrorMsg(pParse,
87907         "Cannot add a REFERENCES column with non-NULL default value");
87908     return;
87909   }
87910   if( pCol->notNull && !pDflt ){
87911     sqlite3ErrorMsg(pParse,
87912         "Cannot add a NOT NULL column with default value NULL");
87913     return;
87914   }
87915 
87916   /* Ensure the default expression is something that sqlite3ValueFromExpr()
87917   ** can handle (i.e. not CURRENT_TIME etc.)
87918   */
87919   if( pDflt ){
87920     sqlite3_value *pVal = 0;
87921     int rc;
87922     rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal);
87923     assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
87924     if( rc!=SQLITE_OK ){
87925       db->mallocFailed = 1;
87926       return;
87927     }
87928     if( !pVal ){
87929       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
87930       return;
87931     }
87932     sqlite3ValueFree(pVal);
87933   }
87934 
87935   /* Modify the CREATE TABLE statement. */
87936   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
87937   if( zCol ){
87938     char *zEnd = &zCol[pColDef->n-1];
87939     int savedDbFlags = db->flags;
87940     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
87941       *zEnd-- = '\0';
87942     }
87943     db->flags |= SQLITE_PreferBuiltin;
87944     sqlite3NestedParse(pParse,
87945         "UPDATE \"%w\".%s SET "
87946           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
87947         "WHERE type = 'table' AND name = %Q",
87948       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
87949       zTab
87950     );
87951     sqlite3DbFree(db, zCol);
87952     db->flags = savedDbFlags;
87953   }
87954 
87955   /* If the default value of the new column is NULL, then set the file
87956   ** format to 2. If the default value of the new column is not NULL,
87957   ** the file format becomes 3.
87958   */
87959   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
87960 
87961   /* Reload the schema of the modified table. */
87962   reloadTableSchema(pParse, pTab, pTab->zName);
87963 }
87964 
87965 /*
87966 ** This function is called by the parser after the table-name in
87967 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
87968 ** pSrc is the full-name of the table being altered.
87969 **
87970 ** This routine makes a (partial) copy of the Table structure
87971 ** for the table being altered and sets Parse.pNewTable to point
87972 ** to it. Routines called by the parser as the column definition
87973 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
87974 ** the copy. The copy of the Table structure is deleted by tokenize.c
87975 ** after parsing is finished.
87976 **
87977 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
87978 ** coding the "ALTER TABLE ... ADD" statement.
87979 */
87980 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
87981   Table *pNew;
87982   Table *pTab;
87983   Vdbe *v;
87984   int iDb;
87985   int i;
87986   int nAlloc;
87987   sqlite3 *db = pParse->db;
87988 
87989   /* Look up the table being altered. */
87990   assert( pParse->pNewTable==0 );
87991   assert( sqlite3BtreeHoldsAllMutexes(db) );
87992   if( db->mallocFailed ) goto exit_begin_add_column;
87993   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
87994   if( !pTab ) goto exit_begin_add_column;
87995 
87996 #ifndef SQLITE_OMIT_VIRTUALTABLE
87997   if( IsVirtual(pTab) ){
87998     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
87999     goto exit_begin_add_column;
88000   }
88001 #endif
88002 
88003   /* Make sure this is not an attempt to ALTER a view. */
88004   if( pTab->pSelect ){
88005     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
88006     goto exit_begin_add_column;
88007   }
88008   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
88009     goto exit_begin_add_column;
88010   }
88011 
88012   assert( pTab->addColOffset>0 );
88013   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
88014 
88015   /* Put a copy of the Table struct in Parse.pNewTable for the
88016   ** sqlite3AddColumn() function and friends to modify.  But modify
88017   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
88018   ** prefix, we insure that the name will not collide with an existing
88019   ** table because user table are not allowed to have the "sqlite_"
88020   ** prefix on their name.
88021   */
88022   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
88023   if( !pNew ) goto exit_begin_add_column;
88024   pParse->pNewTable = pNew;
88025   pNew->nRef = 1;
88026   pNew->nCol = pTab->nCol;
88027   assert( pNew->nCol>0 );
88028   nAlloc = (((pNew->nCol-1)/8)*8)+8;
88029   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
88030   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
88031   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
88032   if( !pNew->aCol || !pNew->zName ){
88033     db->mallocFailed = 1;
88034     goto exit_begin_add_column;
88035   }
88036   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
88037   for(i=0; i<pNew->nCol; i++){
88038     Column *pCol = &pNew->aCol[i];
88039     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
88040     pCol->zColl = 0;
88041     pCol->zType = 0;
88042     pCol->pDflt = 0;
88043     pCol->zDflt = 0;
88044   }
88045   pNew->pSchema = db->aDb[iDb].pSchema;
88046   pNew->addColOffset = pTab->addColOffset;
88047   pNew->nRef = 1;
88048 
88049   /* Begin a transaction and increment the schema cookie.  */
88050   sqlite3BeginWriteOperation(pParse, 0, iDb);
88051   v = sqlite3GetVdbe(pParse);
88052   if( !v ) goto exit_begin_add_column;
88053   sqlite3ChangeCookie(pParse, iDb);
88054 
88055 exit_begin_add_column:
88056   sqlite3SrcListDelete(db, pSrc);
88057   return;
88058 }
88059 #endif  /* SQLITE_ALTER_TABLE */
88060 
88061 /************** End of alter.c ***********************************************/
88062 /************** Begin file analyze.c *****************************************/
88063 /*
88064 ** 2005-07-08
88065 **
88066 ** The author disclaims copyright to this source code.  In place of
88067 ** a legal notice, here is a blessing:
88068 **
88069 **    May you do good and not evil.
88070 **    May you find forgiveness for yourself and forgive others.
88071 **    May you share freely, never taking more than you give.
88072 **
88073 *************************************************************************
88074 ** This file contains code associated with the ANALYZE command.
88075 **
88076 ** The ANALYZE command gather statistics about the content of tables
88077 ** and indices.  These statistics are made available to the query planner
88078 ** to help it make better decisions about how to perform queries.
88079 **
88080 ** The following system tables are or have been supported:
88081 **
88082 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
88083 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
88084 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
88085 **    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
88086 **
88087 ** Additional tables might be added in future releases of SQLite.
88088 ** The sqlite_stat2 table is not created or used unless the SQLite version
88089 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
88090 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
88091 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
88092 ** created and used by SQLite versions 3.7.9 and later and with
88093 ** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
88094 ** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
88095 ** version of sqlite_stat3 and is only available when compiled with
88096 ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
88097 ** not possible to enable both STAT3 and STAT4 at the same time.  If they
88098 ** are both enabled, then STAT4 takes precedence.
88099 **
88100 ** For most applications, sqlite_stat1 provides all the statistics required
88101 ** for the query planner to make good choices.
88102 **
88103 ** Format of sqlite_stat1:
88104 **
88105 ** There is normally one row per index, with the index identified by the
88106 ** name in the idx column.  The tbl column is the name of the table to
88107 ** which the index belongs.  In each such row, the stat column will be
88108 ** a string consisting of a list of integers.  The first integer in this
88109 ** list is the number of rows in the index.  (This is the same as the
88110 ** number of rows in the table, except for partial indices.)  The second
88111 ** integer is the average number of rows in the index that have the same
88112 ** value in the first column of the index.  The third integer is the average
88113 ** number of rows in the index that have the same value for the first two
88114 ** columns.  The N-th integer (for N>1) is the average number of rows in
88115 ** the index which have the same value for the first N-1 columns.  For
88116 ** a K-column index, there will be K+1 integers in the stat column.  If
88117 ** the index is unique, then the last integer will be 1.
88118 **
88119 ** The list of integers in the stat column can optionally be followed
88120 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
88121 ** must be separated from the last integer by a single space.  If the
88122 ** "unordered" keyword is present, then the query planner assumes that
88123 ** the index is unordered and will not use the index for a range query.
88124 **
88125 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
88126 ** column contains a single integer which is the (estimated) number of
88127 ** rows in the table identified by sqlite_stat1.tbl.
88128 **
88129 ** Format of sqlite_stat2:
88130 **
88131 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
88132 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
88133 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
88134 ** about the distribution of keys within an index.  The index is identified by
88135 ** the "idx" column and the "tbl" column is the name of the table to which
88136 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
88137 ** table for each index.
88138 **
88139 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
88140 ** inclusive are samples of the left-most key value in the index taken at
88141 ** evenly spaced points along the index.  Let the number of samples be S
88142 ** (10 in the standard build) and let C be the number of rows in the index.
88143 ** Then the sampled rows are given by:
88144 **
88145 **     rownumber = (i*C*2 + C)/(S*2)
88146 **
88147 ** For i between 0 and S-1.  Conceptually, the index space is divided into
88148 ** S uniform buckets and the samples are the middle row from each bucket.
88149 **
88150 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
88151 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
88152 ** writes the sqlite_stat2 table.  This version of SQLite only supports
88153 ** sqlite_stat3.
88154 **
88155 ** Format for sqlite_stat3:
88156 **
88157 ** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
88158 ** sqlite_stat4 format will be described first.  Further information
88159 ** about sqlite_stat3 follows the sqlite_stat4 description.
88160 **
88161 ** Format for sqlite_stat4:
88162 **
88163 ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
88164 ** to aid the query planner in choosing good indices based on the values
88165 ** that indexed columns are compared against in the WHERE clauses of
88166 ** queries.
88167 **
88168 ** The sqlite_stat4 table contains multiple entries for each index.
88169 ** The idx column names the index and the tbl column is the table of the
88170 ** index.  If the idx and tbl columns are the same, then the sample is
88171 ** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
88172 ** binary encoding of a key from the index.  The nEq column is a
88173 ** list of integers.  The first integer is the approximate number
88174 ** of entries in the index whose left-most column exactly matches
88175 ** the left-most column of the sample.  The second integer in nEq
88176 ** is the approximate number of entries in the index where the
88177 ** first two columns match the first two columns of the sample.
88178 ** And so forth.  nLt is another list of integers that show the approximate
88179 ** number of entries that are strictly less than the sample.  The first
88180 ** integer in nLt contains the number of entries in the index where the
88181 ** left-most column is less than the left-most column of the sample.
88182 ** The K-th integer in the nLt entry is the number of index entries
88183 ** where the first K columns are less than the first K columns of the
88184 ** sample.  The nDLt column is like nLt except that it contains the
88185 ** number of distinct entries in the index that are less than the
88186 ** sample.
88187 **
88188 ** There can be an arbitrary number of sqlite_stat4 entries per index.
88189 ** The ANALYZE command will typically generate sqlite_stat4 tables
88190 ** that contain between 10 and 40 samples which are distributed across
88191 ** the key space, though not uniformly, and which include samples with
88192 ** large nEq values.
88193 **
88194 ** Format for sqlite_stat3 redux:
88195 **
88196 ** The sqlite_stat3 table is like sqlite_stat4 except that it only
88197 ** looks at the left-most column of the index.  The sqlite_stat3.sample
88198 ** column contains the actual value of the left-most column instead
88199 ** of a blob encoding of the complete index key as is found in
88200 ** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
88201 ** all contain just a single integer which is the same as the first
88202 ** integer in the equivalent columns in sqlite_stat4.
88203 */
88204 #ifndef SQLITE_OMIT_ANALYZE
88205 
88206 #if defined(SQLITE_ENABLE_STAT4)
88207 # define IsStat4     1
88208 # define IsStat3     0
88209 #elif defined(SQLITE_ENABLE_STAT3)
88210 # define IsStat4     0
88211 # define IsStat3     1
88212 #else
88213 # define IsStat4     0
88214 # define IsStat3     0
88215 # undef SQLITE_STAT4_SAMPLES
88216 # define SQLITE_STAT4_SAMPLES 1
88217 #endif
88218 #define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
88219 
88220 /*
88221 ** This routine generates code that opens the sqlite_statN tables.
88222 ** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
88223 ** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
88224 ** appropriate compile-time options are provided.
88225 **
88226 ** If the sqlite_statN tables do not previously exist, it is created.
88227 **
88228 ** Argument zWhere may be a pointer to a buffer containing a table name,
88229 ** or it may be a NULL pointer. If it is not NULL, then all entries in
88230 ** the sqlite_statN tables associated with the named table are deleted.
88231 ** If zWhere==0, then code is generated to delete all stat table entries.
88232 */
88233 static void openStatTable(
88234   Parse *pParse,          /* Parsing context */
88235   int iDb,                /* The database we are looking in */
88236   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
88237   const char *zWhere,     /* Delete entries for this table or index */
88238   const char *zWhereType  /* Either "tbl" or "idx" */
88239 ){
88240   static const struct {
88241     const char *zName;
88242     const char *zCols;
88243   } aTable[] = {
88244     { "sqlite_stat1", "tbl,idx,stat" },
88245 #if defined(SQLITE_ENABLE_STAT4)
88246     { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
88247     { "sqlite_stat3", 0 },
88248 #elif defined(SQLITE_ENABLE_STAT3)
88249     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
88250     { "sqlite_stat4", 0 },
88251 #else
88252     { "sqlite_stat3", 0 },
88253     { "sqlite_stat4", 0 },
88254 #endif
88255   };
88256   int i;
88257   sqlite3 *db = pParse->db;
88258   Db *pDb;
88259   Vdbe *v = sqlite3GetVdbe(pParse);
88260   int aRoot[ArraySize(aTable)];
88261   u8 aCreateTbl[ArraySize(aTable)];
88262 
88263   if( v==0 ) return;
88264   assert( sqlite3BtreeHoldsAllMutexes(db) );
88265   assert( sqlite3VdbeDb(v)==db );
88266   pDb = &db->aDb[iDb];
88267 
88268   /* Create new statistic tables if they do not exist, or clear them
88269   ** if they do already exist.
88270   */
88271   for(i=0; i<ArraySize(aTable); i++){
88272     const char *zTab = aTable[i].zName;
88273     Table *pStat;
88274     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
88275       if( aTable[i].zCols ){
88276         /* The sqlite_statN table does not exist. Create it. Note that a
88277         ** side-effect of the CREATE TABLE statement is to leave the rootpage
88278         ** of the new table in register pParse->regRoot. This is important
88279         ** because the OpenWrite opcode below will be needing it. */
88280         sqlite3NestedParse(pParse,
88281             "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
88282         );
88283         aRoot[i] = pParse->regRoot;
88284         aCreateTbl[i] = OPFLAG_P2ISREG;
88285       }
88286     }else{
88287       /* The table already exists. If zWhere is not NULL, delete all entries
88288       ** associated with the table zWhere. If zWhere is NULL, delete the
88289       ** entire contents of the table. */
88290       aRoot[i] = pStat->tnum;
88291       aCreateTbl[i] = 0;
88292       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
88293       if( zWhere ){
88294         sqlite3NestedParse(pParse,
88295            "DELETE FROM %Q.%s WHERE %s=%Q",
88296            pDb->zName, zTab, zWhereType, zWhere
88297         );
88298       }else{
88299         /* The sqlite_stat[134] table already exists.  Delete all rows. */
88300         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
88301       }
88302     }
88303   }
88304 
88305   /* Open the sqlite_stat[134] tables for writing. */
88306   for(i=0; aTable[i].zCols; i++){
88307     assert( i<ArraySize(aTable) );
88308     sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
88309     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
88310     VdbeComment((v, aTable[i].zName));
88311   }
88312 }
88313 
88314 /*
88315 ** Recommended number of samples for sqlite_stat4
88316 */
88317 #ifndef SQLITE_STAT4_SAMPLES
88318 # define SQLITE_STAT4_SAMPLES 24
88319 #endif
88320 
88321 /*
88322 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
88323 ** share an instance of the following structure to hold their state
88324 ** information.
88325 */
88326 typedef struct Stat4Accum Stat4Accum;
88327 typedef struct Stat4Sample Stat4Sample;
88328 struct Stat4Sample {
88329   tRowcnt *anEq;                  /* sqlite_stat4.nEq */
88330   tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
88331 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88332   tRowcnt *anLt;                  /* sqlite_stat4.nLt */
88333   union {
88334     i64 iRowid;                     /* Rowid in main table of the key */
88335     u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
88336   } u;
88337   u32 nRowid;                     /* Sizeof aRowid[] */
88338   u8 isPSample;                   /* True if a periodic sample */
88339   int iCol;                       /* If !isPSample, the reason for inclusion */
88340   u32 iHash;                      /* Tiebreaker hash */
88341 #endif
88342 };
88343 struct Stat4Accum {
88344   tRowcnt nRow;             /* Number of rows in the entire table */
88345   tRowcnt nPSample;         /* How often to do a periodic sample */
88346   int nCol;                 /* Number of columns in index + pk/rowid */
88347   int nKeyCol;              /* Number of index columns w/o the pk/rowid */
88348   int mxSample;             /* Maximum number of samples to accumulate */
88349   Stat4Sample current;      /* Current row as a Stat4Sample */
88350   u32 iPrn;                 /* Pseudo-random number used for sampling */
88351   Stat4Sample *aBest;       /* Array of nCol best samples */
88352   int iMin;                 /* Index in a[] of entry with minimum score */
88353   int nSample;              /* Current number of samples */
88354   int iGet;                 /* Index of current sample accessed by stat_get() */
88355   Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
88356   sqlite3 *db;              /* Database connection, for malloc() */
88357 };
88358 
88359 /* Reclaim memory used by a Stat4Sample
88360 */
88361 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88362 static void sampleClear(sqlite3 *db, Stat4Sample *p){
88363   assert( db!=0 );
88364   if( p->nRowid ){
88365     sqlite3DbFree(db, p->u.aRowid);
88366     p->nRowid = 0;
88367   }
88368 }
88369 #endif
88370 
88371 /* Initialize the BLOB value of a ROWID
88372 */
88373 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88374 static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
88375   assert( db!=0 );
88376   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
88377   p->u.aRowid = sqlite3DbMallocRaw(db, n);
88378   if( p->u.aRowid ){
88379     p->nRowid = n;
88380     memcpy(p->u.aRowid, pData, n);
88381   }else{
88382     p->nRowid = 0;
88383   }
88384 }
88385 #endif
88386 
88387 /* Initialize the INTEGER value of a ROWID.
88388 */
88389 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88390 static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
88391   assert( db!=0 );
88392   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
88393   p->nRowid = 0;
88394   p->u.iRowid = iRowid;
88395 }
88396 #endif
88397 
88398 
88399 /*
88400 ** Copy the contents of object (*pFrom) into (*pTo).
88401 */
88402 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88403 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
88404   pTo->isPSample = pFrom->isPSample;
88405   pTo->iCol = pFrom->iCol;
88406   pTo->iHash = pFrom->iHash;
88407   memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
88408   memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
88409   memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
88410   if( pFrom->nRowid ){
88411     sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
88412   }else{
88413     sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
88414   }
88415 }
88416 #endif
88417 
88418 /*
88419 ** Reclaim all memory of a Stat4Accum structure.
88420 */
88421 static void stat4Destructor(void *pOld){
88422   Stat4Accum *p = (Stat4Accum*)pOld;
88423 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88424   int i;
88425   for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
88426   for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
88427   sampleClear(p->db, &p->current);
88428 #endif
88429   sqlite3DbFree(p->db, p);
88430 }
88431 
88432 /*
88433 ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
88434 ** are:
88435 **     N:    The number of columns in the index including the rowid/pk (note 1)
88436 **     K:    The number of columns in the index excluding the rowid/pk.
88437 **     C:    The number of rows in the index (note 2)
88438 **
88439 ** Note 1:  In the special case of the covering index that implements a
88440 ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
88441 ** total number of columns in the table.
88442 **
88443 ** Note 2:  C is only used for STAT3 and STAT4.
88444 **
88445 ** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
88446 ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
88447 ** PRIMARY KEY of the table.  The covering index that implements the
88448 ** original WITHOUT ROWID table as N==K as a special case.
88449 **
88450 ** This routine allocates the Stat4Accum object in heap memory. The return
88451 ** value is a pointer to the Stat4Accum object.  The datatype of the
88452 ** return value is BLOB, but it is really just a pointer to the Stat4Accum
88453 ** object.
88454 */
88455 static void statInit(
88456   sqlite3_context *context,
88457   int argc,
88458   sqlite3_value **argv
88459 ){
88460   Stat4Accum *p;
88461   int nCol;                       /* Number of columns in index being sampled */
88462   int nKeyCol;                    /* Number of key columns */
88463   int nColUp;                     /* nCol rounded up for alignment */
88464   int n;                          /* Bytes of space to allocate */
88465   sqlite3 *db;                    /* Database connection */
88466 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88467   int mxSample = SQLITE_STAT4_SAMPLES;
88468 #endif
88469 
88470   /* Decode the three function arguments */
88471   UNUSED_PARAMETER(argc);
88472   nCol = sqlite3_value_int(argv[0]);
88473   assert( nCol>0 );
88474   nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
88475   nKeyCol = sqlite3_value_int(argv[1]);
88476   assert( nKeyCol<=nCol );
88477   assert( nKeyCol>0 );
88478 
88479   /* Allocate the space required for the Stat4Accum object */
88480   n = sizeof(*p)
88481     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
88482     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
88483 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88484     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
88485     + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
88486     + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
88487 #endif
88488   ;
88489   db = sqlite3_context_db_handle(context);
88490   p = sqlite3DbMallocZero(db, n);
88491   if( p==0 ){
88492     sqlite3_result_error_nomem(context);
88493     return;
88494   }
88495 
88496   p->db = db;
88497   p->nRow = 0;
88498   p->nCol = nCol;
88499   p->nKeyCol = nKeyCol;
88500   p->current.anDLt = (tRowcnt*)&p[1];
88501   p->current.anEq = &p->current.anDLt[nColUp];
88502 
88503 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88504   {
88505     u8 *pSpace;                     /* Allocated space not yet assigned */
88506     int i;                          /* Used to iterate through p->aSample[] */
88507 
88508     p->iGet = -1;
88509     p->mxSample = mxSample;
88510     p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
88511     p->current.anLt = &p->current.anEq[nColUp];
88512     p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
88513 
88514     /* Set up the Stat4Accum.a[] and aBest[] arrays */
88515     p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
88516     p->aBest = &p->a[mxSample];
88517     pSpace = (u8*)(&p->a[mxSample+nCol]);
88518     for(i=0; i<(mxSample+nCol); i++){
88519       p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
88520       p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
88521       p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
88522     }
88523     assert( (pSpace - (u8*)p)==n );
88524 
88525     for(i=0; i<nCol; i++){
88526       p->aBest[i].iCol = i;
88527     }
88528   }
88529 #endif
88530 
88531   /* Return a pointer to the allocated object to the caller.  Note that
88532   ** only the pointer (the 2nd parameter) matters.  The size of the object
88533   ** (given by the 3rd parameter) is never used and can be any positive
88534   ** value. */
88535   sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
88536 }
88537 static const FuncDef statInitFuncdef = {
88538   2+IsStat34,      /* nArg */
88539   SQLITE_UTF8,     /* funcFlags */
88540   0,               /* pUserData */
88541   0,               /* pNext */
88542   statInit,        /* xFunc */
88543   0,               /* xStep */
88544   0,               /* xFinalize */
88545   "stat_init",     /* zName */
88546   0,               /* pHash */
88547   0                /* pDestructor */
88548 };
88549 
88550 #ifdef SQLITE_ENABLE_STAT4
88551 /*
88552 ** pNew and pOld are both candidate non-periodic samples selected for
88553 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
88554 ** considering only any trailing columns and the sample hash value, this
88555 ** function returns true if sample pNew is to be preferred over pOld.
88556 ** In other words, if we assume that the cardinalities of the selected
88557 ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
88558 **
88559 ** This function assumes that for each argument sample, the contents of
88560 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
88561 */
88562 static int sampleIsBetterPost(
88563   Stat4Accum *pAccum,
88564   Stat4Sample *pNew,
88565   Stat4Sample *pOld
88566 ){
88567   int nCol = pAccum->nCol;
88568   int i;
88569   assert( pNew->iCol==pOld->iCol );
88570   for(i=pNew->iCol+1; i<nCol; i++){
88571     if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
88572     if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
88573   }
88574   if( pNew->iHash>pOld->iHash ) return 1;
88575   return 0;
88576 }
88577 #endif
88578 
88579 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88580 /*
88581 ** Return true if pNew is to be preferred over pOld.
88582 **
88583 ** This function assumes that for each argument sample, the contents of
88584 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
88585 */
88586 static int sampleIsBetter(
88587   Stat4Accum *pAccum,
88588   Stat4Sample *pNew,
88589   Stat4Sample *pOld
88590 ){
88591   tRowcnt nEqNew = pNew->anEq[pNew->iCol];
88592   tRowcnt nEqOld = pOld->anEq[pOld->iCol];
88593 
88594   assert( pOld->isPSample==0 && pNew->isPSample==0 );
88595   assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
88596 
88597   if( (nEqNew>nEqOld) ) return 1;
88598 #ifdef SQLITE_ENABLE_STAT4
88599   if( nEqNew==nEqOld ){
88600     if( pNew->iCol<pOld->iCol ) return 1;
88601     return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
88602   }
88603   return 0;
88604 #else
88605   return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
88606 #endif
88607 }
88608 
88609 /*
88610 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
88611 ** remove the least desirable sample from p->a[] to make room.
88612 */
88613 static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
88614   Stat4Sample *pSample = 0;
88615   int i;
88616 
88617   assert( IsStat4 || nEqZero==0 );
88618 
88619 #ifdef SQLITE_ENABLE_STAT4
88620   if( pNew->isPSample==0 ){
88621     Stat4Sample *pUpgrade = 0;
88622     assert( pNew->anEq[pNew->iCol]>0 );
88623 
88624     /* This sample is being added because the prefix that ends in column
88625     ** iCol occurs many times in the table. However, if we have already
88626     ** added a sample that shares this prefix, there is no need to add
88627     ** this one. Instead, upgrade the priority of the highest priority
88628     ** existing sample that shares this prefix.  */
88629     for(i=p->nSample-1; i>=0; i--){
88630       Stat4Sample *pOld = &p->a[i];
88631       if( pOld->anEq[pNew->iCol]==0 ){
88632         if( pOld->isPSample ) return;
88633         assert( pOld->iCol>pNew->iCol );
88634         assert( sampleIsBetter(p, pNew, pOld) );
88635         if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
88636           pUpgrade = pOld;
88637         }
88638       }
88639     }
88640     if( pUpgrade ){
88641       pUpgrade->iCol = pNew->iCol;
88642       pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
88643       goto find_new_min;
88644     }
88645   }
88646 #endif
88647 
88648   /* If necessary, remove sample iMin to make room for the new sample. */
88649   if( p->nSample>=p->mxSample ){
88650     Stat4Sample *pMin = &p->a[p->iMin];
88651     tRowcnt *anEq = pMin->anEq;
88652     tRowcnt *anLt = pMin->anLt;
88653     tRowcnt *anDLt = pMin->anDLt;
88654     sampleClear(p->db, pMin);
88655     memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
88656     pSample = &p->a[p->nSample-1];
88657     pSample->nRowid = 0;
88658     pSample->anEq = anEq;
88659     pSample->anDLt = anDLt;
88660     pSample->anLt = anLt;
88661     p->nSample = p->mxSample-1;
88662   }
88663 
88664   /* The "rows less-than" for the rowid column must be greater than that
88665   ** for the last sample in the p->a[] array. Otherwise, the samples would
88666   ** be out of order. */
88667 #ifdef SQLITE_ENABLE_STAT4
88668   assert( p->nSample==0
88669        || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
88670 #endif
88671 
88672   /* Insert the new sample */
88673   pSample = &p->a[p->nSample];
88674   sampleCopy(p, pSample, pNew);
88675   p->nSample++;
88676 
88677   /* Zero the first nEqZero entries in the anEq[] array. */
88678   memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
88679 
88680 #ifdef SQLITE_ENABLE_STAT4
88681  find_new_min:
88682 #endif
88683   if( p->nSample>=p->mxSample ){
88684     int iMin = -1;
88685     for(i=0; i<p->mxSample; i++){
88686       if( p->a[i].isPSample ) continue;
88687       if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
88688         iMin = i;
88689       }
88690     }
88691     assert( iMin>=0 );
88692     p->iMin = iMin;
88693   }
88694 }
88695 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
88696 
88697 /*
88698 ** Field iChng of the index being scanned has changed. So at this point
88699 ** p->current contains a sample that reflects the previous row of the
88700 ** index. The value of anEq[iChng] and subsequent anEq[] elements are
88701 ** correct at this point.
88702 */
88703 static void samplePushPrevious(Stat4Accum *p, int iChng){
88704 #ifdef SQLITE_ENABLE_STAT4
88705   int i;
88706 
88707   /* Check if any samples from the aBest[] array should be pushed
88708   ** into IndexSample.a[] at this point.  */
88709   for(i=(p->nCol-2); i>=iChng; i--){
88710     Stat4Sample *pBest = &p->aBest[i];
88711     pBest->anEq[i] = p->current.anEq[i];
88712     if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
88713       sampleInsert(p, pBest, i);
88714     }
88715   }
88716 
88717   /* Update the anEq[] fields of any samples already collected. */
88718   for(i=p->nSample-1; i>=0; i--){
88719     int j;
88720     for(j=iChng; j<p->nCol; j++){
88721       if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
88722     }
88723   }
88724 #endif
88725 
88726 #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
88727   if( iChng==0 ){
88728     tRowcnt nLt = p->current.anLt[0];
88729     tRowcnt nEq = p->current.anEq[0];
88730 
88731     /* Check if this is to be a periodic sample. If so, add it. */
88732     if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
88733       p->current.isPSample = 1;
88734       sampleInsert(p, &p->current, 0);
88735       p->current.isPSample = 0;
88736     }else
88737 
88738     /* Or if it is a non-periodic sample. Add it in this case too. */
88739     if( p->nSample<p->mxSample
88740      || sampleIsBetter(p, &p->current, &p->a[p->iMin])
88741     ){
88742       sampleInsert(p, &p->current, 0);
88743     }
88744   }
88745 #endif
88746 
88747 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
88748   UNUSED_PARAMETER( p );
88749   UNUSED_PARAMETER( iChng );
88750 #endif
88751 }
88752 
88753 /*
88754 ** Implementation of the stat_push SQL function:  stat_push(P,C,R)
88755 ** Arguments:
88756 **
88757 **    P     Pointer to the Stat4Accum object created by stat_init()
88758 **    C     Index of left-most column to differ from previous row
88759 **    R     Rowid for the current row.  Might be a key record for
88760 **          WITHOUT ROWID tables.
88761 **
88762 ** This SQL function always returns NULL.  It's purpose it to accumulate
88763 ** statistical data and/or samples in the Stat4Accum object about the
88764 ** index being analyzed.  The stat_get() SQL function will later be used to
88765 ** extract relevant information for constructing the sqlite_statN tables.
88766 **
88767 ** The R parameter is only used for STAT3 and STAT4
88768 */
88769 static void statPush(
88770   sqlite3_context *context,
88771   int argc,
88772   sqlite3_value **argv
88773 ){
88774   int i;
88775 
88776   /* The three function arguments */
88777   Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
88778   int iChng = sqlite3_value_int(argv[1]);
88779 
88780   UNUSED_PARAMETER( argc );
88781   UNUSED_PARAMETER( context );
88782   assert( p->nCol>0 );
88783   assert( iChng<p->nCol );
88784 
88785   if( p->nRow==0 ){
88786     /* This is the first call to this function. Do initialization. */
88787     for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
88788   }else{
88789     /* Second and subsequent calls get processed here */
88790     samplePushPrevious(p, iChng);
88791 
88792     /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
88793     ** to the current row of the index. */
88794     for(i=0; i<iChng; i++){
88795       p->current.anEq[i]++;
88796     }
88797     for(i=iChng; i<p->nCol; i++){
88798       p->current.anDLt[i]++;
88799 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88800       p->current.anLt[i] += p->current.anEq[i];
88801 #endif
88802       p->current.anEq[i] = 1;
88803     }
88804   }
88805   p->nRow++;
88806 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88807   if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
88808     sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
88809   }else{
88810     sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
88811                                        sqlite3_value_blob(argv[2]));
88812   }
88813   p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
88814 #endif
88815 
88816 #ifdef SQLITE_ENABLE_STAT4
88817   {
88818     tRowcnt nLt = p->current.anLt[p->nCol-1];
88819 
88820     /* Check if this is to be a periodic sample. If so, add it. */
88821     if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
88822       p->current.isPSample = 1;
88823       p->current.iCol = 0;
88824       sampleInsert(p, &p->current, p->nCol-1);
88825       p->current.isPSample = 0;
88826     }
88827 
88828     /* Update the aBest[] array. */
88829     for(i=0; i<(p->nCol-1); i++){
88830       p->current.iCol = i;
88831       if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
88832         sampleCopy(p, &p->aBest[i], &p->current);
88833       }
88834     }
88835   }
88836 #endif
88837 }
88838 static const FuncDef statPushFuncdef = {
88839   2+IsStat34,      /* nArg */
88840   SQLITE_UTF8,     /* funcFlags */
88841   0,               /* pUserData */
88842   0,               /* pNext */
88843   statPush,        /* xFunc */
88844   0,               /* xStep */
88845   0,               /* xFinalize */
88846   "stat_push",     /* zName */
88847   0,               /* pHash */
88848   0                /* pDestructor */
88849 };
88850 
88851 #define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
88852 #define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
88853 #define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
88854 #define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
88855 #define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
88856 
88857 /*
88858 ** Implementation of the stat_get(P,J) SQL function.  This routine is
88859 ** used to query statistical information that has been gathered into
88860 ** the Stat4Accum object by prior calls to stat_push().  The P parameter
88861 ** has type BLOB but it is really just a pointer to the Stat4Accum object.
88862 ** The content to returned is determined by the parameter J
88863 ** which is one of the STAT_GET_xxxx values defined above.
88864 **
88865 ** If neither STAT3 nor STAT4 are enabled, then J is always
88866 ** STAT_GET_STAT1 and is hence omitted and this routine becomes
88867 ** a one-parameter function, stat_get(P), that always returns the
88868 ** stat1 table entry information.
88869 */
88870 static void statGet(
88871   sqlite3_context *context,
88872   int argc,
88873   sqlite3_value **argv
88874 ){
88875   Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
88876 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88877   /* STAT3 and STAT4 have a parameter on this routine. */
88878   int eCall = sqlite3_value_int(argv[1]);
88879   assert( argc==2 );
88880   assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
88881        || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
88882        || eCall==STAT_GET_NDLT
88883   );
88884   if( eCall==STAT_GET_STAT1 )
88885 #else
88886   assert( argc==1 );
88887 #endif
88888   {
88889     /* Return the value to store in the "stat" column of the sqlite_stat1
88890     ** table for this index.
88891     **
88892     ** The value is a string composed of a list of integers describing
88893     ** the index. The first integer in the list is the total number of
88894     ** entries in the index. There is one additional integer in the list
88895     ** for each indexed column. This additional integer is an estimate of
88896     ** the number of rows matched by a stabbing query on the index using
88897     ** a key with the corresponding number of fields. In other words,
88898     ** if the index is on columns (a,b) and the sqlite_stat1 value is
88899     ** "100 10 2", then SQLite estimates that:
88900     **
88901     **   * the index contains 100 rows,
88902     **   * "WHERE a=?" matches 10 rows, and
88903     **   * "WHERE a=? AND b=?" matches 2 rows.
88904     **
88905     ** If D is the count of distinct values and K is the total number of
88906     ** rows, then each estimate is computed as:
88907     **
88908     **        I = (K+D-1)/D
88909     */
88910     char *z;
88911     int i;
88912 
88913     char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
88914     if( zRet==0 ){
88915       sqlite3_result_error_nomem(context);
88916       return;
88917     }
88918 
88919     sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
88920     z = zRet + sqlite3Strlen30(zRet);
88921     for(i=0; i<p->nKeyCol; i++){
88922       u64 nDistinct = p->current.anDLt[i] + 1;
88923       u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
88924       sqlite3_snprintf(24, z, " %llu", iVal);
88925       z += sqlite3Strlen30(z);
88926       assert( p->current.anEq[i] );
88927     }
88928     assert( z[0]=='\0' && z>zRet );
88929 
88930     sqlite3_result_text(context, zRet, -1, sqlite3_free);
88931   }
88932 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88933   else if( eCall==STAT_GET_ROWID ){
88934     if( p->iGet<0 ){
88935       samplePushPrevious(p, 0);
88936       p->iGet = 0;
88937     }
88938     if( p->iGet<p->nSample ){
88939       Stat4Sample *pS = p->a + p->iGet;
88940       if( pS->nRowid==0 ){
88941         sqlite3_result_int64(context, pS->u.iRowid);
88942       }else{
88943         sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
88944                             SQLITE_TRANSIENT);
88945       }
88946     }
88947   }else{
88948     tRowcnt *aCnt = 0;
88949 
88950     assert( p->iGet<p->nSample );
88951     switch( eCall ){
88952       case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
88953       case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
88954       default: {
88955         aCnt = p->a[p->iGet].anDLt;
88956         p->iGet++;
88957         break;
88958       }
88959     }
88960 
88961     if( IsStat3 ){
88962       sqlite3_result_int64(context, (i64)aCnt[0]);
88963     }else{
88964       char *zRet = sqlite3MallocZero(p->nCol * 25);
88965       if( zRet==0 ){
88966         sqlite3_result_error_nomem(context);
88967       }else{
88968         int i;
88969         char *z = zRet;
88970         for(i=0; i<p->nCol; i++){
88971           sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
88972           z += sqlite3Strlen30(z);
88973         }
88974         assert( z[0]=='\0' && z>zRet );
88975         z[-1] = '\0';
88976         sqlite3_result_text(context, zRet, -1, sqlite3_free);
88977       }
88978     }
88979   }
88980 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
88981 #ifndef SQLITE_DEBUG
88982   UNUSED_PARAMETER( argc );
88983 #endif
88984 }
88985 static const FuncDef statGetFuncdef = {
88986   1+IsStat34,      /* nArg */
88987   SQLITE_UTF8,     /* funcFlags */
88988   0,               /* pUserData */
88989   0,               /* pNext */
88990   statGet,         /* xFunc */
88991   0,               /* xStep */
88992   0,               /* xFinalize */
88993   "stat_get",      /* zName */
88994   0,               /* pHash */
88995   0                /* pDestructor */
88996 };
88997 
88998 static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
88999   assert( regOut!=regStat4 && regOut!=regStat4+1 );
89000 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89001   sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
89002 #elif SQLITE_DEBUG
89003   assert( iParam==STAT_GET_STAT1 );
89004 #else
89005   UNUSED_PARAMETER( iParam );
89006 #endif
89007   sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
89008   sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
89009   sqlite3VdbeChangeP5(v, 1 + IsStat34);
89010 }
89011 
89012 /*
89013 ** Generate code to do an analysis of all indices associated with
89014 ** a single table.
89015 */
89016 static void analyzeOneTable(
89017   Parse *pParse,   /* Parser context */
89018   Table *pTab,     /* Table whose indices are to be analyzed */
89019   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
89020   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
89021   int iMem,        /* Available memory locations begin here */
89022   int iTab         /* Next available cursor */
89023 ){
89024   sqlite3 *db = pParse->db;    /* Database handle */
89025   Index *pIdx;                 /* An index to being analyzed */
89026   int iIdxCur;                 /* Cursor open on index being analyzed */
89027   int iTabCur;                 /* Table cursor */
89028   Vdbe *v;                     /* The virtual machine being built up */
89029   int i;                       /* Loop counter */
89030   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
89031   int iDb;                     /* Index of database containing pTab */
89032   u8 needTableCnt = 1;         /* True to count the table */
89033   int regNewRowid = iMem++;    /* Rowid for the inserted record */
89034   int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
89035   int regChng = iMem++;        /* Index of changed index field */
89036 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89037   int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
89038 #endif
89039   int regTemp = iMem++;        /* Temporary use register */
89040   int regTabname = iMem++;     /* Register containing table name */
89041   int regIdxname = iMem++;     /* Register containing index name */
89042   int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
89043   int regPrev = iMem;          /* MUST BE LAST (see below) */
89044 
89045   pParse->nMem = MAX(pParse->nMem, iMem);
89046   v = sqlite3GetVdbe(pParse);
89047   if( v==0 || NEVER(pTab==0) ){
89048     return;
89049   }
89050   if( pTab->tnum==0 ){
89051     /* Do not gather statistics on views or virtual tables */
89052     return;
89053   }
89054   if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
89055     /* Do not gather statistics on system tables */
89056     return;
89057   }
89058   assert( sqlite3BtreeHoldsAllMutexes(db) );
89059   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
89060   assert( iDb>=0 );
89061   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89062 #ifndef SQLITE_OMIT_AUTHORIZATION
89063   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
89064       db->aDb[iDb].zName ) ){
89065     return;
89066   }
89067 #endif
89068 
89069   /* Establish a read-lock on the table at the shared-cache level.
89070   ** Open a read-only cursor on the table. Also allocate a cursor number
89071   ** to use for scanning indexes (iIdxCur). No index cursor is opened at
89072   ** this time though.  */
89073   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
89074   iTabCur = iTab++;
89075   iIdxCur = iTab++;
89076   pParse->nTab = MAX(pParse->nTab, iTab);
89077   sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
89078   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
89079 
89080   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
89081     int nCol;                     /* Number of columns in pIdx. "N" */
89082     int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
89083     int addrNextRow;              /* Address of "next_row:" */
89084     const char *zIdxName;         /* Name of the index */
89085     int nColTest;                 /* Number of columns to test for changes */
89086 
89087     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
89088     if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
89089     if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
89090       nCol = pIdx->nKeyCol;
89091       zIdxName = pTab->zName;
89092       nColTest = nCol - 1;
89093     }else{
89094       nCol = pIdx->nColumn;
89095       zIdxName = pIdx->zName;
89096       nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
89097     }
89098 
89099     /* Populate the register containing the index name. */
89100     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0);
89101     VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
89102 
89103     /*
89104     ** Pseudo-code for loop that calls stat_push():
89105     **
89106     **   Rewind csr
89107     **   if eof(csr) goto end_of_scan;
89108     **   regChng = 0
89109     **   goto chng_addr_0;
89110     **
89111     **  next_row:
89112     **   regChng = 0
89113     **   if( idx(0) != regPrev(0) ) goto chng_addr_0
89114     **   regChng = 1
89115     **   if( idx(1) != regPrev(1) ) goto chng_addr_1
89116     **   ...
89117     **   regChng = N
89118     **   goto chng_addr_N
89119     **
89120     **  chng_addr_0:
89121     **   regPrev(0) = idx(0)
89122     **  chng_addr_1:
89123     **   regPrev(1) = idx(1)
89124     **  ...
89125     **
89126     **  endDistinctTest:
89127     **   regRowid = idx(rowid)
89128     **   stat_push(P, regChng, regRowid)
89129     **   Next csr
89130     **   if !eof(csr) goto next_row;
89131     **
89132     **  end_of_scan:
89133     */
89134 
89135     /* Make sure there are enough memory cells allocated to accommodate
89136     ** the regPrev array and a trailing rowid (the rowid slot is required
89137     ** when building a record to insert into the sample column of
89138     ** the sqlite_stat4 table.  */
89139     pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
89140 
89141     /* Open a read-only cursor on the index being analyzed. */
89142     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
89143     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
89144     sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
89145     VdbeComment((v, "%s", pIdx->zName));
89146 
89147     /* Invoke the stat_init() function. The arguments are:
89148     **
89149     **    (1) the number of columns in the index including the rowid
89150     **        (or for a WITHOUT ROWID table, the number of PK columns),
89151     **    (2) the number of columns in the key without the rowid/pk
89152     **    (3) the number of rows in the index,
89153     **
89154     **
89155     ** The third argument is only used for STAT3 and STAT4
89156     */
89157 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89158     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
89159 #endif
89160     sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
89161     sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
89162     sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
89163     sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
89164     sqlite3VdbeChangeP5(v, 2+IsStat34);
89165 
89166     /* Implementation of the following:
89167     **
89168     **   Rewind csr
89169     **   if eof(csr) goto end_of_scan;
89170     **   regChng = 0
89171     **   goto next_push_0;
89172     **
89173     */
89174     addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
89175     VdbeCoverage(v);
89176     sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
89177     addrNextRow = sqlite3VdbeCurrentAddr(v);
89178 
89179     if( nColTest>0 ){
89180       int endDistinctTest = sqlite3VdbeMakeLabel(v);
89181       int *aGotoChng;               /* Array of jump instruction addresses */
89182       aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
89183       if( aGotoChng==0 ) continue;
89184 
89185       /*
89186       **  next_row:
89187       **   regChng = 0
89188       **   if( idx(0) != regPrev(0) ) goto chng_addr_0
89189       **   regChng = 1
89190       **   if( idx(1) != regPrev(1) ) goto chng_addr_1
89191       **   ...
89192       **   regChng = N
89193       **   goto endDistinctTest
89194       */
89195       sqlite3VdbeAddOp0(v, OP_Goto);
89196       addrNextRow = sqlite3VdbeCurrentAddr(v);
89197       if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
89198         /* For a single-column UNIQUE index, once we have found a non-NULL
89199         ** row, we know that all the rest will be distinct, so skip
89200         ** subsequent distinctness tests. */
89201         sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
89202         VdbeCoverage(v);
89203       }
89204       for(i=0; i<nColTest; i++){
89205         char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
89206         sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
89207         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
89208         aGotoChng[i] =
89209         sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
89210         sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
89211         VdbeCoverage(v);
89212       }
89213       sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
89214       sqlite3VdbeAddOp2(v, OP_Goto, 0, endDistinctTest);
89215 
89216 
89217       /*
89218       **  chng_addr_0:
89219       **   regPrev(0) = idx(0)
89220       **  chng_addr_1:
89221       **   regPrev(1) = idx(1)
89222       **  ...
89223       */
89224       sqlite3VdbeJumpHere(v, addrNextRow-1);
89225       for(i=0; i<nColTest; i++){
89226         sqlite3VdbeJumpHere(v, aGotoChng[i]);
89227         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
89228       }
89229       sqlite3VdbeResolveLabel(v, endDistinctTest);
89230       sqlite3DbFree(db, aGotoChng);
89231     }
89232 
89233     /*
89234     **  chng_addr_N:
89235     **   regRowid = idx(rowid)            // STAT34 only
89236     **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
89237     **   Next csr
89238     **   if !eof(csr) goto next_row;
89239     */
89240 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89241     assert( regRowid==(regStat4+2) );
89242     if( HasRowid(pTab) ){
89243       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
89244     }else{
89245       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
89246       int j, k, regKey;
89247       regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
89248       for(j=0; j<pPk->nKeyCol; j++){
89249         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
89250         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
89251         VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
89252       }
89253       sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
89254       sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
89255     }
89256 #endif
89257     assert( regChng==(regStat4+1) );
89258     sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
89259     sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
89260     sqlite3VdbeChangeP5(v, 2+IsStat34);
89261     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
89262 
89263     /* Add the entry to the stat1 table. */
89264     callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
89265     assert( "BBB"[0]==SQLITE_AFF_TEXT );
89266     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
89267     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
89268     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
89269     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
89270 
89271     /* Add the entries to the stat3 or stat4 table. */
89272 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89273     {
89274       int regEq = regStat1;
89275       int regLt = regStat1+1;
89276       int regDLt = regStat1+2;
89277       int regSample = regStat1+3;
89278       int regCol = regStat1+4;
89279       int regSampleRowid = regCol + nCol;
89280       int addrNext;
89281       int addrIsNull;
89282       u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
89283 
89284       pParse->nMem = MAX(pParse->nMem, regCol+nCol);
89285 
89286       addrNext = sqlite3VdbeCurrentAddr(v);
89287       callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
89288       addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
89289       VdbeCoverage(v);
89290       callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
89291       callStatGet(v, regStat4, STAT_GET_NLT, regLt);
89292       callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
89293       sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
89294       /* We know that the regSampleRowid row exists because it was read by
89295       ** the previous loop.  Thus the not-found jump of seekOp will never
89296       ** be taken */
89297       VdbeCoverageNeverTaken(v);
89298 #ifdef SQLITE_ENABLE_STAT3
89299       sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
89300                                       pIdx->aiColumn[0], regSample);
89301 #else
89302       for(i=0; i<nCol; i++){
89303         i16 iCol = pIdx->aiColumn[i];
89304         sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
89305       }
89306       sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
89307 #endif
89308       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
89309       sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
89310       sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
89311       sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
89312       sqlite3VdbeJumpHere(v, addrIsNull);
89313     }
89314 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
89315 
89316     /* End of analysis */
89317     sqlite3VdbeJumpHere(v, addrRewind);
89318   }
89319 
89320 
89321   /* Create a single sqlite_stat1 entry containing NULL as the index
89322   ** name and the row count as the content.
89323   */
89324   if( pOnlyIdx==0 && needTableCnt ){
89325     VdbeComment((v, "%s", pTab->zName));
89326     sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
89327     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
89328     sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
89329     assert( "BBB"[0]==SQLITE_AFF_TEXT );
89330     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
89331     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
89332     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
89333     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
89334     sqlite3VdbeJumpHere(v, jZeroRows);
89335   }
89336 }
89337 
89338 
89339 /*
89340 ** Generate code that will cause the most recent index analysis to
89341 ** be loaded into internal hash tables where is can be used.
89342 */
89343 static void loadAnalysis(Parse *pParse, int iDb){
89344   Vdbe *v = sqlite3GetVdbe(pParse);
89345   if( v ){
89346     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
89347   }
89348 }
89349 
89350 /*
89351 ** Generate code that will do an analysis of an entire database
89352 */
89353 static void analyzeDatabase(Parse *pParse, int iDb){
89354   sqlite3 *db = pParse->db;
89355   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
89356   HashElem *k;
89357   int iStatCur;
89358   int iMem;
89359   int iTab;
89360 
89361   sqlite3BeginWriteOperation(pParse, 0, iDb);
89362   iStatCur = pParse->nTab;
89363   pParse->nTab += 3;
89364   openStatTable(pParse, iDb, iStatCur, 0, 0);
89365   iMem = pParse->nMem+1;
89366   iTab = pParse->nTab;
89367   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89368   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
89369     Table *pTab = (Table*)sqliteHashData(k);
89370     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
89371   }
89372   loadAnalysis(pParse, iDb);
89373 }
89374 
89375 /*
89376 ** Generate code that will do an analysis of a single table in
89377 ** a database.  If pOnlyIdx is not NULL then it is a single index
89378 ** in pTab that should be analyzed.
89379 */
89380 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
89381   int iDb;
89382   int iStatCur;
89383 
89384   assert( pTab!=0 );
89385   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
89386   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
89387   sqlite3BeginWriteOperation(pParse, 0, iDb);
89388   iStatCur = pParse->nTab;
89389   pParse->nTab += 3;
89390   if( pOnlyIdx ){
89391     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
89392   }else{
89393     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
89394   }
89395   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
89396   loadAnalysis(pParse, iDb);
89397 }
89398 
89399 /*
89400 ** Generate code for the ANALYZE command.  The parser calls this routine
89401 ** when it recognizes an ANALYZE command.
89402 **
89403 **        ANALYZE                            -- 1
89404 **        ANALYZE  <database>                -- 2
89405 **        ANALYZE  ?<database>.?<tablename>  -- 3
89406 **
89407 ** Form 1 causes all indices in all attached databases to be analyzed.
89408 ** Form 2 analyzes all indices the single database named.
89409 ** Form 3 analyzes all indices associated with the named table.
89410 */
89411 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
89412   sqlite3 *db = pParse->db;
89413   int iDb;
89414   int i;
89415   char *z, *zDb;
89416   Table *pTab;
89417   Index *pIdx;
89418   Token *pTableName;
89419   Vdbe *v;
89420 
89421   /* Read the database schema. If an error occurs, leave an error message
89422   ** and code in pParse and return NULL. */
89423   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
89424   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
89425     return;
89426   }
89427 
89428   assert( pName2!=0 || pName1==0 );
89429   if( pName1==0 ){
89430     /* Form 1:  Analyze everything */
89431     for(i=0; i<db->nDb; i++){
89432       if( i==1 ) continue;  /* Do not analyze the TEMP database */
89433       analyzeDatabase(pParse, i);
89434     }
89435   }else if( pName2->n==0 ){
89436     /* Form 2:  Analyze the database or table named */
89437     iDb = sqlite3FindDb(db, pName1);
89438     if( iDb>=0 ){
89439       analyzeDatabase(pParse, iDb);
89440     }else{
89441       z = sqlite3NameFromToken(db, pName1);
89442       if( z ){
89443         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
89444           analyzeTable(pParse, pIdx->pTable, pIdx);
89445         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
89446           analyzeTable(pParse, pTab, 0);
89447         }
89448         sqlite3DbFree(db, z);
89449       }
89450     }
89451   }else{
89452     /* Form 3: Analyze the fully qualified table name */
89453     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
89454     if( iDb>=0 ){
89455       zDb = db->aDb[iDb].zName;
89456       z = sqlite3NameFromToken(db, pTableName);
89457       if( z ){
89458         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
89459           analyzeTable(pParse, pIdx->pTable, pIdx);
89460         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
89461           analyzeTable(pParse, pTab, 0);
89462         }
89463         sqlite3DbFree(db, z);
89464       }
89465     }
89466   }
89467   v = sqlite3GetVdbe(pParse);
89468   if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
89469 }
89470 
89471 /*
89472 ** Used to pass information from the analyzer reader through to the
89473 ** callback routine.
89474 */
89475 typedef struct analysisInfo analysisInfo;
89476 struct analysisInfo {
89477   sqlite3 *db;
89478   const char *zDatabase;
89479 };
89480 
89481 /*
89482 ** The first argument points to a nul-terminated string containing a
89483 ** list of space separated integers. Read the first nOut of these into
89484 ** the array aOut[].
89485 */
89486 static void decodeIntArray(
89487   char *zIntArray,       /* String containing int array to decode */
89488   int nOut,              /* Number of slots in aOut[] */
89489   tRowcnt *aOut,         /* Store integers here */
89490   LogEst *aLog,          /* Or, if aOut==0, here */
89491   Index *pIndex          /* Handle extra flags for this index, if not NULL */
89492 ){
89493   char *z = zIntArray;
89494   int c;
89495   int i;
89496   tRowcnt v;
89497 
89498 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89499   if( z==0 ) z = "";
89500 #else
89501   assert( z!=0 );
89502 #endif
89503   for(i=0; *z && i<nOut; i++){
89504     v = 0;
89505     while( (c=z[0])>='0' && c<='9' ){
89506       v = v*10 + c - '0';
89507       z++;
89508     }
89509 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89510     if( aOut ) aOut[i] = v;
89511     if( aLog ) aLog[i] = sqlite3LogEst(v);
89512 #else
89513     assert( aOut==0 );
89514     UNUSED_PARAMETER(aOut);
89515     assert( aLog!=0 );
89516     aLog[i] = sqlite3LogEst(v);
89517 #endif
89518     if( *z==' ' ) z++;
89519   }
89520 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
89521   assert( pIndex!=0 ); {
89522 #else
89523   if( pIndex ){
89524 #endif
89525     pIndex->bUnordered = 0;
89526     pIndex->noSkipScan = 0;
89527     while( z[0] ){
89528       if( sqlite3_strglob("unordered*", z)==0 ){
89529         pIndex->bUnordered = 1;
89530       }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
89531         pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
89532       }else if( sqlite3_strglob("noskipscan*", z)==0 ){
89533         pIndex->noSkipScan = 1;
89534       }
89535 #ifdef SQLITE_ENABLE_COSTMULT
89536       else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
89537         pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
89538       }
89539 #endif
89540       while( z[0]!=0 && z[0]!=' ' ) z++;
89541       while( z[0]==' ' ) z++;
89542     }
89543   }
89544 }
89545 
89546 /*
89547 ** This callback is invoked once for each index when reading the
89548 ** sqlite_stat1 table.
89549 **
89550 **     argv[0] = name of the table
89551 **     argv[1] = name of the index (might be NULL)
89552 **     argv[2] = results of analysis - on integer for each column
89553 **
89554 ** Entries for which argv[1]==NULL simply record the number of rows in
89555 ** the table.
89556 */
89557 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
89558   analysisInfo *pInfo = (analysisInfo*)pData;
89559   Index *pIndex;
89560   Table *pTable;
89561   const char *z;
89562 
89563   assert( argc==3 );
89564   UNUSED_PARAMETER2(NotUsed, argc);
89565 
89566   if( argv==0 || argv[0]==0 || argv[2]==0 ){
89567     return 0;
89568   }
89569   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
89570   if( pTable==0 ){
89571     return 0;
89572   }
89573   if( argv[1]==0 ){
89574     pIndex = 0;
89575   }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
89576     pIndex = sqlite3PrimaryKeyIndex(pTable);
89577   }else{
89578     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
89579   }
89580   z = argv[2];
89581 
89582   if( pIndex ){
89583     tRowcnt *aiRowEst = 0;
89584     int nCol = pIndex->nKeyCol+1;
89585 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89586     /* Index.aiRowEst may already be set here if there are duplicate
89587     ** sqlite_stat1 entries for this index. In that case just clobber
89588     ** the old data with the new instead of allocating a new array.  */
89589     if( pIndex->aiRowEst==0 ){
89590       pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
89591       if( pIndex->aiRowEst==0 ) pInfo->db->mallocFailed = 1;
89592     }
89593     aiRowEst = pIndex->aiRowEst;
89594 #endif
89595     pIndex->bUnordered = 0;
89596     decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
89597     if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
89598   }else{
89599     Index fakeIdx;
89600     fakeIdx.szIdxRow = pTable->szTabRow;
89601 #ifdef SQLITE_ENABLE_COSTMULT
89602     fakeIdx.pTable = pTable;
89603 #endif
89604     decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
89605     pTable->szTabRow = fakeIdx.szIdxRow;
89606   }
89607 
89608   return 0;
89609 }
89610 
89611 /*
89612 ** If the Index.aSample variable is not NULL, delete the aSample[] array
89613 ** and its contents.
89614 */
89615 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
89616 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89617   if( pIdx->aSample ){
89618     int j;
89619     for(j=0; j<pIdx->nSample; j++){
89620       IndexSample *p = &pIdx->aSample[j];
89621       sqlite3DbFree(db, p->p);
89622     }
89623     sqlite3DbFree(db, pIdx->aSample);
89624   }
89625   if( db && db->pnBytesFreed==0 ){
89626     pIdx->nSample = 0;
89627     pIdx->aSample = 0;
89628   }
89629 #else
89630   UNUSED_PARAMETER(db);
89631   UNUSED_PARAMETER(pIdx);
89632 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
89633 }
89634 
89635 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89636 /*
89637 ** Populate the pIdx->aAvgEq[] array based on the samples currently
89638 ** stored in pIdx->aSample[].
89639 */
89640 static void initAvgEq(Index *pIdx){
89641   if( pIdx ){
89642     IndexSample *aSample = pIdx->aSample;
89643     IndexSample *pFinal = &aSample[pIdx->nSample-1];
89644     int iCol;
89645     int nCol = 1;
89646     if( pIdx->nSampleCol>1 ){
89647       /* If this is stat4 data, then calculate aAvgEq[] values for all
89648       ** sample columns except the last. The last is always set to 1, as
89649       ** once the trailing PK fields are considered all index keys are
89650       ** unique.  */
89651       nCol = pIdx->nSampleCol-1;
89652       pIdx->aAvgEq[nCol] = 1;
89653     }
89654     for(iCol=0; iCol<nCol; iCol++){
89655       int nSample = pIdx->nSample;
89656       int i;                    /* Used to iterate through samples */
89657       tRowcnt sumEq = 0;        /* Sum of the nEq values */
89658       tRowcnt avgEq = 0;
89659       tRowcnt nRow;             /* Number of rows in index */
89660       i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
89661       i64 nDist100;             /* Number of distinct values in index */
89662 
89663       if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
89664         nRow = pFinal->anLt[iCol];
89665         nDist100 = (i64)100 * pFinal->anDLt[iCol];
89666         nSample--;
89667       }else{
89668         nRow = pIdx->aiRowEst[0];
89669         nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
89670       }
89671       pIdx->nRowEst0 = nRow;
89672 
89673       /* Set nSum to the number of distinct (iCol+1) field prefixes that
89674       ** occur in the stat4 table for this index. Set sumEq to the sum of
89675       ** the nEq values for column iCol for the same set (adding the value
89676       ** only once where there exist duplicate prefixes).  */
89677       for(i=0; i<nSample; i++){
89678         if( i==(pIdx->nSample-1)
89679          || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
89680         ){
89681           sumEq += aSample[i].anEq[iCol];
89682           nSum100 += 100;
89683         }
89684       }
89685 
89686       if( nDist100>nSum100 ){
89687         avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
89688       }
89689       if( avgEq==0 ) avgEq = 1;
89690       pIdx->aAvgEq[iCol] = avgEq;
89691     }
89692   }
89693 }
89694 
89695 /*
89696 ** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
89697 ** is supplied instead, find the PRIMARY KEY index for that table.
89698 */
89699 static Index *findIndexOrPrimaryKey(
89700   sqlite3 *db,
89701   const char *zName,
89702   const char *zDb
89703 ){
89704   Index *pIdx = sqlite3FindIndex(db, zName, zDb);
89705   if( pIdx==0 ){
89706     Table *pTab = sqlite3FindTable(db, zName, zDb);
89707     if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
89708   }
89709   return pIdx;
89710 }
89711 
89712 /*
89713 ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
89714 ** into the relevant Index.aSample[] arrays.
89715 **
89716 ** Arguments zSql1 and zSql2 must point to SQL statements that return
89717 ** data equivalent to the following (statements are different for stat3,
89718 ** see the caller of this function for details):
89719 **
89720 **    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
89721 **    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
89722 **
89723 ** where %Q is replaced with the database name before the SQL is executed.
89724 */
89725 static int loadStatTbl(
89726   sqlite3 *db,                  /* Database handle */
89727   int bStat3,                   /* Assume single column records only */
89728   const char *zSql1,            /* SQL statement 1 (see above) */
89729   const char *zSql2,            /* SQL statement 2 (see above) */
89730   const char *zDb               /* Database name (e.g. "main") */
89731 ){
89732   int rc;                       /* Result codes from subroutines */
89733   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
89734   char *zSql;                   /* Text of the SQL statement */
89735   Index *pPrevIdx = 0;          /* Previous index in the loop */
89736   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
89737 
89738   assert( db->lookaside.bEnabled==0 );
89739   zSql = sqlite3MPrintf(db, zSql1, zDb);
89740   if( !zSql ){
89741     return SQLITE_NOMEM;
89742   }
89743   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
89744   sqlite3DbFree(db, zSql);
89745   if( rc ) return rc;
89746 
89747   while( sqlite3_step(pStmt)==SQLITE_ROW ){
89748     int nIdxCol = 1;              /* Number of columns in stat4 records */
89749 
89750     char *zIndex;   /* Index name */
89751     Index *pIdx;    /* Pointer to the index object */
89752     int nSample;    /* Number of samples */
89753     int nByte;      /* Bytes of space required */
89754     int i;          /* Bytes of space required */
89755     tRowcnt *pSpace;
89756 
89757     zIndex = (char *)sqlite3_column_text(pStmt, 0);
89758     if( zIndex==0 ) continue;
89759     nSample = sqlite3_column_int(pStmt, 1);
89760     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
89761     assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
89762     /* Index.nSample is non-zero at this point if data has already been
89763     ** loaded from the stat4 table. In this case ignore stat3 data.  */
89764     if( pIdx==0 || pIdx->nSample ) continue;
89765     if( bStat3==0 ){
89766       assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
89767       if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
89768         nIdxCol = pIdx->nKeyCol;
89769       }else{
89770         nIdxCol = pIdx->nColumn;
89771       }
89772     }
89773     pIdx->nSampleCol = nIdxCol;
89774     nByte = sizeof(IndexSample) * nSample;
89775     nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
89776     nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
89777 
89778     pIdx->aSample = sqlite3DbMallocZero(db, nByte);
89779     if( pIdx->aSample==0 ){
89780       sqlite3_finalize(pStmt);
89781       return SQLITE_NOMEM;
89782     }
89783     pSpace = (tRowcnt*)&pIdx->aSample[nSample];
89784     pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
89785     for(i=0; i<nSample; i++){
89786       pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
89787       pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
89788       pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
89789     }
89790     assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
89791   }
89792   rc = sqlite3_finalize(pStmt);
89793   if( rc ) return rc;
89794 
89795   zSql = sqlite3MPrintf(db, zSql2, zDb);
89796   if( !zSql ){
89797     return SQLITE_NOMEM;
89798   }
89799   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
89800   sqlite3DbFree(db, zSql);
89801   if( rc ) return rc;
89802 
89803   while( sqlite3_step(pStmt)==SQLITE_ROW ){
89804     char *zIndex;                 /* Index name */
89805     Index *pIdx;                  /* Pointer to the index object */
89806     int nCol = 1;                 /* Number of columns in index */
89807 
89808     zIndex = (char *)sqlite3_column_text(pStmt, 0);
89809     if( zIndex==0 ) continue;
89810     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
89811     if( pIdx==0 ) continue;
89812     /* This next condition is true if data has already been loaded from
89813     ** the sqlite_stat4 table. In this case ignore stat3 data.  */
89814     nCol = pIdx->nSampleCol;
89815     if( bStat3 && nCol>1 ) continue;
89816     if( pIdx!=pPrevIdx ){
89817       initAvgEq(pPrevIdx);
89818       pPrevIdx = pIdx;
89819     }
89820     pSample = &pIdx->aSample[pIdx->nSample];
89821     decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
89822     decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
89823     decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
89824 
89825     /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
89826     ** This is in case the sample record is corrupted. In that case, the
89827     ** sqlite3VdbeRecordCompare() may read up to two varints past the
89828     ** end of the allocated buffer before it realizes it is dealing with
89829     ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
89830     ** a buffer overread.  */
89831     pSample->n = sqlite3_column_bytes(pStmt, 4);
89832     pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
89833     if( pSample->p==0 ){
89834       sqlite3_finalize(pStmt);
89835       return SQLITE_NOMEM;
89836     }
89837     memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
89838     pIdx->nSample++;
89839   }
89840   rc = sqlite3_finalize(pStmt);
89841   if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
89842   return rc;
89843 }
89844 
89845 /*
89846 ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
89847 ** the Index.aSample[] arrays of all indices.
89848 */
89849 static int loadStat4(sqlite3 *db, const char *zDb){
89850   int rc = SQLITE_OK;             /* Result codes from subroutines */
89851 
89852   assert( db->lookaside.bEnabled==0 );
89853   if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
89854     rc = loadStatTbl(db, 0,
89855       "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
89856       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
89857       zDb
89858     );
89859   }
89860 
89861   if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
89862     rc = loadStatTbl(db, 1,
89863       "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
89864       "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
89865       zDb
89866     );
89867   }
89868 
89869   return rc;
89870 }
89871 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
89872 
89873 /*
89874 ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
89875 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
89876 ** arrays. The contents of sqlite_stat3/4 are used to populate the
89877 ** Index.aSample[] arrays.
89878 **
89879 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
89880 ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
89881 ** during compilation and the sqlite_stat3/4 table is present, no data is
89882 ** read from it.
89883 **
89884 ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
89885 ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
89886 ** returned. However, in this case, data is read from the sqlite_stat1
89887 ** table (if it is present) before returning.
89888 **
89889 ** If an OOM error occurs, this function always sets db->mallocFailed.
89890 ** This means if the caller does not care about other errors, the return
89891 ** code may be ignored.
89892 */
89893 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
89894   analysisInfo sInfo;
89895   HashElem *i;
89896   char *zSql;
89897   int rc;
89898 
89899   assert( iDb>=0 && iDb<db->nDb );
89900   assert( db->aDb[iDb].pBt!=0 );
89901 
89902   /* Clear any prior statistics */
89903   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89904   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
89905     Index *pIdx = sqliteHashData(i);
89906     sqlite3DefaultRowEst(pIdx);
89907 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89908     sqlite3DeleteIndexSamples(db, pIdx);
89909     pIdx->aSample = 0;
89910 #endif
89911   }
89912 
89913   /* Check to make sure the sqlite_stat1 table exists */
89914   sInfo.db = db;
89915   sInfo.zDatabase = db->aDb[iDb].zName;
89916   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
89917     return SQLITE_ERROR;
89918   }
89919 
89920   /* Load new statistics out of the sqlite_stat1 table */
89921   zSql = sqlite3MPrintf(db,
89922       "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
89923   if( zSql==0 ){
89924     rc = SQLITE_NOMEM;
89925   }else{
89926     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
89927     sqlite3DbFree(db, zSql);
89928   }
89929 
89930 
89931   /* Load the statistics from the sqlite_stat4 table. */
89932 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89933   if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
89934     int lookasideEnabled = db->lookaside.bEnabled;
89935     db->lookaside.bEnabled = 0;
89936     rc = loadStat4(db, sInfo.zDatabase);
89937     db->lookaside.bEnabled = lookasideEnabled;
89938   }
89939   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
89940     Index *pIdx = sqliteHashData(i);
89941     sqlite3_free(pIdx->aiRowEst);
89942     pIdx->aiRowEst = 0;
89943   }
89944 #endif
89945 
89946   if( rc==SQLITE_NOMEM ){
89947     db->mallocFailed = 1;
89948   }
89949   return rc;
89950 }
89951 
89952 
89953 #endif /* SQLITE_OMIT_ANALYZE */
89954 
89955 /************** End of analyze.c *********************************************/
89956 /************** Begin file attach.c ******************************************/
89957 /*
89958 ** 2003 April 6
89959 **
89960 ** The author disclaims copyright to this source code.  In place of
89961 ** a legal notice, here is a blessing:
89962 **
89963 **    May you do good and not evil.
89964 **    May you find forgiveness for yourself and forgive others.
89965 **    May you share freely, never taking more than you give.
89966 **
89967 *************************************************************************
89968 ** This file contains code used to implement the ATTACH and DETACH commands.
89969 */
89970 
89971 #ifndef SQLITE_OMIT_ATTACH
89972 /*
89973 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
89974 ** is slightly different from resolving a normal SQL expression, because simple
89975 ** identifiers are treated as strings, not possible column names or aliases.
89976 **
89977 ** i.e. if the parser sees:
89978 **
89979 **     ATTACH DATABASE abc AS def
89980 **
89981 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
89982 ** looking for columns of the same name.
89983 **
89984 ** This only applies to the root node of pExpr, so the statement:
89985 **
89986 **     ATTACH DATABASE abc||def AS 'db2'
89987 **
89988 ** will fail because neither abc or def can be resolved.
89989 */
89990 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
89991 {
89992   int rc = SQLITE_OK;
89993   if( pExpr ){
89994     if( pExpr->op!=TK_ID ){
89995       rc = sqlite3ResolveExprNames(pName, pExpr);
89996     }else{
89997       pExpr->op = TK_STRING;
89998     }
89999   }
90000   return rc;
90001 }
90002 
90003 /*
90004 ** An SQL user-function registered to do the work of an ATTACH statement. The
90005 ** three arguments to the function come directly from an attach statement:
90006 **
90007 **     ATTACH DATABASE x AS y KEY z
90008 **
90009 **     SELECT sqlite_attach(x, y, z)
90010 **
90011 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
90012 ** third argument.
90013 */
90014 static void attachFunc(
90015   sqlite3_context *context,
90016   int NotUsed,
90017   sqlite3_value **argv
90018 ){
90019   int i;
90020   int rc = 0;
90021   sqlite3 *db = sqlite3_context_db_handle(context);
90022   const char *zName;
90023   const char *zFile;
90024   char *zPath = 0;
90025   char *zErr = 0;
90026   unsigned int flags;
90027   Db *aNew;
90028   char *zErrDyn = 0;
90029   sqlite3_vfs *pVfs;
90030 
90031   UNUSED_PARAMETER(NotUsed);
90032 
90033   zFile = (const char *)sqlite3_value_text(argv[0]);
90034   zName = (const char *)sqlite3_value_text(argv[1]);
90035   if( zFile==0 ) zFile = "";
90036   if( zName==0 ) zName = "";
90037 
90038   /* Check for the following errors:
90039   **
90040   **     * Too many attached databases,
90041   **     * Transaction currently open
90042   **     * Specified database name already being used.
90043   */
90044   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
90045     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
90046       db->aLimit[SQLITE_LIMIT_ATTACHED]
90047     );
90048     goto attach_error;
90049   }
90050   if( !db->autoCommit ){
90051     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
90052     goto attach_error;
90053   }
90054   for(i=0; i<db->nDb; i++){
90055     char *z = db->aDb[i].zName;
90056     assert( z && zName );
90057     if( sqlite3StrICmp(z, zName)==0 ){
90058       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
90059       goto attach_error;
90060     }
90061   }
90062 
90063   /* Allocate the new entry in the db->aDb[] array and initialize the schema
90064   ** hash tables.
90065   */
90066   if( db->aDb==db->aDbStatic ){
90067     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
90068     if( aNew==0 ) return;
90069     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
90070   }else{
90071     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
90072     if( aNew==0 ) return;
90073   }
90074   db->aDb = aNew;
90075   aNew = &db->aDb[db->nDb];
90076   memset(aNew, 0, sizeof(*aNew));
90077 
90078   /* Open the database file. If the btree is successfully opened, use
90079   ** it to obtain the database schema. At this point the schema may
90080   ** or may not be initialized.
90081   */
90082   flags = db->openFlags;
90083   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
90084   if( rc!=SQLITE_OK ){
90085     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
90086     sqlite3_result_error(context, zErr, -1);
90087     sqlite3_free(zErr);
90088     return;
90089   }
90090   assert( pVfs );
90091   flags |= SQLITE_OPEN_MAIN_DB;
90092   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
90093   sqlite3_free( zPath );
90094   db->nDb++;
90095   if( rc==SQLITE_CONSTRAINT ){
90096     rc = SQLITE_ERROR;
90097     zErrDyn = sqlite3MPrintf(db, "database is already attached");
90098   }else if( rc==SQLITE_OK ){
90099     Pager *pPager;
90100     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
90101     if( !aNew->pSchema ){
90102       rc = SQLITE_NOMEM;
90103     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
90104       zErrDyn = sqlite3MPrintf(db,
90105         "attached databases must use the same text encoding as main database");
90106       rc = SQLITE_ERROR;
90107     }
90108     sqlite3BtreeEnter(aNew->pBt);
90109     pPager = sqlite3BtreePager(aNew->pBt);
90110     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
90111     sqlite3BtreeSecureDelete(aNew->pBt,
90112                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
90113 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
90114     sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
90115 #endif
90116     sqlite3BtreeLeave(aNew->pBt);
90117   }
90118   aNew->safety_level = 3;
90119   aNew->zName = sqlite3DbStrDup(db, zName);
90120   if( rc==SQLITE_OK && aNew->zName==0 ){
90121     rc = SQLITE_NOMEM;
90122   }
90123 
90124 
90125 #ifdef SQLITE_HAS_CODEC
90126   if( rc==SQLITE_OK ){
90127     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
90128     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
90129     int nKey;
90130     char *zKey;
90131     int t = sqlite3_value_type(argv[2]);
90132     switch( t ){
90133       case SQLITE_INTEGER:
90134       case SQLITE_FLOAT:
90135         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
90136         rc = SQLITE_ERROR;
90137         break;
90138 
90139       case SQLITE_TEXT:
90140       case SQLITE_BLOB:
90141         nKey = sqlite3_value_bytes(argv[2]);
90142         zKey = (char *)sqlite3_value_blob(argv[2]);
90143         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
90144         break;
90145 
90146       case SQLITE_NULL:
90147         /* No key specified.  Use the key from the main database */
90148         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
90149         if( nKey>0 || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
90150           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
90151         }
90152         break;
90153     }
90154   }
90155 #endif
90156 
90157   /* If the file was opened successfully, read the schema for the new database.
90158   ** If this fails, or if opening the file failed, then close the file and
90159   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
90160   ** we found it.
90161   */
90162   if( rc==SQLITE_OK ){
90163     sqlite3BtreeEnterAll(db);
90164     rc = sqlite3Init(db, &zErrDyn);
90165     sqlite3BtreeLeaveAll(db);
90166   }
90167 #ifdef SQLITE_USER_AUTHENTICATION
90168   if( rc==SQLITE_OK ){
90169     u8 newAuth = 0;
90170     rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
90171     if( newAuth<db->auth.authLevel ){
90172       rc = SQLITE_AUTH_USER;
90173     }
90174   }
90175 #endif
90176   if( rc ){
90177     int iDb = db->nDb - 1;
90178     assert( iDb>=2 );
90179     if( db->aDb[iDb].pBt ){
90180       sqlite3BtreeClose(db->aDb[iDb].pBt);
90181       db->aDb[iDb].pBt = 0;
90182       db->aDb[iDb].pSchema = 0;
90183     }
90184     sqlite3ResetAllSchemasOfConnection(db);
90185     db->nDb = iDb;
90186     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
90187       db->mallocFailed = 1;
90188       sqlite3DbFree(db, zErrDyn);
90189       zErrDyn = sqlite3MPrintf(db, "out of memory");
90190     }else if( zErrDyn==0 ){
90191       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
90192     }
90193     goto attach_error;
90194   }
90195 
90196   return;
90197 
90198 attach_error:
90199   /* Return an error if we get here */
90200   if( zErrDyn ){
90201     sqlite3_result_error(context, zErrDyn, -1);
90202     sqlite3DbFree(db, zErrDyn);
90203   }
90204   if( rc ) sqlite3_result_error_code(context, rc);
90205 }
90206 
90207 /*
90208 ** An SQL user-function registered to do the work of an DETACH statement. The
90209 ** three arguments to the function come directly from a detach statement:
90210 **
90211 **     DETACH DATABASE x
90212 **
90213 **     SELECT sqlite_detach(x)
90214 */
90215 static void detachFunc(
90216   sqlite3_context *context,
90217   int NotUsed,
90218   sqlite3_value **argv
90219 ){
90220   const char *zName = (const char *)sqlite3_value_text(argv[0]);
90221   sqlite3 *db = sqlite3_context_db_handle(context);
90222   int i;
90223   Db *pDb = 0;
90224   char zErr[128];
90225 
90226   UNUSED_PARAMETER(NotUsed);
90227 
90228   if( zName==0 ) zName = "";
90229   for(i=0; i<db->nDb; i++){
90230     pDb = &db->aDb[i];
90231     if( pDb->pBt==0 ) continue;
90232     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
90233   }
90234 
90235   if( i>=db->nDb ){
90236     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
90237     goto detach_error;
90238   }
90239   if( i<2 ){
90240     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
90241     goto detach_error;
90242   }
90243   if( !db->autoCommit ){
90244     sqlite3_snprintf(sizeof(zErr), zErr,
90245                      "cannot DETACH database within transaction");
90246     goto detach_error;
90247   }
90248   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
90249     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
90250     goto detach_error;
90251   }
90252 
90253   sqlite3BtreeClose(pDb->pBt);
90254   pDb->pBt = 0;
90255   pDb->pSchema = 0;
90256   sqlite3CollapseDatabaseArray(db);
90257   return;
90258 
90259 detach_error:
90260   sqlite3_result_error(context, zErr, -1);
90261 }
90262 
90263 /*
90264 ** This procedure generates VDBE code for a single invocation of either the
90265 ** sqlite_detach() or sqlite_attach() SQL user functions.
90266 */
90267 static void codeAttach(
90268   Parse *pParse,       /* The parser context */
90269   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
90270   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
90271   Expr *pAuthArg,      /* Expression to pass to authorization callback */
90272   Expr *pFilename,     /* Name of database file */
90273   Expr *pDbname,       /* Name of the database to use internally */
90274   Expr *pKey           /* Database key for encryption extension */
90275 ){
90276   int rc;
90277   NameContext sName;
90278   Vdbe *v;
90279   sqlite3* db = pParse->db;
90280   int regArgs;
90281 
90282   memset(&sName, 0, sizeof(NameContext));
90283   sName.pParse = pParse;
90284 
90285   if(
90286       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
90287       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
90288       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
90289   ){
90290     goto attach_end;
90291   }
90292 
90293 #ifndef SQLITE_OMIT_AUTHORIZATION
90294   if( pAuthArg ){
90295     char *zAuthArg;
90296     if( pAuthArg->op==TK_STRING ){
90297       zAuthArg = pAuthArg->u.zToken;
90298     }else{
90299       zAuthArg = 0;
90300     }
90301     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
90302     if(rc!=SQLITE_OK ){
90303       goto attach_end;
90304     }
90305   }
90306 #endif /* SQLITE_OMIT_AUTHORIZATION */
90307 
90308 
90309   v = sqlite3GetVdbe(pParse);
90310   regArgs = sqlite3GetTempRange(pParse, 4);
90311   sqlite3ExprCode(pParse, pFilename, regArgs);
90312   sqlite3ExprCode(pParse, pDbname, regArgs+1);
90313   sqlite3ExprCode(pParse, pKey, regArgs+2);
90314 
90315   assert( v || db->mallocFailed );
90316   if( v ){
90317     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
90318     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
90319     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
90320     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
90321 
90322     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
90323     ** statement only). For DETACH, set it to false (expire all existing
90324     ** statements).
90325     */
90326     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
90327   }
90328 
90329 attach_end:
90330   sqlite3ExprDelete(db, pFilename);
90331   sqlite3ExprDelete(db, pDbname);
90332   sqlite3ExprDelete(db, pKey);
90333 }
90334 
90335 /*
90336 ** Called by the parser to compile a DETACH statement.
90337 **
90338 **     DETACH pDbname
90339 */
90340 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
90341   static const FuncDef detach_func = {
90342     1,                /* nArg */
90343     SQLITE_UTF8,      /* funcFlags */
90344     0,                /* pUserData */
90345     0,                /* pNext */
90346     detachFunc,       /* xFunc */
90347     0,                /* xStep */
90348     0,                /* xFinalize */
90349     "sqlite_detach",  /* zName */
90350     0,                /* pHash */
90351     0                 /* pDestructor */
90352   };
90353   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
90354 }
90355 
90356 /*
90357 ** Called by the parser to compile an ATTACH statement.
90358 **
90359 **     ATTACH p AS pDbname KEY pKey
90360 */
90361 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
90362   static const FuncDef attach_func = {
90363     3,                /* nArg */
90364     SQLITE_UTF8,      /* funcFlags */
90365     0,                /* pUserData */
90366     0,                /* pNext */
90367     attachFunc,       /* xFunc */
90368     0,                /* xStep */
90369     0,                /* xFinalize */
90370     "sqlite_attach",  /* zName */
90371     0,                /* pHash */
90372     0                 /* pDestructor */
90373   };
90374   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
90375 }
90376 #endif /* SQLITE_OMIT_ATTACH */
90377 
90378 /*
90379 ** Initialize a DbFixer structure.  This routine must be called prior
90380 ** to passing the structure to one of the sqliteFixAAAA() routines below.
90381 */
90382 SQLITE_PRIVATE void sqlite3FixInit(
90383   DbFixer *pFix,      /* The fixer to be initialized */
90384   Parse *pParse,      /* Error messages will be written here */
90385   int iDb,            /* This is the database that must be used */
90386   const char *zType,  /* "view", "trigger", or "index" */
90387   const Token *pName  /* Name of the view, trigger, or index */
90388 ){
90389   sqlite3 *db;
90390 
90391   db = pParse->db;
90392   assert( db->nDb>iDb );
90393   pFix->pParse = pParse;
90394   pFix->zDb = db->aDb[iDb].zName;
90395   pFix->pSchema = db->aDb[iDb].pSchema;
90396   pFix->zType = zType;
90397   pFix->pName = pName;
90398   pFix->bVarOnly = (iDb==1);
90399 }
90400 
90401 /*
90402 ** The following set of routines walk through the parse tree and assign
90403 ** a specific database to all table references where the database name
90404 ** was left unspecified in the original SQL statement.  The pFix structure
90405 ** must have been initialized by a prior call to sqlite3FixInit().
90406 **
90407 ** These routines are used to make sure that an index, trigger, or
90408 ** view in one database does not refer to objects in a different database.
90409 ** (Exception: indices, triggers, and views in the TEMP database are
90410 ** allowed to refer to anything.)  If a reference is explicitly made
90411 ** to an object in a different database, an error message is added to
90412 ** pParse->zErrMsg and these routines return non-zero.  If everything
90413 ** checks out, these routines return 0.
90414 */
90415 SQLITE_PRIVATE int sqlite3FixSrcList(
90416   DbFixer *pFix,       /* Context of the fixation */
90417   SrcList *pList       /* The Source list to check and modify */
90418 ){
90419   int i;
90420   const char *zDb;
90421   struct SrcList_item *pItem;
90422 
90423   if( NEVER(pList==0) ) return 0;
90424   zDb = pFix->zDb;
90425   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
90426     if( pFix->bVarOnly==0 ){
90427       if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
90428         sqlite3ErrorMsg(pFix->pParse,
90429             "%s %T cannot reference objects in database %s",
90430             pFix->zType, pFix->pName, pItem->zDatabase);
90431         return 1;
90432       }
90433       sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
90434       pItem->zDatabase = 0;
90435       pItem->pSchema = pFix->pSchema;
90436     }
90437 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
90438     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
90439     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
90440 #endif
90441   }
90442   return 0;
90443 }
90444 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
90445 SQLITE_PRIVATE int sqlite3FixSelect(
90446   DbFixer *pFix,       /* Context of the fixation */
90447   Select *pSelect      /* The SELECT statement to be fixed to one database */
90448 ){
90449   while( pSelect ){
90450     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
90451       return 1;
90452     }
90453     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
90454       return 1;
90455     }
90456     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
90457       return 1;
90458     }
90459     if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
90460       return 1;
90461     }
90462     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
90463       return 1;
90464     }
90465     if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
90466       return 1;
90467     }
90468     if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
90469       return 1;
90470     }
90471     if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
90472       return 1;
90473     }
90474     pSelect = pSelect->pPrior;
90475   }
90476   return 0;
90477 }
90478 SQLITE_PRIVATE int sqlite3FixExpr(
90479   DbFixer *pFix,     /* Context of the fixation */
90480   Expr *pExpr        /* The expression to be fixed to one database */
90481 ){
90482   while( pExpr ){
90483     if( pExpr->op==TK_VARIABLE ){
90484       if( pFix->pParse->db->init.busy ){
90485         pExpr->op = TK_NULL;
90486       }else{
90487         sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
90488         return 1;
90489       }
90490     }
90491     if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
90492     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
90493       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
90494     }else{
90495       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
90496     }
90497     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
90498       return 1;
90499     }
90500     pExpr = pExpr->pLeft;
90501   }
90502   return 0;
90503 }
90504 SQLITE_PRIVATE int sqlite3FixExprList(
90505   DbFixer *pFix,     /* Context of the fixation */
90506   ExprList *pList    /* The expression to be fixed to one database */
90507 ){
90508   int i;
90509   struct ExprList_item *pItem;
90510   if( pList==0 ) return 0;
90511   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
90512     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
90513       return 1;
90514     }
90515   }
90516   return 0;
90517 }
90518 #endif
90519 
90520 #ifndef SQLITE_OMIT_TRIGGER
90521 SQLITE_PRIVATE int sqlite3FixTriggerStep(
90522   DbFixer *pFix,     /* Context of the fixation */
90523   TriggerStep *pStep /* The trigger step be fixed to one database */
90524 ){
90525   while( pStep ){
90526     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
90527       return 1;
90528     }
90529     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
90530       return 1;
90531     }
90532     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
90533       return 1;
90534     }
90535     pStep = pStep->pNext;
90536   }
90537   return 0;
90538 }
90539 #endif
90540 
90541 /************** End of attach.c **********************************************/
90542 /************** Begin file auth.c ********************************************/
90543 /*
90544 ** 2003 January 11
90545 **
90546 ** The author disclaims copyright to this source code.  In place of
90547 ** a legal notice, here is a blessing:
90548 **
90549 **    May you do good and not evil.
90550 **    May you find forgiveness for yourself and forgive others.
90551 **    May you share freely, never taking more than you give.
90552 **
90553 *************************************************************************
90554 ** This file contains code used to implement the sqlite3_set_authorizer()
90555 ** API.  This facility is an optional feature of the library.  Embedded
90556 ** systems that do not need this facility may omit it by recompiling
90557 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
90558 */
90559 
90560 /*
90561 ** All of the code in this file may be omitted by defining a single
90562 ** macro.
90563 */
90564 #ifndef SQLITE_OMIT_AUTHORIZATION
90565 
90566 /*
90567 ** Set or clear the access authorization function.
90568 **
90569 ** The access authorization function is be called during the compilation
90570 ** phase to verify that the user has read and/or write access permission on
90571 ** various fields of the database.  The first argument to the auth function
90572 ** is a copy of the 3rd argument to this routine.  The second argument
90573 ** to the auth function is one of these constants:
90574 **
90575 **       SQLITE_CREATE_INDEX
90576 **       SQLITE_CREATE_TABLE
90577 **       SQLITE_CREATE_TEMP_INDEX
90578 **       SQLITE_CREATE_TEMP_TABLE
90579 **       SQLITE_CREATE_TEMP_TRIGGER
90580 **       SQLITE_CREATE_TEMP_VIEW
90581 **       SQLITE_CREATE_TRIGGER
90582 **       SQLITE_CREATE_VIEW
90583 **       SQLITE_DELETE
90584 **       SQLITE_DROP_INDEX
90585 **       SQLITE_DROP_TABLE
90586 **       SQLITE_DROP_TEMP_INDEX
90587 **       SQLITE_DROP_TEMP_TABLE
90588 **       SQLITE_DROP_TEMP_TRIGGER
90589 **       SQLITE_DROP_TEMP_VIEW
90590 **       SQLITE_DROP_TRIGGER
90591 **       SQLITE_DROP_VIEW
90592 **       SQLITE_INSERT
90593 **       SQLITE_PRAGMA
90594 **       SQLITE_READ
90595 **       SQLITE_SELECT
90596 **       SQLITE_TRANSACTION
90597 **       SQLITE_UPDATE
90598 **
90599 ** The third and fourth arguments to the auth function are the name of
90600 ** the table and the column that are being accessed.  The auth function
90601 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
90602 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
90603 ** means that the SQL statement will never-run - the sqlite3_exec() call
90604 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
90605 ** should run but attempts to read the specified column will return NULL
90606 ** and attempts to write the column will be ignored.
90607 **
90608 ** Setting the auth function to NULL disables this hook.  The default
90609 ** setting of the auth function is NULL.
90610 */
90611 SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
90612   sqlite3 *db,
90613   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
90614   void *pArg
90615 ){
90616 #ifdef SQLITE_ENABLE_API_ARMOR
90617   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
90618 #endif
90619   sqlite3_mutex_enter(db->mutex);
90620   db->xAuth = (sqlite3_xauth)xAuth;
90621   db->pAuthArg = pArg;
90622   sqlite3ExpirePreparedStatements(db);
90623   sqlite3_mutex_leave(db->mutex);
90624   return SQLITE_OK;
90625 }
90626 
90627 /*
90628 ** Write an error message into pParse->zErrMsg that explains that the
90629 ** user-supplied authorization function returned an illegal value.
90630 */
90631 static void sqliteAuthBadReturnCode(Parse *pParse){
90632   sqlite3ErrorMsg(pParse, "authorizer malfunction");
90633   pParse->rc = SQLITE_ERROR;
90634 }
90635 
90636 /*
90637 ** Invoke the authorization callback for permission to read column zCol from
90638 ** table zTab in database zDb. This function assumes that an authorization
90639 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
90640 **
90641 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
90642 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
90643 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
90644 */
90645 SQLITE_PRIVATE int sqlite3AuthReadCol(
90646   Parse *pParse,                  /* The parser context */
90647   const char *zTab,               /* Table name */
90648   const char *zCol,               /* Column name */
90649   int iDb                         /* Index of containing database. */
90650 ){
90651   sqlite3 *db = pParse->db;       /* Database handle */
90652   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
90653   int rc;                         /* Auth callback return code */
90654 
90655   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
90656 #ifdef SQLITE_USER_AUTHENTICATION
90657                  ,db->auth.zAuthUser
90658 #endif
90659                 );
90660   if( rc==SQLITE_DENY ){
90661     if( db->nDb>2 || iDb!=0 ){
90662       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
90663     }else{
90664       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
90665     }
90666     pParse->rc = SQLITE_AUTH;
90667   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
90668     sqliteAuthBadReturnCode(pParse);
90669   }
90670   return rc;
90671 }
90672 
90673 /*
90674 ** The pExpr should be a TK_COLUMN expression.  The table referred to
90675 ** is in pTabList or else it is the NEW or OLD table of a trigger.
90676 ** Check to see if it is OK to read this particular column.
90677 **
90678 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
90679 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
90680 ** then generate an error.
90681 */
90682 SQLITE_PRIVATE void sqlite3AuthRead(
90683   Parse *pParse,        /* The parser context */
90684   Expr *pExpr,          /* The expression to check authorization on */
90685   Schema *pSchema,      /* The schema of the expression */
90686   SrcList *pTabList     /* All table that pExpr might refer to */
90687 ){
90688   sqlite3 *db = pParse->db;
90689   Table *pTab = 0;      /* The table being read */
90690   const char *zCol;     /* Name of the column of the table */
90691   int iSrc;             /* Index in pTabList->a[] of table being read */
90692   int iDb;              /* The index of the database the expression refers to */
90693   int iCol;             /* Index of column in table */
90694 
90695   if( db->xAuth==0 ) return;
90696   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
90697   if( iDb<0 ){
90698     /* An attempt to read a column out of a subquery or other
90699     ** temporary table. */
90700     return;
90701   }
90702 
90703   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
90704   if( pExpr->op==TK_TRIGGER ){
90705     pTab = pParse->pTriggerTab;
90706   }else{
90707     assert( pTabList );
90708     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
90709       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
90710         pTab = pTabList->a[iSrc].pTab;
90711         break;
90712       }
90713     }
90714   }
90715   iCol = pExpr->iColumn;
90716   if( NEVER(pTab==0) ) return;
90717 
90718   if( iCol>=0 ){
90719     assert( iCol<pTab->nCol );
90720     zCol = pTab->aCol[iCol].zName;
90721   }else if( pTab->iPKey>=0 ){
90722     assert( pTab->iPKey<pTab->nCol );
90723     zCol = pTab->aCol[pTab->iPKey].zName;
90724   }else{
90725     zCol = "ROWID";
90726   }
90727   assert( iDb>=0 && iDb<db->nDb );
90728   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
90729     pExpr->op = TK_NULL;
90730   }
90731 }
90732 
90733 /*
90734 ** Do an authorization check using the code and arguments given.  Return
90735 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
90736 ** is returned, then the error count and error message in pParse are
90737 ** modified appropriately.
90738 */
90739 SQLITE_PRIVATE int sqlite3AuthCheck(
90740   Parse *pParse,
90741   int code,
90742   const char *zArg1,
90743   const char *zArg2,
90744   const char *zArg3
90745 ){
90746   sqlite3 *db = pParse->db;
90747   int rc;
90748 
90749   /* Don't do any authorization checks if the database is initialising
90750   ** or if the parser is being invoked from within sqlite3_declare_vtab.
90751   */
90752   if( db->init.busy || IN_DECLARE_VTAB ){
90753     return SQLITE_OK;
90754   }
90755 
90756   if( db->xAuth==0 ){
90757     return SQLITE_OK;
90758   }
90759   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
90760 #ifdef SQLITE_USER_AUTHENTICATION
90761                  ,db->auth.zAuthUser
90762 #endif
90763                 );
90764   if( rc==SQLITE_DENY ){
90765     sqlite3ErrorMsg(pParse, "not authorized");
90766     pParse->rc = SQLITE_AUTH;
90767   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
90768     rc = SQLITE_DENY;
90769     sqliteAuthBadReturnCode(pParse);
90770   }
90771   return rc;
90772 }
90773 
90774 /*
90775 ** Push an authorization context.  After this routine is called, the
90776 ** zArg3 argument to authorization callbacks will be zContext until
90777 ** popped.  Or if pParse==0, this routine is a no-op.
90778 */
90779 SQLITE_PRIVATE void sqlite3AuthContextPush(
90780   Parse *pParse,
90781   AuthContext *pContext,
90782   const char *zContext
90783 ){
90784   assert( pParse );
90785   pContext->pParse = pParse;
90786   pContext->zAuthContext = pParse->zAuthContext;
90787   pParse->zAuthContext = zContext;
90788 }
90789 
90790 /*
90791 ** Pop an authorization context that was previously pushed
90792 ** by sqlite3AuthContextPush
90793 */
90794 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
90795   if( pContext->pParse ){
90796     pContext->pParse->zAuthContext = pContext->zAuthContext;
90797     pContext->pParse = 0;
90798   }
90799 }
90800 
90801 #endif /* SQLITE_OMIT_AUTHORIZATION */
90802 
90803 /************** End of auth.c ************************************************/
90804 /************** Begin file build.c *******************************************/
90805 /*
90806 ** 2001 September 15
90807 **
90808 ** The author disclaims copyright to this source code.  In place of
90809 ** a legal notice, here is a blessing:
90810 **
90811 **    May you do good and not evil.
90812 **    May you find forgiveness for yourself and forgive others.
90813 **    May you share freely, never taking more than you give.
90814 **
90815 *************************************************************************
90816 ** This file contains C code routines that are called by the SQLite parser
90817 ** when syntax rules are reduced.  The routines in this file handle the
90818 ** following kinds of SQL syntax:
90819 **
90820 **     CREATE TABLE
90821 **     DROP TABLE
90822 **     CREATE INDEX
90823 **     DROP INDEX
90824 **     creating ID lists
90825 **     BEGIN TRANSACTION
90826 **     COMMIT
90827 **     ROLLBACK
90828 */
90829 
90830 /*
90831 ** This routine is called when a new SQL statement is beginning to
90832 ** be parsed.  Initialize the pParse structure as needed.
90833 */
90834 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
90835   pParse->explain = (u8)explainFlag;
90836   pParse->nVar = 0;
90837 }
90838 
90839 #ifndef SQLITE_OMIT_SHARED_CACHE
90840 /*
90841 ** The TableLock structure is only used by the sqlite3TableLock() and
90842 ** codeTableLocks() functions.
90843 */
90844 struct TableLock {
90845   int iDb;             /* The database containing the table to be locked */
90846   int iTab;            /* The root page of the table to be locked */
90847   u8 isWriteLock;      /* True for write lock.  False for a read lock */
90848   const char *zName;   /* Name of the table */
90849 };
90850 
90851 /*
90852 ** Record the fact that we want to lock a table at run-time.
90853 **
90854 ** The table to be locked has root page iTab and is found in database iDb.
90855 ** A read or a write lock can be taken depending on isWritelock.
90856 **
90857 ** This routine just records the fact that the lock is desired.  The
90858 ** code to make the lock occur is generated by a later call to
90859 ** codeTableLocks() which occurs during sqlite3FinishCoding().
90860 */
90861 SQLITE_PRIVATE void sqlite3TableLock(
90862   Parse *pParse,     /* Parsing context */
90863   int iDb,           /* Index of the database containing the table to lock */
90864   int iTab,          /* Root page number of the table to be locked */
90865   u8 isWriteLock,    /* True for a write lock */
90866   const char *zName  /* Name of the table to be locked */
90867 ){
90868   Parse *pToplevel = sqlite3ParseToplevel(pParse);
90869   int i;
90870   int nBytes;
90871   TableLock *p;
90872   assert( iDb>=0 );
90873 
90874   for(i=0; i<pToplevel->nTableLock; i++){
90875     p = &pToplevel->aTableLock[i];
90876     if( p->iDb==iDb && p->iTab==iTab ){
90877       p->isWriteLock = (p->isWriteLock || isWriteLock);
90878       return;
90879     }
90880   }
90881 
90882   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
90883   pToplevel->aTableLock =
90884       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
90885   if( pToplevel->aTableLock ){
90886     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
90887     p->iDb = iDb;
90888     p->iTab = iTab;
90889     p->isWriteLock = isWriteLock;
90890     p->zName = zName;
90891   }else{
90892     pToplevel->nTableLock = 0;
90893     pToplevel->db->mallocFailed = 1;
90894   }
90895 }
90896 
90897 /*
90898 ** Code an OP_TableLock instruction for each table locked by the
90899 ** statement (configured by calls to sqlite3TableLock()).
90900 */
90901 static void codeTableLocks(Parse *pParse){
90902   int i;
90903   Vdbe *pVdbe;
90904 
90905   pVdbe = sqlite3GetVdbe(pParse);
90906   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
90907 
90908   for(i=0; i<pParse->nTableLock; i++){
90909     TableLock *p = &pParse->aTableLock[i];
90910     int p1 = p->iDb;
90911     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
90912                       p->zName, P4_STATIC);
90913   }
90914 }
90915 #else
90916   #define codeTableLocks(x)
90917 #endif
90918 
90919 /*
90920 ** Return TRUE if the given yDbMask object is empty - if it contains no
90921 ** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
90922 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
90923 */
90924 #if SQLITE_MAX_ATTACHED>30
90925 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
90926   int i;
90927   for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
90928   return 1;
90929 }
90930 #endif
90931 
90932 /*
90933 ** This routine is called after a single SQL statement has been
90934 ** parsed and a VDBE program to execute that statement has been
90935 ** prepared.  This routine puts the finishing touches on the
90936 ** VDBE program and resets the pParse structure for the next
90937 ** parse.
90938 **
90939 ** Note that if an error occurred, it might be the case that
90940 ** no VDBE code was generated.
90941 */
90942 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
90943   sqlite3 *db;
90944   Vdbe *v;
90945 
90946   assert( pParse->pToplevel==0 );
90947   db = pParse->db;
90948   if( pParse->nested ) return;
90949   if( db->mallocFailed || pParse->nErr ){
90950     if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
90951     return;
90952   }
90953 
90954   /* Begin by generating some termination code at the end of the
90955   ** vdbe program
90956   */
90957   v = sqlite3GetVdbe(pParse);
90958   assert( !pParse->isMultiWrite
90959        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
90960   if( v ){
90961     while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
90962     sqlite3VdbeAddOp0(v, OP_Halt);
90963 
90964 #if SQLITE_USER_AUTHENTICATION
90965     if( pParse->nTableLock>0 && db->init.busy==0 ){
90966       sqlite3UserAuthInit(db);
90967       if( db->auth.authLevel<UAUTH_User ){
90968         pParse->rc = SQLITE_AUTH_USER;
90969         sqlite3ErrorMsg(pParse, "user not authenticated");
90970         return;
90971       }
90972     }
90973 #endif
90974 
90975     /* The cookie mask contains one bit for each database file open.
90976     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
90977     ** set for each database that is used.  Generate code to start a
90978     ** transaction on each used database and to verify the schema cookie
90979     ** on each used database.
90980     */
90981     if( db->mallocFailed==0
90982      && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
90983     ){
90984       int iDb, i;
90985       assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
90986       sqlite3VdbeJumpHere(v, 0);
90987       for(iDb=0; iDb<db->nDb; iDb++){
90988         if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
90989         sqlite3VdbeUsesBtree(v, iDb);
90990         sqlite3VdbeAddOp4Int(v,
90991           OP_Transaction,                    /* Opcode */
90992           iDb,                               /* P1 */
90993           DbMaskTest(pParse->writeMask,iDb), /* P2 */
90994           pParse->cookieValue[iDb],          /* P3 */
90995           db->aDb[iDb].pSchema->iGeneration  /* P4 */
90996         );
90997         if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
90998       }
90999 #ifndef SQLITE_OMIT_VIRTUALTABLE
91000       for(i=0; i<pParse->nVtabLock; i++){
91001         char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
91002         sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
91003       }
91004       pParse->nVtabLock = 0;
91005 #endif
91006 
91007       /* Once all the cookies have been verified and transactions opened,
91008       ** obtain the required table-locks. This is a no-op unless the
91009       ** shared-cache feature is enabled.
91010       */
91011       codeTableLocks(pParse);
91012 
91013       /* Initialize any AUTOINCREMENT data structures required.
91014       */
91015       sqlite3AutoincrementBegin(pParse);
91016 
91017       /* Code constant expressions that where factored out of inner loops */
91018       if( pParse->pConstExpr ){
91019         ExprList *pEL = pParse->pConstExpr;
91020         pParse->okConstFactor = 0;
91021         for(i=0; i<pEL->nExpr; i++){
91022           sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
91023         }
91024       }
91025 
91026       /* Finally, jump back to the beginning of the executable code. */
91027       sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
91028     }
91029   }
91030 
91031 
91032   /* Get the VDBE program ready for execution
91033   */
91034   if( v && pParse->nErr==0 && !db->mallocFailed ){
91035     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
91036     /* A minimum of one cursor is required if autoincrement is used
91037     *  See ticket [a696379c1f08866] */
91038     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
91039     sqlite3VdbeMakeReady(v, pParse);
91040     pParse->rc = SQLITE_DONE;
91041     pParse->colNamesSet = 0;
91042   }else{
91043     pParse->rc = SQLITE_ERROR;
91044   }
91045   pParse->nTab = 0;
91046   pParse->nMem = 0;
91047   pParse->nSet = 0;
91048   pParse->nVar = 0;
91049   DbMaskZero(pParse->cookieMask);
91050 }
91051 
91052 /*
91053 ** Run the parser and code generator recursively in order to generate
91054 ** code for the SQL statement given onto the end of the pParse context
91055 ** currently under construction.  When the parser is run recursively
91056 ** this way, the final OP_Halt is not appended and other initialization
91057 ** and finalization steps are omitted because those are handling by the
91058 ** outermost parser.
91059 **
91060 ** Not everything is nestable.  This facility is designed to permit
91061 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
91062 ** care if you decide to try to use this routine for some other purposes.
91063 */
91064 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
91065   va_list ap;
91066   char *zSql;
91067   char *zErrMsg = 0;
91068   sqlite3 *db = pParse->db;
91069 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
91070   char saveBuf[SAVE_SZ];
91071 
91072   if( pParse->nErr ) return;
91073   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
91074   va_start(ap, zFormat);
91075   zSql = sqlite3VMPrintf(db, zFormat, ap);
91076   va_end(ap);
91077   if( zSql==0 ){
91078     return;   /* A malloc must have failed */
91079   }
91080   pParse->nested++;
91081   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
91082   memset(&pParse->nVar, 0, SAVE_SZ);
91083   sqlite3RunParser(pParse, zSql, &zErrMsg);
91084   sqlite3DbFree(db, zErrMsg);
91085   sqlite3DbFree(db, zSql);
91086   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
91087   pParse->nested--;
91088 }
91089 
91090 #if SQLITE_USER_AUTHENTICATION
91091 /*
91092 ** Return TRUE if zTable is the name of the system table that stores the
91093 ** list of users and their access credentials.
91094 */
91095 SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
91096   return sqlite3_stricmp(zTable, "sqlite_user")==0;
91097 }
91098 #endif
91099 
91100 /*
91101 ** Locate the in-memory structure that describes a particular database
91102 ** table given the name of that table and (optionally) the name of the
91103 ** database containing the table.  Return NULL if not found.
91104 **
91105 ** If zDatabase is 0, all databases are searched for the table and the
91106 ** first matching table is returned.  (No checking for duplicate table
91107 ** names is done.)  The search order is TEMP first, then MAIN, then any
91108 ** auxiliary databases added using the ATTACH command.
91109 **
91110 ** See also sqlite3LocateTable().
91111 */
91112 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
91113   Table *p = 0;
91114   int i;
91115 
91116   /* All mutexes are required for schema access.  Make sure we hold them. */
91117   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
91118 #if SQLITE_USER_AUTHENTICATION
91119   /* Only the admin user is allowed to know that the sqlite_user table
91120   ** exists */
91121   if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
91122     return 0;
91123   }
91124 #endif
91125   for(i=OMIT_TEMPDB; i<db->nDb; i++){
91126     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
91127     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
91128     assert( sqlite3SchemaMutexHeld(db, j, 0) );
91129     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
91130     if( p ) break;
91131   }
91132   return p;
91133 }
91134 
91135 /*
91136 ** Locate the in-memory structure that describes a particular database
91137 ** table given the name of that table and (optionally) the name of the
91138 ** database containing the table.  Return NULL if not found.  Also leave an
91139 ** error message in pParse->zErrMsg.
91140 **
91141 ** The difference between this routine and sqlite3FindTable() is that this
91142 ** routine leaves an error message in pParse->zErrMsg where
91143 ** sqlite3FindTable() does not.
91144 */
91145 SQLITE_PRIVATE Table *sqlite3LocateTable(
91146   Parse *pParse,         /* context in which to report errors */
91147   int isView,            /* True if looking for a VIEW rather than a TABLE */
91148   const char *zName,     /* Name of the table we are looking for */
91149   const char *zDbase     /* Name of the database.  Might be NULL */
91150 ){
91151   Table *p;
91152 
91153   /* Read the database schema. If an error occurs, leave an error message
91154   ** and code in pParse and return NULL. */
91155   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
91156     return 0;
91157   }
91158 
91159   p = sqlite3FindTable(pParse->db, zName, zDbase);
91160   if( p==0 ){
91161     const char *zMsg = isView ? "no such view" : "no such table";
91162     if( zDbase ){
91163       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
91164     }else{
91165       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
91166     }
91167     pParse->checkSchema = 1;
91168   }
91169 #if SQLITE_USER_AUTHENICATION
91170   else if( pParse->db->auth.authLevel<UAUTH_User ){
91171     sqlite3ErrorMsg(pParse, "user not authenticated");
91172     p = 0;
91173   }
91174 #endif
91175   return p;
91176 }
91177 
91178 /*
91179 ** Locate the table identified by *p.
91180 **
91181 ** This is a wrapper around sqlite3LocateTable(). The difference between
91182 ** sqlite3LocateTable() and this function is that this function restricts
91183 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
91184 ** non-NULL if it is part of a view or trigger program definition. See
91185 ** sqlite3FixSrcList() for details.
91186 */
91187 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
91188   Parse *pParse,
91189   int isView,
91190   struct SrcList_item *p
91191 ){
91192   const char *zDb;
91193   assert( p->pSchema==0 || p->zDatabase==0 );
91194   if( p->pSchema ){
91195     int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
91196     zDb = pParse->db->aDb[iDb].zName;
91197   }else{
91198     zDb = p->zDatabase;
91199   }
91200   return sqlite3LocateTable(pParse, isView, p->zName, zDb);
91201 }
91202 
91203 /*
91204 ** Locate the in-memory structure that describes
91205 ** a particular index given the name of that index
91206 ** and the name of the database that contains the index.
91207 ** Return NULL if not found.
91208 **
91209 ** If zDatabase is 0, all databases are searched for the
91210 ** table and the first matching index is returned.  (No checking
91211 ** for duplicate index names is done.)  The search order is
91212 ** TEMP first, then MAIN, then any auxiliary databases added
91213 ** using the ATTACH command.
91214 */
91215 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
91216   Index *p = 0;
91217   int i;
91218   /* All mutexes are required for schema access.  Make sure we hold them. */
91219   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
91220   for(i=OMIT_TEMPDB; i<db->nDb; i++){
91221     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
91222     Schema *pSchema = db->aDb[j].pSchema;
91223     assert( pSchema );
91224     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
91225     assert( sqlite3SchemaMutexHeld(db, j, 0) );
91226     p = sqlite3HashFind(&pSchema->idxHash, zName);
91227     if( p ) break;
91228   }
91229   return p;
91230 }
91231 
91232 /*
91233 ** Reclaim the memory used by an index
91234 */
91235 static void freeIndex(sqlite3 *db, Index *p){
91236 #ifndef SQLITE_OMIT_ANALYZE
91237   sqlite3DeleteIndexSamples(db, p);
91238 #endif
91239   sqlite3ExprDelete(db, p->pPartIdxWhere);
91240   sqlite3DbFree(db, p->zColAff);
91241   if( p->isResized ) sqlite3DbFree(db, p->azColl);
91242 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
91243   sqlite3_free(p->aiRowEst);
91244 #endif
91245   sqlite3DbFree(db, p);
91246 }
91247 
91248 /*
91249 ** For the index called zIdxName which is found in the database iDb,
91250 ** unlike that index from its Table then remove the index from
91251 ** the index hash table and free all memory structures associated
91252 ** with the index.
91253 */
91254 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
91255   Index *pIndex;
91256   Hash *pHash;
91257 
91258   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91259   pHash = &db->aDb[iDb].pSchema->idxHash;
91260   pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
91261   if( ALWAYS(pIndex) ){
91262     if( pIndex->pTable->pIndex==pIndex ){
91263       pIndex->pTable->pIndex = pIndex->pNext;
91264     }else{
91265       Index *p;
91266       /* Justification of ALWAYS();  The index must be on the list of
91267       ** indices. */
91268       p = pIndex->pTable->pIndex;
91269       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
91270       if( ALWAYS(p && p->pNext==pIndex) ){
91271         p->pNext = pIndex->pNext;
91272       }
91273     }
91274     freeIndex(db, pIndex);
91275   }
91276   db->flags |= SQLITE_InternChanges;
91277 }
91278 
91279 /*
91280 ** Look through the list of open database files in db->aDb[] and if
91281 ** any have been closed, remove them from the list.  Reallocate the
91282 ** db->aDb[] structure to a smaller size, if possible.
91283 **
91284 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
91285 ** are never candidates for being collapsed.
91286 */
91287 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
91288   int i, j;
91289   for(i=j=2; i<db->nDb; i++){
91290     struct Db *pDb = &db->aDb[i];
91291     if( pDb->pBt==0 ){
91292       sqlite3DbFree(db, pDb->zName);
91293       pDb->zName = 0;
91294       continue;
91295     }
91296     if( j<i ){
91297       db->aDb[j] = db->aDb[i];
91298     }
91299     j++;
91300   }
91301   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
91302   db->nDb = j;
91303   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
91304     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
91305     sqlite3DbFree(db, db->aDb);
91306     db->aDb = db->aDbStatic;
91307   }
91308 }
91309 
91310 /*
91311 ** Reset the schema for the database at index iDb.  Also reset the
91312 ** TEMP schema.
91313 */
91314 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
91315   Db *pDb;
91316   assert( iDb<db->nDb );
91317 
91318   /* Case 1:  Reset the single schema identified by iDb */
91319   pDb = &db->aDb[iDb];
91320   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91321   assert( pDb->pSchema!=0 );
91322   sqlite3SchemaClear(pDb->pSchema);
91323 
91324   /* If any database other than TEMP is reset, then also reset TEMP
91325   ** since TEMP might be holding triggers that reference tables in the
91326   ** other database.
91327   */
91328   if( iDb!=1 ){
91329     pDb = &db->aDb[1];
91330     assert( pDb->pSchema!=0 );
91331     sqlite3SchemaClear(pDb->pSchema);
91332   }
91333   return;
91334 }
91335 
91336 /*
91337 ** Erase all schema information from all attached databases (including
91338 ** "main" and "temp") for a single database connection.
91339 */
91340 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
91341   int i;
91342   sqlite3BtreeEnterAll(db);
91343   for(i=0; i<db->nDb; i++){
91344     Db *pDb = &db->aDb[i];
91345     if( pDb->pSchema ){
91346       sqlite3SchemaClear(pDb->pSchema);
91347     }
91348   }
91349   db->flags &= ~SQLITE_InternChanges;
91350   sqlite3VtabUnlockList(db);
91351   sqlite3BtreeLeaveAll(db);
91352   sqlite3CollapseDatabaseArray(db);
91353 }
91354 
91355 /*
91356 ** This routine is called when a commit occurs.
91357 */
91358 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
91359   db->flags &= ~SQLITE_InternChanges;
91360 }
91361 
91362 /*
91363 ** Delete memory allocated for the column names of a table or view (the
91364 ** Table.aCol[] array).
91365 */
91366 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
91367   int i;
91368   Column *pCol;
91369   assert( pTable!=0 );
91370   if( (pCol = pTable->aCol)!=0 ){
91371     for(i=0; i<pTable->nCol; i++, pCol++){
91372       sqlite3DbFree(db, pCol->zName);
91373       sqlite3ExprDelete(db, pCol->pDflt);
91374       sqlite3DbFree(db, pCol->zDflt);
91375       sqlite3DbFree(db, pCol->zType);
91376       sqlite3DbFree(db, pCol->zColl);
91377     }
91378     sqlite3DbFree(db, pTable->aCol);
91379   }
91380 }
91381 
91382 /*
91383 ** Remove the memory data structures associated with the given
91384 ** Table.  No changes are made to disk by this routine.
91385 **
91386 ** This routine just deletes the data structure.  It does not unlink
91387 ** the table data structure from the hash table.  But it does destroy
91388 ** memory structures of the indices and foreign keys associated with
91389 ** the table.
91390 **
91391 ** The db parameter is optional.  It is needed if the Table object
91392 ** contains lookaside memory.  (Table objects in the schema do not use
91393 ** lookaside memory, but some ephemeral Table objects do.)  Or the
91394 ** db parameter can be used with db->pnBytesFreed to measure the memory
91395 ** used by the Table object.
91396 */
91397 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
91398   Index *pIndex, *pNext;
91399   TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
91400 
91401   assert( !pTable || pTable->nRef>0 );
91402 
91403   /* Do not delete the table until the reference count reaches zero. */
91404   if( !pTable ) return;
91405   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
91406 
91407   /* Record the number of outstanding lookaside allocations in schema Tables
91408   ** prior to doing any free() operations.  Since schema Tables do not use
91409   ** lookaside, this number should not change. */
91410   TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
91411                          db->lookaside.nOut : 0 );
91412 
91413   /* Delete all indices associated with this table. */
91414   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
91415     pNext = pIndex->pNext;
91416     assert( pIndex->pSchema==pTable->pSchema );
91417     if( !db || db->pnBytesFreed==0 ){
91418       char *zName = pIndex->zName;
91419       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
91420          &pIndex->pSchema->idxHash, zName, 0
91421       );
91422       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
91423       assert( pOld==pIndex || pOld==0 );
91424     }
91425     freeIndex(db, pIndex);
91426   }
91427 
91428   /* Delete any foreign keys attached to this table. */
91429   sqlite3FkDelete(db, pTable);
91430 
91431   /* Delete the Table structure itself.
91432   */
91433   sqliteDeleteColumnNames(db, pTable);
91434   sqlite3DbFree(db, pTable->zName);
91435   sqlite3DbFree(db, pTable->zColAff);
91436   sqlite3SelectDelete(db, pTable->pSelect);
91437 #ifndef SQLITE_OMIT_CHECK
91438   sqlite3ExprListDelete(db, pTable->pCheck);
91439 #endif
91440 #ifndef SQLITE_OMIT_VIRTUALTABLE
91441   sqlite3VtabClear(db, pTable);
91442 #endif
91443   sqlite3DbFree(db, pTable);
91444 
91445   /* Verify that no lookaside memory was used by schema tables */
91446   assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
91447 }
91448 
91449 /*
91450 ** Unlink the given table from the hash tables and the delete the
91451 ** table structure with all its indices and foreign keys.
91452 */
91453 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
91454   Table *p;
91455   Db *pDb;
91456 
91457   assert( db!=0 );
91458   assert( iDb>=0 && iDb<db->nDb );
91459   assert( zTabName );
91460   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91461   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
91462   pDb = &db->aDb[iDb];
91463   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
91464   sqlite3DeleteTable(db, p);
91465   db->flags |= SQLITE_InternChanges;
91466 }
91467 
91468 /*
91469 ** Given a token, return a string that consists of the text of that
91470 ** token.  Space to hold the returned string
91471 ** is obtained from sqliteMalloc() and must be freed by the calling
91472 ** function.
91473 **
91474 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
91475 ** surround the body of the token are removed.
91476 **
91477 ** Tokens are often just pointers into the original SQL text and so
91478 ** are not \000 terminated and are not persistent.  The returned string
91479 ** is \000 terminated and is persistent.
91480 */
91481 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
91482   char *zName;
91483   if( pName ){
91484     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
91485     sqlite3Dequote(zName);
91486   }else{
91487     zName = 0;
91488   }
91489   return zName;
91490 }
91491 
91492 /*
91493 ** Open the sqlite_master table stored in database number iDb for
91494 ** writing. The table is opened using cursor 0.
91495 */
91496 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
91497   Vdbe *v = sqlite3GetVdbe(p);
91498   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
91499   sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
91500   if( p->nTab==0 ){
91501     p->nTab = 1;
91502   }
91503 }
91504 
91505 /*
91506 ** Parameter zName points to a nul-terminated buffer containing the name
91507 ** of a database ("main", "temp" or the name of an attached db). This
91508 ** function returns the index of the named database in db->aDb[], or
91509 ** -1 if the named db cannot be found.
91510 */
91511 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
91512   int i = -1;         /* Database number */
91513   if( zName ){
91514     Db *pDb;
91515     int n = sqlite3Strlen30(zName);
91516     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
91517       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
91518           0==sqlite3StrICmp(pDb->zName, zName) ){
91519         break;
91520       }
91521     }
91522   }
91523   return i;
91524 }
91525 
91526 /*
91527 ** The token *pName contains the name of a database (either "main" or
91528 ** "temp" or the name of an attached db). This routine returns the
91529 ** index of the named database in db->aDb[], or -1 if the named db
91530 ** does not exist.
91531 */
91532 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
91533   int i;                               /* Database number */
91534   char *zName;                         /* Name we are searching for */
91535   zName = sqlite3NameFromToken(db, pName);
91536   i = sqlite3FindDbName(db, zName);
91537   sqlite3DbFree(db, zName);
91538   return i;
91539 }
91540 
91541 /* The table or view or trigger name is passed to this routine via tokens
91542 ** pName1 and pName2. If the table name was fully qualified, for example:
91543 **
91544 ** CREATE TABLE xxx.yyy (...);
91545 **
91546 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
91547 ** the table name is not fully qualified, i.e.:
91548 **
91549 ** CREATE TABLE yyy(...);
91550 **
91551 ** Then pName1 is set to "yyy" and pName2 is "".
91552 **
91553 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
91554 ** pName2) that stores the unqualified table name.  The index of the
91555 ** database "xxx" is returned.
91556 */
91557 SQLITE_PRIVATE int sqlite3TwoPartName(
91558   Parse *pParse,      /* Parsing and code generating context */
91559   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
91560   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
91561   Token **pUnqual     /* Write the unqualified object name here */
91562 ){
91563   int iDb;                    /* Database holding the object */
91564   sqlite3 *db = pParse->db;
91565 
91566   if( ALWAYS(pName2!=0) && pName2->n>0 ){
91567     if( db->init.busy ) {
91568       sqlite3ErrorMsg(pParse, "corrupt database");
91569       return -1;
91570     }
91571     *pUnqual = pName2;
91572     iDb = sqlite3FindDb(db, pName1);
91573     if( iDb<0 ){
91574       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
91575       return -1;
91576     }
91577   }else{
91578     assert( db->init.iDb==0 || db->init.busy );
91579     iDb = db->init.iDb;
91580     *pUnqual = pName1;
91581   }
91582   return iDb;
91583 }
91584 
91585 /*
91586 ** This routine is used to check if the UTF-8 string zName is a legal
91587 ** unqualified name for a new schema object (table, index, view or
91588 ** trigger). All names are legal except those that begin with the string
91589 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
91590 ** is reserved for internal use.
91591 */
91592 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
91593   if( !pParse->db->init.busy && pParse->nested==0
91594           && (pParse->db->flags & SQLITE_WriteSchema)==0
91595           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
91596     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
91597     return SQLITE_ERROR;
91598   }
91599   return SQLITE_OK;
91600 }
91601 
91602 /*
91603 ** Return the PRIMARY KEY index of a table
91604 */
91605 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
91606   Index *p;
91607   for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
91608   return p;
91609 }
91610 
91611 /*
91612 ** Return the column of index pIdx that corresponds to table
91613 ** column iCol.  Return -1 if not found.
91614 */
91615 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
91616   int i;
91617   for(i=0; i<pIdx->nColumn; i++){
91618     if( iCol==pIdx->aiColumn[i] ) return i;
91619   }
91620   return -1;
91621 }
91622 
91623 /*
91624 ** Begin constructing a new table representation in memory.  This is
91625 ** the first of several action routines that get called in response
91626 ** to a CREATE TABLE statement.  In particular, this routine is called
91627 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
91628 ** flag is true if the table should be stored in the auxiliary database
91629 ** file instead of in the main database file.  This is normally the case
91630 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
91631 ** CREATE and TABLE.
91632 **
91633 ** The new table record is initialized and put in pParse->pNewTable.
91634 ** As more of the CREATE TABLE statement is parsed, additional action
91635 ** routines will be called to add more information to this record.
91636 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
91637 ** is called to complete the construction of the new table record.
91638 */
91639 SQLITE_PRIVATE void sqlite3StartTable(
91640   Parse *pParse,   /* Parser context */
91641   Token *pName1,   /* First part of the name of the table or view */
91642   Token *pName2,   /* Second part of the name of the table or view */
91643   int isTemp,      /* True if this is a TEMP table */
91644   int isView,      /* True if this is a VIEW */
91645   int isVirtual,   /* True if this is a VIRTUAL table */
91646   int noErr        /* Do nothing if table already exists */
91647 ){
91648   Table *pTable;
91649   char *zName = 0; /* The name of the new table */
91650   sqlite3 *db = pParse->db;
91651   Vdbe *v;
91652   int iDb;         /* Database number to create the table in */
91653   Token *pName;    /* Unqualified name of the table to create */
91654 
91655   /* The table or view name to create is passed to this routine via tokens
91656   ** pName1 and pName2. If the table name was fully qualified, for example:
91657   **
91658   ** CREATE TABLE xxx.yyy (...);
91659   **
91660   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
91661   ** the table name is not fully qualified, i.e.:
91662   **
91663   ** CREATE TABLE yyy(...);
91664   **
91665   ** Then pName1 is set to "yyy" and pName2 is "".
91666   **
91667   ** The call below sets the pName pointer to point at the token (pName1 or
91668   ** pName2) that stores the unqualified table name. The variable iDb is
91669   ** set to the index of the database that the table or view is to be
91670   ** created in.
91671   */
91672   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
91673   if( iDb<0 ) return;
91674   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
91675     /* If creating a temp table, the name may not be qualified. Unless
91676     ** the database name is "temp" anyway.  */
91677     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
91678     return;
91679   }
91680   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
91681 
91682   pParse->sNameToken = *pName;
91683   zName = sqlite3NameFromToken(db, pName);
91684   if( zName==0 ) return;
91685   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
91686     goto begin_table_error;
91687   }
91688   if( db->init.iDb==1 ) isTemp = 1;
91689 #ifndef SQLITE_OMIT_AUTHORIZATION
91690   assert( (isTemp & 1)==isTemp );
91691   {
91692     int code;
91693     char *zDb = db->aDb[iDb].zName;
91694     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
91695       goto begin_table_error;
91696     }
91697     if( isView ){
91698       if( !OMIT_TEMPDB && isTemp ){
91699         code = SQLITE_CREATE_TEMP_VIEW;
91700       }else{
91701         code = SQLITE_CREATE_VIEW;
91702       }
91703     }else{
91704       if( !OMIT_TEMPDB && isTemp ){
91705         code = SQLITE_CREATE_TEMP_TABLE;
91706       }else{
91707         code = SQLITE_CREATE_TABLE;
91708       }
91709     }
91710     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
91711       goto begin_table_error;
91712     }
91713   }
91714 #endif
91715 
91716   /* Make sure the new table name does not collide with an existing
91717   ** index or table name in the same database.  Issue an error message if
91718   ** it does. The exception is if the statement being parsed was passed
91719   ** to an sqlite3_declare_vtab() call. In that case only the column names
91720   ** and types will be used, so there is no need to test for namespace
91721   ** collisions.
91722   */
91723   if( !IN_DECLARE_VTAB ){
91724     char *zDb = db->aDb[iDb].zName;
91725     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
91726       goto begin_table_error;
91727     }
91728     pTable = sqlite3FindTable(db, zName, zDb);
91729     if( pTable ){
91730       if( !noErr ){
91731         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
91732       }else{
91733         assert( !db->init.busy || CORRUPT_DB );
91734         sqlite3CodeVerifySchema(pParse, iDb);
91735       }
91736       goto begin_table_error;
91737     }
91738     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
91739       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
91740       goto begin_table_error;
91741     }
91742   }
91743 
91744   pTable = sqlite3DbMallocZero(db, sizeof(Table));
91745   if( pTable==0 ){
91746     db->mallocFailed = 1;
91747     pParse->rc = SQLITE_NOMEM;
91748     pParse->nErr++;
91749     goto begin_table_error;
91750   }
91751   pTable->zName = zName;
91752   pTable->iPKey = -1;
91753   pTable->pSchema = db->aDb[iDb].pSchema;
91754   pTable->nRef = 1;
91755   pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
91756   assert( pParse->pNewTable==0 );
91757   pParse->pNewTable = pTable;
91758 
91759   /* If this is the magic sqlite_sequence table used by autoincrement,
91760   ** then record a pointer to this table in the main database structure
91761   ** so that INSERT can find the table easily.
91762   */
91763 #ifndef SQLITE_OMIT_AUTOINCREMENT
91764   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
91765     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91766     pTable->pSchema->pSeqTab = pTable;
91767   }
91768 #endif
91769 
91770   /* Begin generating the code that will insert the table record into
91771   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
91772   ** and allocate the record number for the table entry now.  Before any
91773   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
91774   ** indices to be created and the table record must come before the
91775   ** indices.  Hence, the record number for the table must be allocated
91776   ** now.
91777   */
91778   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
91779     int j1;
91780     int fileFormat;
91781     int reg1, reg2, reg3;
91782     sqlite3BeginWriteOperation(pParse, 0, iDb);
91783 
91784 #ifndef SQLITE_OMIT_VIRTUALTABLE
91785     if( isVirtual ){
91786       sqlite3VdbeAddOp0(v, OP_VBegin);
91787     }
91788 #endif
91789 
91790     /* If the file format and encoding in the database have not been set,
91791     ** set them now.
91792     */
91793     reg1 = pParse->regRowid = ++pParse->nMem;
91794     reg2 = pParse->regRoot = ++pParse->nMem;
91795     reg3 = ++pParse->nMem;
91796     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
91797     sqlite3VdbeUsesBtree(v, iDb);
91798     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
91799     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
91800                   1 : SQLITE_MAX_FILE_FORMAT;
91801     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
91802     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
91803     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
91804     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
91805     sqlite3VdbeJumpHere(v, j1);
91806 
91807     /* This just creates a place-holder record in the sqlite_master table.
91808     ** The record created does not contain anything yet.  It will be replaced
91809     ** by the real entry in code generated at sqlite3EndTable().
91810     **
91811     ** The rowid for the new entry is left in register pParse->regRowid.
91812     ** The root page number of the new table is left in reg pParse->regRoot.
91813     ** The rowid and root page number values are needed by the code that
91814     ** sqlite3EndTable will generate.
91815     */
91816 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
91817     if( isView || isVirtual ){
91818       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
91819     }else
91820 #endif
91821     {
91822       pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
91823     }
91824     sqlite3OpenMasterTable(pParse, iDb);
91825     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
91826     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
91827     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
91828     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
91829     sqlite3VdbeAddOp0(v, OP_Close);
91830   }
91831 
91832   /* Normal (non-error) return. */
91833   return;
91834 
91835   /* If an error occurs, we jump here */
91836 begin_table_error:
91837   sqlite3DbFree(db, zName);
91838   return;
91839 }
91840 
91841 /*
91842 ** This macro is used to compare two strings in a case-insensitive manner.
91843 ** It is slightly faster than calling sqlite3StrICmp() directly, but
91844 ** produces larger code.
91845 **
91846 ** WARNING: This macro is not compatible with the strcmp() family. It
91847 ** returns true if the two strings are equal, otherwise false.
91848 */
91849 #define STRICMP(x, y) (\
91850 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
91851 sqlite3UpperToLower[*(unsigned char *)(y)]     \
91852 && sqlite3StrICmp((x)+1,(y)+1)==0 )
91853 
91854 /*
91855 ** Add a new column to the table currently being constructed.
91856 **
91857 ** The parser calls this routine once for each column declaration
91858 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
91859 ** first to get things going.  Then this routine is called for each
91860 ** column.
91861 */
91862 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
91863   Table *p;
91864   int i;
91865   char *z;
91866   Column *pCol;
91867   sqlite3 *db = pParse->db;
91868   if( (p = pParse->pNewTable)==0 ) return;
91869 #if SQLITE_MAX_COLUMN
91870   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
91871     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
91872     return;
91873   }
91874 #endif
91875   z = sqlite3NameFromToken(db, pName);
91876   if( z==0 ) return;
91877   for(i=0; i<p->nCol; i++){
91878     if( STRICMP(z, p->aCol[i].zName) ){
91879       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
91880       sqlite3DbFree(db, z);
91881       return;
91882     }
91883   }
91884   if( (p->nCol & 0x7)==0 ){
91885     Column *aNew;
91886     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
91887     if( aNew==0 ){
91888       sqlite3DbFree(db, z);
91889       return;
91890     }
91891     p->aCol = aNew;
91892   }
91893   pCol = &p->aCol[p->nCol];
91894   memset(pCol, 0, sizeof(p->aCol[0]));
91895   pCol->zName = z;
91896 
91897   /* If there is no type specified, columns have the default affinity
91898   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
91899   ** be called next to set pCol->affinity correctly.
91900   */
91901   pCol->affinity = SQLITE_AFF_NONE;
91902   pCol->szEst = 1;
91903   p->nCol++;
91904 }
91905 
91906 /*
91907 ** This routine is called by the parser while in the middle of
91908 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
91909 ** been seen on a column.  This routine sets the notNull flag on
91910 ** the column currently under construction.
91911 */
91912 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
91913   Table *p;
91914   p = pParse->pNewTable;
91915   if( p==0 || NEVER(p->nCol<1) ) return;
91916   p->aCol[p->nCol-1].notNull = (u8)onError;
91917 }
91918 
91919 /*
91920 ** Scan the column type name zType (length nType) and return the
91921 ** associated affinity type.
91922 **
91923 ** This routine does a case-independent search of zType for the
91924 ** substrings in the following table. If one of the substrings is
91925 ** found, the corresponding affinity is returned. If zType contains
91926 ** more than one of the substrings, entries toward the top of
91927 ** the table take priority. For example, if zType is 'BLOBINT',
91928 ** SQLITE_AFF_INTEGER is returned.
91929 **
91930 ** Substring     | Affinity
91931 ** --------------------------------
91932 ** 'INT'         | SQLITE_AFF_INTEGER
91933 ** 'CHAR'        | SQLITE_AFF_TEXT
91934 ** 'CLOB'        | SQLITE_AFF_TEXT
91935 ** 'TEXT'        | SQLITE_AFF_TEXT
91936 ** 'BLOB'        | SQLITE_AFF_NONE
91937 ** 'REAL'        | SQLITE_AFF_REAL
91938 ** 'FLOA'        | SQLITE_AFF_REAL
91939 ** 'DOUB'        | SQLITE_AFF_REAL
91940 **
91941 ** If none of the substrings in the above table are found,
91942 ** SQLITE_AFF_NUMERIC is returned.
91943 */
91944 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
91945   u32 h = 0;
91946   char aff = SQLITE_AFF_NUMERIC;
91947   const char *zChar = 0;
91948 
91949   if( zIn==0 ) return aff;
91950   while( zIn[0] ){
91951     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
91952     zIn++;
91953     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
91954       aff = SQLITE_AFF_TEXT;
91955       zChar = zIn;
91956     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
91957       aff = SQLITE_AFF_TEXT;
91958     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
91959       aff = SQLITE_AFF_TEXT;
91960     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
91961         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
91962       aff = SQLITE_AFF_NONE;
91963       if( zIn[0]=='(' ) zChar = zIn;
91964 #ifndef SQLITE_OMIT_FLOATING_POINT
91965     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
91966         && aff==SQLITE_AFF_NUMERIC ){
91967       aff = SQLITE_AFF_REAL;
91968     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
91969         && aff==SQLITE_AFF_NUMERIC ){
91970       aff = SQLITE_AFF_REAL;
91971     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
91972         && aff==SQLITE_AFF_NUMERIC ){
91973       aff = SQLITE_AFF_REAL;
91974 #endif
91975     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
91976       aff = SQLITE_AFF_INTEGER;
91977       break;
91978     }
91979   }
91980 
91981   /* If pszEst is not NULL, store an estimate of the field size.  The
91982   ** estimate is scaled so that the size of an integer is 1.  */
91983   if( pszEst ){
91984     *pszEst = 1;   /* default size is approx 4 bytes */
91985     if( aff<SQLITE_AFF_NUMERIC ){
91986       if( zChar ){
91987         while( zChar[0] ){
91988           if( sqlite3Isdigit(zChar[0]) ){
91989             int v = 0;
91990             sqlite3GetInt32(zChar, &v);
91991             v = v/4 + 1;
91992             if( v>255 ) v = 255;
91993             *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
91994             break;
91995           }
91996           zChar++;
91997         }
91998       }else{
91999         *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
92000       }
92001     }
92002   }
92003   return aff;
92004 }
92005 
92006 /*
92007 ** This routine is called by the parser while in the middle of
92008 ** parsing a CREATE TABLE statement.  The pFirst token is the first
92009 ** token in the sequence of tokens that describe the type of the
92010 ** column currently under construction.   pLast is the last token
92011 ** in the sequence.  Use this information to construct a string
92012 ** that contains the typename of the column and store that string
92013 ** in zType.
92014 */
92015 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
92016   Table *p;
92017   Column *pCol;
92018 
92019   p = pParse->pNewTable;
92020   if( p==0 || NEVER(p->nCol<1) ) return;
92021   pCol = &p->aCol[p->nCol-1];
92022   assert( pCol->zType==0 || CORRUPT_DB );
92023   sqlite3DbFree(pParse->db, pCol->zType);
92024   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
92025   pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
92026 }
92027 
92028 /*
92029 ** The expression is the default value for the most recently added column
92030 ** of the table currently under construction.
92031 **
92032 ** Default value expressions must be constant.  Raise an exception if this
92033 ** is not the case.
92034 **
92035 ** This routine is called by the parser while in the middle of
92036 ** parsing a CREATE TABLE statement.
92037 */
92038 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
92039   Table *p;
92040   Column *pCol;
92041   sqlite3 *db = pParse->db;
92042   p = pParse->pNewTable;
92043   if( p!=0 ){
92044     pCol = &(p->aCol[p->nCol-1]);
92045     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
92046       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
92047           pCol->zName);
92048     }else{
92049       /* A copy of pExpr is used instead of the original, as pExpr contains
92050       ** tokens that point to volatile memory. The 'span' of the expression
92051       ** is required by pragma table_info.
92052       */
92053       sqlite3ExprDelete(db, pCol->pDflt);
92054       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
92055       sqlite3DbFree(db, pCol->zDflt);
92056       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
92057                                      (int)(pSpan->zEnd - pSpan->zStart));
92058     }
92059   }
92060   sqlite3ExprDelete(db, pSpan->pExpr);
92061 }
92062 
92063 /*
92064 ** Designate the PRIMARY KEY for the table.  pList is a list of names
92065 ** of columns that form the primary key.  If pList is NULL, then the
92066 ** most recently added column of the table is the primary key.
92067 **
92068 ** A table can have at most one primary key.  If the table already has
92069 ** a primary key (and this is the second primary key) then create an
92070 ** error.
92071 **
92072 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
92073 ** then we will try to use that column as the rowid.  Set the Table.iPKey
92074 ** field of the table under construction to be the index of the
92075 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
92076 ** no INTEGER PRIMARY KEY.
92077 **
92078 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
92079 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
92080 */
92081 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
92082   Parse *pParse,    /* Parsing context */
92083   ExprList *pList,  /* List of field names to be indexed */
92084   int onError,      /* What to do with a uniqueness conflict */
92085   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
92086   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
92087 ){
92088   Table *pTab = pParse->pNewTable;
92089   char *zType = 0;
92090   int iCol = -1, i;
92091   int nTerm;
92092   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
92093   if( pTab->tabFlags & TF_HasPrimaryKey ){
92094     sqlite3ErrorMsg(pParse,
92095       "table \"%s\" has more than one primary key", pTab->zName);
92096     goto primary_key_exit;
92097   }
92098   pTab->tabFlags |= TF_HasPrimaryKey;
92099   if( pList==0 ){
92100     iCol = pTab->nCol - 1;
92101     pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
92102     zType = pTab->aCol[iCol].zType;
92103     nTerm = 1;
92104   }else{
92105     nTerm = pList->nExpr;
92106     for(i=0; i<nTerm; i++){
92107       for(iCol=0; iCol<pTab->nCol; iCol++){
92108         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
92109           pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
92110           zType = pTab->aCol[iCol].zType;
92111           break;
92112         }
92113       }
92114     }
92115   }
92116   if( nTerm==1
92117    && zType && sqlite3StrICmp(zType, "INTEGER")==0
92118    && sortOrder==SQLITE_SO_ASC
92119   ){
92120     pTab->iPKey = iCol;
92121     pTab->keyConf = (u8)onError;
92122     assert( autoInc==0 || autoInc==1 );
92123     pTab->tabFlags |= autoInc*TF_Autoincrement;
92124     if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
92125   }else if( autoInc ){
92126 #ifndef SQLITE_OMIT_AUTOINCREMENT
92127     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
92128        "INTEGER PRIMARY KEY");
92129 #endif
92130   }else{
92131     Vdbe *v = pParse->pVdbe;
92132     Index *p;
92133     if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
92134     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
92135                            0, sortOrder, 0);
92136     if( p ){
92137       p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
92138       if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
92139     }
92140     pList = 0;
92141   }
92142 
92143 primary_key_exit:
92144   sqlite3ExprListDelete(pParse->db, pList);
92145   return;
92146 }
92147 
92148 /*
92149 ** Add a new CHECK constraint to the table currently under construction.
92150 */
92151 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
92152   Parse *pParse,    /* Parsing context */
92153   Expr *pCheckExpr  /* The check expression */
92154 ){
92155 #ifndef SQLITE_OMIT_CHECK
92156   Table *pTab = pParse->pNewTable;
92157   sqlite3 *db = pParse->db;
92158   if( pTab && !IN_DECLARE_VTAB
92159    && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
92160   ){
92161     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
92162     if( pParse->constraintName.n ){
92163       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
92164     }
92165   }else
92166 #endif
92167   {
92168     sqlite3ExprDelete(pParse->db, pCheckExpr);
92169   }
92170 }
92171 
92172 /*
92173 ** Set the collation function of the most recently parsed table column
92174 ** to the CollSeq given.
92175 */
92176 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
92177   Table *p;
92178   int i;
92179   char *zColl;              /* Dequoted name of collation sequence */
92180   sqlite3 *db;
92181 
92182   if( (p = pParse->pNewTable)==0 ) return;
92183   i = p->nCol-1;
92184   db = pParse->db;
92185   zColl = sqlite3NameFromToken(db, pToken);
92186   if( !zColl ) return;
92187 
92188   if( sqlite3LocateCollSeq(pParse, zColl) ){
92189     Index *pIdx;
92190     sqlite3DbFree(db, p->aCol[i].zColl);
92191     p->aCol[i].zColl = zColl;
92192 
92193     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
92194     ** then an index may have been created on this column before the
92195     ** collation type was added. Correct this if it is the case.
92196     */
92197     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
92198       assert( pIdx->nKeyCol==1 );
92199       if( pIdx->aiColumn[0]==i ){
92200         pIdx->azColl[0] = p->aCol[i].zColl;
92201       }
92202     }
92203   }else{
92204     sqlite3DbFree(db, zColl);
92205   }
92206 }
92207 
92208 /*
92209 ** This function returns the collation sequence for database native text
92210 ** encoding identified by the string zName, length nName.
92211 **
92212 ** If the requested collation sequence is not available, or not available
92213 ** in the database native encoding, the collation factory is invoked to
92214 ** request it. If the collation factory does not supply such a sequence,
92215 ** and the sequence is available in another text encoding, then that is
92216 ** returned instead.
92217 **
92218 ** If no versions of the requested collations sequence are available, or
92219 ** another error occurs, NULL is returned and an error message written into
92220 ** pParse.
92221 **
92222 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
92223 ** invokes the collation factory if the named collation cannot be found
92224 ** and generates an error message.
92225 **
92226 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
92227 */
92228 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
92229   sqlite3 *db = pParse->db;
92230   u8 enc = ENC(db);
92231   u8 initbusy = db->init.busy;
92232   CollSeq *pColl;
92233 
92234   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
92235   if( !initbusy && (!pColl || !pColl->xCmp) ){
92236     pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
92237   }
92238 
92239   return pColl;
92240 }
92241 
92242 
92243 /*
92244 ** Generate code that will increment the schema cookie.
92245 **
92246 ** The schema cookie is used to determine when the schema for the
92247 ** database changes.  After each schema change, the cookie value
92248 ** changes.  When a process first reads the schema it records the
92249 ** cookie.  Thereafter, whenever it goes to access the database,
92250 ** it checks the cookie to make sure the schema has not changed
92251 ** since it was last read.
92252 **
92253 ** This plan is not completely bullet-proof.  It is possible for
92254 ** the schema to change multiple times and for the cookie to be
92255 ** set back to prior value.  But schema changes are infrequent
92256 ** and the probability of hitting the same cookie value is only
92257 ** 1 chance in 2^32.  So we're safe enough.
92258 */
92259 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
92260   int r1 = sqlite3GetTempReg(pParse);
92261   sqlite3 *db = pParse->db;
92262   Vdbe *v = pParse->pVdbe;
92263   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92264   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
92265   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
92266   sqlite3ReleaseTempReg(pParse, r1);
92267 }
92268 
92269 /*
92270 ** Measure the number of characters needed to output the given
92271 ** identifier.  The number returned includes any quotes used
92272 ** but does not include the null terminator.
92273 **
92274 ** The estimate is conservative.  It might be larger that what is
92275 ** really needed.
92276 */
92277 static int identLength(const char *z){
92278   int n;
92279   for(n=0; *z; n++, z++){
92280     if( *z=='"' ){ n++; }
92281   }
92282   return n + 2;
92283 }
92284 
92285 /*
92286 ** The first parameter is a pointer to an output buffer. The second
92287 ** parameter is a pointer to an integer that contains the offset at
92288 ** which to write into the output buffer. This function copies the
92289 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
92290 ** to the specified offset in the buffer and updates *pIdx to refer
92291 ** to the first byte after the last byte written before returning.
92292 **
92293 ** If the string zSignedIdent consists entirely of alpha-numeric
92294 ** characters, does not begin with a digit and is not an SQL keyword,
92295 ** then it is copied to the output buffer exactly as it is. Otherwise,
92296 ** it is quoted using double-quotes.
92297 */
92298 static void identPut(char *z, int *pIdx, char *zSignedIdent){
92299   unsigned char *zIdent = (unsigned char*)zSignedIdent;
92300   int i, j, needQuote;
92301   i = *pIdx;
92302 
92303   for(j=0; zIdent[j]; j++){
92304     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
92305   }
92306   needQuote = sqlite3Isdigit(zIdent[0])
92307             || sqlite3KeywordCode(zIdent, j)!=TK_ID
92308             || zIdent[j]!=0
92309             || j==0;
92310 
92311   if( needQuote ) z[i++] = '"';
92312   for(j=0; zIdent[j]; j++){
92313     z[i++] = zIdent[j];
92314     if( zIdent[j]=='"' ) z[i++] = '"';
92315   }
92316   if( needQuote ) z[i++] = '"';
92317   z[i] = 0;
92318   *pIdx = i;
92319 }
92320 
92321 /*
92322 ** Generate a CREATE TABLE statement appropriate for the given
92323 ** table.  Memory to hold the text of the statement is obtained
92324 ** from sqliteMalloc() and must be freed by the calling function.
92325 */
92326 static char *createTableStmt(sqlite3 *db, Table *p){
92327   int i, k, n;
92328   char *zStmt;
92329   char *zSep, *zSep2, *zEnd;
92330   Column *pCol;
92331   n = 0;
92332   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
92333     n += identLength(pCol->zName) + 5;
92334   }
92335   n += identLength(p->zName);
92336   if( n<50 ){
92337     zSep = "";
92338     zSep2 = ",";
92339     zEnd = ")";
92340   }else{
92341     zSep = "\n  ";
92342     zSep2 = ",\n  ";
92343     zEnd = "\n)";
92344   }
92345   n += 35 + 6*p->nCol;
92346   zStmt = sqlite3DbMallocRaw(0, n);
92347   if( zStmt==0 ){
92348     db->mallocFailed = 1;
92349     return 0;
92350   }
92351   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
92352   k = sqlite3Strlen30(zStmt);
92353   identPut(zStmt, &k, p->zName);
92354   zStmt[k++] = '(';
92355   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
92356     static const char * const azType[] = {
92357         /* SQLITE_AFF_NONE    */ "",
92358         /* SQLITE_AFF_TEXT    */ " TEXT",
92359         /* SQLITE_AFF_NUMERIC */ " NUM",
92360         /* SQLITE_AFF_INTEGER */ " INT",
92361         /* SQLITE_AFF_REAL    */ " REAL"
92362     };
92363     int len;
92364     const char *zType;
92365 
92366     sqlite3_snprintf(n-k, &zStmt[k], zSep);
92367     k += sqlite3Strlen30(&zStmt[k]);
92368     zSep = zSep2;
92369     identPut(zStmt, &k, pCol->zName);
92370     assert( pCol->affinity-SQLITE_AFF_NONE >= 0 );
92371     assert( pCol->affinity-SQLITE_AFF_NONE < ArraySize(azType) );
92372     testcase( pCol->affinity==SQLITE_AFF_NONE );
92373     testcase( pCol->affinity==SQLITE_AFF_TEXT );
92374     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
92375     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
92376     testcase( pCol->affinity==SQLITE_AFF_REAL );
92377 
92378     zType = azType[pCol->affinity - SQLITE_AFF_NONE];
92379     len = sqlite3Strlen30(zType);
92380     assert( pCol->affinity==SQLITE_AFF_NONE
92381             || pCol->affinity==sqlite3AffinityType(zType, 0) );
92382     memcpy(&zStmt[k], zType, len);
92383     k += len;
92384     assert( k<=n );
92385   }
92386   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
92387   return zStmt;
92388 }
92389 
92390 /*
92391 ** Resize an Index object to hold N columns total.  Return SQLITE_OK
92392 ** on success and SQLITE_NOMEM on an OOM error.
92393 */
92394 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
92395   char *zExtra;
92396   int nByte;
92397   if( pIdx->nColumn>=N ) return SQLITE_OK;
92398   assert( pIdx->isResized==0 );
92399   nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
92400   zExtra = sqlite3DbMallocZero(db, nByte);
92401   if( zExtra==0 ) return SQLITE_NOMEM;
92402   memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
92403   pIdx->azColl = (char**)zExtra;
92404   zExtra += sizeof(char*)*N;
92405   memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
92406   pIdx->aiColumn = (i16*)zExtra;
92407   zExtra += sizeof(i16)*N;
92408   memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
92409   pIdx->aSortOrder = (u8*)zExtra;
92410   pIdx->nColumn = N;
92411   pIdx->isResized = 1;
92412   return SQLITE_OK;
92413 }
92414 
92415 /*
92416 ** Estimate the total row width for a table.
92417 */
92418 static void estimateTableWidth(Table *pTab){
92419   unsigned wTable = 0;
92420   const Column *pTabCol;
92421   int i;
92422   for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
92423     wTable += pTabCol->szEst;
92424   }
92425   if( pTab->iPKey<0 ) wTable++;
92426   pTab->szTabRow = sqlite3LogEst(wTable*4);
92427 }
92428 
92429 /*
92430 ** Estimate the average size of a row for an index.
92431 */
92432 static void estimateIndexWidth(Index *pIdx){
92433   unsigned wIndex = 0;
92434   int i;
92435   const Column *aCol = pIdx->pTable->aCol;
92436   for(i=0; i<pIdx->nColumn; i++){
92437     i16 x = pIdx->aiColumn[i];
92438     assert( x<pIdx->pTable->nCol );
92439     wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
92440   }
92441   pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
92442 }
92443 
92444 /* Return true if value x is found any of the first nCol entries of aiCol[]
92445 */
92446 static int hasColumn(const i16 *aiCol, int nCol, int x){
92447   while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
92448   return 0;
92449 }
92450 
92451 /*
92452 ** This routine runs at the end of parsing a CREATE TABLE statement that
92453 ** has a WITHOUT ROWID clause.  The job of this routine is to convert both
92454 ** internal schema data structures and the generated VDBE code so that they
92455 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
92456 ** Changes include:
92457 **
92458 **     (1)  Convert the OP_CreateTable into an OP_CreateIndex.  There is
92459 **          no rowid btree for a WITHOUT ROWID.  Instead, the canonical
92460 **          data storage is a covering index btree.
92461 **     (2)  Bypass the creation of the sqlite_master table entry
92462 **          for the PRIMARY KEY as the primary key index is now
92463 **          identified by the sqlite_master table entry of the table itself.
92464 **     (3)  Set the Index.tnum of the PRIMARY KEY Index object in the
92465 **          schema to the rootpage from the main table.
92466 **     (4)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
92467 **     (5)  Add all table columns to the PRIMARY KEY Index object
92468 **          so that the PRIMARY KEY is a covering index.  The surplus
92469 **          columns are part of KeyInfo.nXField and are not used for
92470 **          sorting or lookup or uniqueness checks.
92471 **     (6)  Replace the rowid tail on all automatically generated UNIQUE
92472 **          indices with the PRIMARY KEY columns.
92473 */
92474 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
92475   Index *pIdx;
92476   Index *pPk;
92477   int nPk;
92478   int i, j;
92479   sqlite3 *db = pParse->db;
92480   Vdbe *v = pParse->pVdbe;
92481 
92482   /* Convert the OP_CreateTable opcode that would normally create the
92483   ** root-page for the table into an OP_CreateIndex opcode.  The index
92484   ** created will become the PRIMARY KEY index.
92485   */
92486   if( pParse->addrCrTab ){
92487     assert( v );
92488     sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
92489   }
92490 
92491   /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
92492   ** table entry.
92493   */
92494   if( pParse->addrSkipPK ){
92495     assert( v );
92496     sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
92497   }
92498 
92499   /* Locate the PRIMARY KEY index.  Or, if this table was originally
92500   ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
92501   */
92502   if( pTab->iPKey>=0 ){
92503     ExprList *pList;
92504     pList = sqlite3ExprListAppend(pParse, 0, 0);
92505     if( pList==0 ) return;
92506     pList->a[0].zName = sqlite3DbStrDup(pParse->db,
92507                                         pTab->aCol[pTab->iPKey].zName);
92508     pList->a[0].sortOrder = pParse->iPkSortOrder;
92509     assert( pParse->pNewTable==pTab );
92510     pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
92511     if( pPk==0 ) return;
92512     pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
92513     pTab->iPKey = -1;
92514   }else{
92515     pPk = sqlite3PrimaryKeyIndex(pTab);
92516     /*
92517     ** Remove all redundant columns from the PRIMARY KEY.  For example, change
92518     ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
92519     ** code assumes the PRIMARY KEY contains no repeated columns.
92520     */
92521     for(i=j=1; i<pPk->nKeyCol; i++){
92522       if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
92523         pPk->nColumn--;
92524       }else{
92525         pPk->aiColumn[j++] = pPk->aiColumn[i];
92526       }
92527     }
92528     pPk->nKeyCol = j;
92529   }
92530   pPk->isCovering = 1;
92531   assert( pPk!=0 );
92532   nPk = pPk->nKeyCol;
92533 
92534   /* Make sure every column of the PRIMARY KEY is NOT NULL.  (Except,
92535   ** do not enforce this for imposter tables.) */
92536   if( !db->init.imposterTable ){
92537     for(i=0; i<nPk; i++){
92538       pTab->aCol[pPk->aiColumn[i]].notNull = 1;
92539     }
92540     pPk->uniqNotNull = 1;
92541   }
92542 
92543   /* The root page of the PRIMARY KEY is the table root page */
92544   pPk->tnum = pTab->tnum;
92545 
92546   /* Update the in-memory representation of all UNIQUE indices by converting
92547   ** the final rowid column into one or more columns of the PRIMARY KEY.
92548   */
92549   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
92550     int n;
92551     if( IsPrimaryKeyIndex(pIdx) ) continue;
92552     for(i=n=0; i<nPk; i++){
92553       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
92554     }
92555     if( n==0 ){
92556       /* This index is a superset of the primary key */
92557       pIdx->nColumn = pIdx->nKeyCol;
92558       continue;
92559     }
92560     if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
92561     for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
92562       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
92563         pIdx->aiColumn[j] = pPk->aiColumn[i];
92564         pIdx->azColl[j] = pPk->azColl[i];
92565         j++;
92566       }
92567     }
92568     assert( pIdx->nColumn>=pIdx->nKeyCol+n );
92569     assert( pIdx->nColumn>=j );
92570   }
92571 
92572   /* Add all table columns to the PRIMARY KEY index
92573   */
92574   if( nPk<pTab->nCol ){
92575     if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
92576     for(i=0, j=nPk; i<pTab->nCol; i++){
92577       if( !hasColumn(pPk->aiColumn, j, i) ){
92578         assert( j<pPk->nColumn );
92579         pPk->aiColumn[j] = i;
92580         pPk->azColl[j] = "BINARY";
92581         j++;
92582       }
92583     }
92584     assert( pPk->nColumn==j );
92585     assert( pTab->nCol==j );
92586   }else{
92587     pPk->nColumn = pTab->nCol;
92588   }
92589 }
92590 
92591 /*
92592 ** This routine is called to report the final ")" that terminates
92593 ** a CREATE TABLE statement.
92594 **
92595 ** The table structure that other action routines have been building
92596 ** is added to the internal hash tables, assuming no errors have
92597 ** occurred.
92598 **
92599 ** An entry for the table is made in the master table on disk, unless
92600 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
92601 ** it means we are reading the sqlite_master table because we just
92602 ** connected to the database or because the sqlite_master table has
92603 ** recently changed, so the entry for this table already exists in
92604 ** the sqlite_master table.  We do not want to create it again.
92605 **
92606 ** If the pSelect argument is not NULL, it means that this routine
92607 ** was called to create a table generated from a
92608 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
92609 ** the new table will match the result set of the SELECT.
92610 */
92611 SQLITE_PRIVATE void sqlite3EndTable(
92612   Parse *pParse,          /* Parse context */
92613   Token *pCons,           /* The ',' token after the last column defn. */
92614   Token *pEnd,            /* The ')' before options in the CREATE TABLE */
92615   u8 tabOpts,             /* Extra table options. Usually 0. */
92616   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
92617 ){
92618   Table *p;                 /* The new table */
92619   sqlite3 *db = pParse->db; /* The database connection */
92620   int iDb;                  /* Database in which the table lives */
92621   Index *pIdx;              /* An implied index of the table */
92622 
92623   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
92624     return;
92625   }
92626   p = pParse->pNewTable;
92627   if( p==0 ) return;
92628 
92629   assert( !db->init.busy || !pSelect );
92630 
92631   /* If the db->init.busy is 1 it means we are reading the SQL off the
92632   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
92633   ** So do not write to the disk again.  Extract the root page number
92634   ** for the table from the db->init.newTnum field.  (The page number
92635   ** should have been put there by the sqliteOpenCb routine.)
92636   */
92637   if( db->init.busy ){
92638     p->tnum = db->init.newTnum;
92639   }
92640 
92641   /* Special processing for WITHOUT ROWID Tables */
92642   if( tabOpts & TF_WithoutRowid ){
92643     if( (p->tabFlags & TF_Autoincrement) ){
92644       sqlite3ErrorMsg(pParse,
92645           "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
92646       return;
92647     }
92648     if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
92649       sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
92650     }else{
92651       p->tabFlags |= TF_WithoutRowid;
92652       convertToWithoutRowidTable(pParse, p);
92653     }
92654   }
92655 
92656   iDb = sqlite3SchemaToIndex(db, p->pSchema);
92657 
92658 #ifndef SQLITE_OMIT_CHECK
92659   /* Resolve names in all CHECK constraint expressions.
92660   */
92661   if( p->pCheck ){
92662     sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
92663   }
92664 #endif /* !defined(SQLITE_OMIT_CHECK) */
92665 
92666   /* Estimate the average row size for the table and for all implied indices */
92667   estimateTableWidth(p);
92668   for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
92669     estimateIndexWidth(pIdx);
92670   }
92671 
92672   /* If not initializing, then create a record for the new table
92673   ** in the SQLITE_MASTER table of the database.
92674   **
92675   ** If this is a TEMPORARY table, write the entry into the auxiliary
92676   ** file instead of into the main database file.
92677   */
92678   if( !db->init.busy ){
92679     int n;
92680     Vdbe *v;
92681     char *zType;    /* "view" or "table" */
92682     char *zType2;   /* "VIEW" or "TABLE" */
92683     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
92684 
92685     v = sqlite3GetVdbe(pParse);
92686     if( NEVER(v==0) ) return;
92687 
92688     sqlite3VdbeAddOp1(v, OP_Close, 0);
92689 
92690     /*
92691     ** Initialize zType for the new view or table.
92692     */
92693     if( p->pSelect==0 ){
92694       /* A regular table */
92695       zType = "table";
92696       zType2 = "TABLE";
92697 #ifndef SQLITE_OMIT_VIEW
92698     }else{
92699       /* A view */
92700       zType = "view";
92701       zType2 = "VIEW";
92702 #endif
92703     }
92704 
92705     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
92706     ** statement to populate the new table. The root-page number for the
92707     ** new table is in register pParse->regRoot.
92708     **
92709     ** Once the SELECT has been coded by sqlite3Select(), it is in a
92710     ** suitable state to query for the column names and types to be used
92711     ** by the new table.
92712     **
92713     ** A shared-cache write-lock is not required to write to the new table,
92714     ** as a schema-lock must have already been obtained to create it. Since
92715     ** a schema-lock excludes all other database users, the write-lock would
92716     ** be redundant.
92717     */
92718     if( pSelect ){
92719       SelectDest dest;
92720       Table *pSelTab;
92721 
92722       assert(pParse->nTab==1);
92723       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
92724       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
92725       pParse->nTab = 2;
92726       sqlite3SelectDestInit(&dest, SRT_Table, 1);
92727       sqlite3Select(pParse, pSelect, &dest);
92728       sqlite3VdbeAddOp1(v, OP_Close, 1);
92729       if( pParse->nErr==0 ){
92730         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
92731         if( pSelTab==0 ) return;
92732         assert( p->aCol==0 );
92733         p->nCol = pSelTab->nCol;
92734         p->aCol = pSelTab->aCol;
92735         pSelTab->nCol = 0;
92736         pSelTab->aCol = 0;
92737         sqlite3DeleteTable(db, pSelTab);
92738       }
92739     }
92740 
92741     /* Compute the complete text of the CREATE statement */
92742     if( pSelect ){
92743       zStmt = createTableStmt(db, p);
92744     }else{
92745       Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
92746       n = (int)(pEnd2->z - pParse->sNameToken.z);
92747       if( pEnd2->z[0]!=';' ) n += pEnd2->n;
92748       zStmt = sqlite3MPrintf(db,
92749           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
92750       );
92751     }
92752 
92753     /* A slot for the record has already been allocated in the
92754     ** SQLITE_MASTER table.  We just need to update that slot with all
92755     ** the information we've collected.
92756     */
92757     sqlite3NestedParse(pParse,
92758       "UPDATE %Q.%s "
92759          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
92760        "WHERE rowid=#%d",
92761       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
92762       zType,
92763       p->zName,
92764       p->zName,
92765       pParse->regRoot,
92766       zStmt,
92767       pParse->regRowid
92768     );
92769     sqlite3DbFree(db, zStmt);
92770     sqlite3ChangeCookie(pParse, iDb);
92771 
92772 #ifndef SQLITE_OMIT_AUTOINCREMENT
92773     /* Check to see if we need to create an sqlite_sequence table for
92774     ** keeping track of autoincrement keys.
92775     */
92776     if( p->tabFlags & TF_Autoincrement ){
92777       Db *pDb = &db->aDb[iDb];
92778       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92779       if( pDb->pSchema->pSeqTab==0 ){
92780         sqlite3NestedParse(pParse,
92781           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
92782           pDb->zName
92783         );
92784       }
92785     }
92786 #endif
92787 
92788     /* Reparse everything to update our internal data structures */
92789     sqlite3VdbeAddParseSchemaOp(v, iDb,
92790            sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
92791   }
92792 
92793 
92794   /* Add the table to the in-memory representation of the database.
92795   */
92796   if( db->init.busy ){
92797     Table *pOld;
92798     Schema *pSchema = p->pSchema;
92799     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92800     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
92801     if( pOld ){
92802       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
92803       db->mallocFailed = 1;
92804       return;
92805     }
92806     pParse->pNewTable = 0;
92807     db->flags |= SQLITE_InternChanges;
92808 
92809 #ifndef SQLITE_OMIT_ALTERTABLE
92810     if( !p->pSelect ){
92811       const char *zName = (const char *)pParse->sNameToken.z;
92812       int nName;
92813       assert( !pSelect && pCons && pEnd );
92814       if( pCons->z==0 ){
92815         pCons = pEnd;
92816       }
92817       nName = (int)((const char *)pCons->z - zName);
92818       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
92819     }
92820 #endif
92821   }
92822 }
92823 
92824 #ifndef SQLITE_OMIT_VIEW
92825 /*
92826 ** The parser calls this routine in order to create a new VIEW
92827 */
92828 SQLITE_PRIVATE void sqlite3CreateView(
92829   Parse *pParse,     /* The parsing context */
92830   Token *pBegin,     /* The CREATE token that begins the statement */
92831   Token *pName1,     /* The token that holds the name of the view */
92832   Token *pName2,     /* The token that holds the name of the view */
92833   Select *pSelect,   /* A SELECT statement that will become the new view */
92834   int isTemp,        /* TRUE for a TEMPORARY view */
92835   int noErr          /* Suppress error messages if VIEW already exists */
92836 ){
92837   Table *p;
92838   int n;
92839   const char *z;
92840   Token sEnd;
92841   DbFixer sFix;
92842   Token *pName = 0;
92843   int iDb;
92844   sqlite3 *db = pParse->db;
92845 
92846   if( pParse->nVar>0 ){
92847     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
92848     sqlite3SelectDelete(db, pSelect);
92849     return;
92850   }
92851   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
92852   p = pParse->pNewTable;
92853   if( p==0 || pParse->nErr ){
92854     sqlite3SelectDelete(db, pSelect);
92855     return;
92856   }
92857   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
92858   iDb = sqlite3SchemaToIndex(db, p->pSchema);
92859   sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
92860   if( sqlite3FixSelect(&sFix, pSelect) ){
92861     sqlite3SelectDelete(db, pSelect);
92862     return;
92863   }
92864 
92865   /* Make a copy of the entire SELECT statement that defines the view.
92866   ** This will force all the Expr.token.z values to be dynamically
92867   ** allocated rather than point to the input string - which means that
92868   ** they will persist after the current sqlite3_exec() call returns.
92869   */
92870   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
92871   sqlite3SelectDelete(db, pSelect);
92872   if( db->mallocFailed ){
92873     return;
92874   }
92875   if( !db->init.busy ){
92876     sqlite3ViewGetColumnNames(pParse, p);
92877   }
92878 
92879   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
92880   ** the end.
92881   */
92882   sEnd = pParse->sLastToken;
92883   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
92884     sEnd.z += sEnd.n;
92885   }
92886   sEnd.n = 0;
92887   n = (int)(sEnd.z - pBegin->z);
92888   z = pBegin->z;
92889   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
92890   sEnd.z = &z[n-1];
92891   sEnd.n = 1;
92892 
92893   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
92894   sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
92895   return;
92896 }
92897 #endif /* SQLITE_OMIT_VIEW */
92898 
92899 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
92900 /*
92901 ** The Table structure pTable is really a VIEW.  Fill in the names of
92902 ** the columns of the view in the pTable structure.  Return the number
92903 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
92904 */
92905 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
92906   Table *pSelTab;   /* A fake table from which we get the result set */
92907   Select *pSel;     /* Copy of the SELECT that implements the view */
92908   int nErr = 0;     /* Number of errors encountered */
92909   int n;            /* Temporarily holds the number of cursors assigned */
92910   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
92911   sqlite3_xauth xAuth;       /* Saved xAuth pointer */
92912 
92913   assert( pTable );
92914 
92915 #ifndef SQLITE_OMIT_VIRTUALTABLE
92916   if( sqlite3VtabCallConnect(pParse, pTable) ){
92917     return SQLITE_ERROR;
92918   }
92919   if( IsVirtual(pTable) ) return 0;
92920 #endif
92921 
92922 #ifndef SQLITE_OMIT_VIEW
92923   /* A positive nCol means the columns names for this view are
92924   ** already known.
92925   */
92926   if( pTable->nCol>0 ) return 0;
92927 
92928   /* A negative nCol is a special marker meaning that we are currently
92929   ** trying to compute the column names.  If we enter this routine with
92930   ** a negative nCol, it means two or more views form a loop, like this:
92931   **
92932   **     CREATE VIEW one AS SELECT * FROM two;
92933   **     CREATE VIEW two AS SELECT * FROM one;
92934   **
92935   ** Actually, the error above is now caught prior to reaching this point.
92936   ** But the following test is still important as it does come up
92937   ** in the following:
92938   **
92939   **     CREATE TABLE main.ex1(a);
92940   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
92941   **     SELECT * FROM temp.ex1;
92942   */
92943   if( pTable->nCol<0 ){
92944     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
92945     return 1;
92946   }
92947   assert( pTable->nCol>=0 );
92948 
92949   /* If we get this far, it means we need to compute the table names.
92950   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
92951   ** "*" elements in the results set of the view and will assign cursors
92952   ** to the elements of the FROM clause.  But we do not want these changes
92953   ** to be permanent.  So the computation is done on a copy of the SELECT
92954   ** statement that defines the view.
92955   */
92956   assert( pTable->pSelect );
92957   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
92958   if( pSel ){
92959     u8 enableLookaside = db->lookaside.bEnabled;
92960     n = pParse->nTab;
92961     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
92962     pTable->nCol = -1;
92963     db->lookaside.bEnabled = 0;
92964 #ifndef SQLITE_OMIT_AUTHORIZATION
92965     xAuth = db->xAuth;
92966     db->xAuth = 0;
92967     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
92968     db->xAuth = xAuth;
92969 #else
92970     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
92971 #endif
92972     db->lookaside.bEnabled = enableLookaside;
92973     pParse->nTab = n;
92974     if( pSelTab ){
92975       assert( pTable->aCol==0 );
92976       pTable->nCol = pSelTab->nCol;
92977       pTable->aCol = pSelTab->aCol;
92978       pSelTab->nCol = 0;
92979       pSelTab->aCol = 0;
92980       sqlite3DeleteTable(db, pSelTab);
92981       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
92982       pTable->pSchema->schemaFlags |= DB_UnresetViews;
92983     }else{
92984       pTable->nCol = 0;
92985       nErr++;
92986     }
92987     sqlite3SelectDelete(db, pSel);
92988   } else {
92989     nErr++;
92990   }
92991 #endif /* SQLITE_OMIT_VIEW */
92992   return nErr;
92993 }
92994 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
92995 
92996 #ifndef SQLITE_OMIT_VIEW
92997 /*
92998 ** Clear the column names from every VIEW in database idx.
92999 */
93000 static void sqliteViewResetAll(sqlite3 *db, int idx){
93001   HashElem *i;
93002   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
93003   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
93004   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
93005     Table *pTab = sqliteHashData(i);
93006     if( pTab->pSelect ){
93007       sqliteDeleteColumnNames(db, pTab);
93008       pTab->aCol = 0;
93009       pTab->nCol = 0;
93010     }
93011   }
93012   DbClearProperty(db, idx, DB_UnresetViews);
93013 }
93014 #else
93015 # define sqliteViewResetAll(A,B)
93016 #endif /* SQLITE_OMIT_VIEW */
93017 
93018 /*
93019 ** This function is called by the VDBE to adjust the internal schema
93020 ** used by SQLite when the btree layer moves a table root page. The
93021 ** root-page of a table or index in database iDb has changed from iFrom
93022 ** to iTo.
93023 **
93024 ** Ticket #1728:  The symbol table might still contain information
93025 ** on tables and/or indices that are the process of being deleted.
93026 ** If you are unlucky, one of those deleted indices or tables might
93027 ** have the same rootpage number as the real table or index that is
93028 ** being moved.  So we cannot stop searching after the first match
93029 ** because the first match might be for one of the deleted indices
93030 ** or tables and not the table/index that is actually being moved.
93031 ** We must continue looping until all tables and indices with
93032 ** rootpage==iFrom have been converted to have a rootpage of iTo
93033 ** in order to be certain that we got the right one.
93034 */
93035 #ifndef SQLITE_OMIT_AUTOVACUUM
93036 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
93037   HashElem *pElem;
93038   Hash *pHash;
93039   Db *pDb;
93040 
93041   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93042   pDb = &db->aDb[iDb];
93043   pHash = &pDb->pSchema->tblHash;
93044   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
93045     Table *pTab = sqliteHashData(pElem);
93046     if( pTab->tnum==iFrom ){
93047       pTab->tnum = iTo;
93048     }
93049   }
93050   pHash = &pDb->pSchema->idxHash;
93051   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
93052     Index *pIdx = sqliteHashData(pElem);
93053     if( pIdx->tnum==iFrom ){
93054       pIdx->tnum = iTo;
93055     }
93056   }
93057 }
93058 #endif
93059 
93060 /*
93061 ** Write code to erase the table with root-page iTable from database iDb.
93062 ** Also write code to modify the sqlite_master table and internal schema
93063 ** if a root-page of another table is moved by the btree-layer whilst
93064 ** erasing iTable (this can happen with an auto-vacuum database).
93065 */
93066 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
93067   Vdbe *v = sqlite3GetVdbe(pParse);
93068   int r1 = sqlite3GetTempReg(pParse);
93069   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
93070   sqlite3MayAbort(pParse);
93071 #ifndef SQLITE_OMIT_AUTOVACUUM
93072   /* OP_Destroy stores an in integer r1. If this integer
93073   ** is non-zero, then it is the root page number of a table moved to
93074   ** location iTable. The following code modifies the sqlite_master table to
93075   ** reflect this.
93076   **
93077   ** The "#NNN" in the SQL is a special constant that means whatever value
93078   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
93079   ** token for additional information.
93080   */
93081   sqlite3NestedParse(pParse,
93082      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
93083      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
93084 #endif
93085   sqlite3ReleaseTempReg(pParse, r1);
93086 }
93087 
93088 /*
93089 ** Write VDBE code to erase table pTab and all associated indices on disk.
93090 ** Code to update the sqlite_master tables and internal schema definitions
93091 ** in case a root-page belonging to another table is moved by the btree layer
93092 ** is also added (this can happen with an auto-vacuum database).
93093 */
93094 static void destroyTable(Parse *pParse, Table *pTab){
93095 #ifdef SQLITE_OMIT_AUTOVACUUM
93096   Index *pIdx;
93097   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
93098   destroyRootPage(pParse, pTab->tnum, iDb);
93099   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
93100     destroyRootPage(pParse, pIdx->tnum, iDb);
93101   }
93102 #else
93103   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
93104   ** is not defined), then it is important to call OP_Destroy on the
93105   ** table and index root-pages in order, starting with the numerically
93106   ** largest root-page number. This guarantees that none of the root-pages
93107   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
93108   ** following were coded:
93109   **
93110   ** OP_Destroy 4 0
93111   ** ...
93112   ** OP_Destroy 5 0
93113   **
93114   ** and root page 5 happened to be the largest root-page number in the
93115   ** database, then root page 5 would be moved to page 4 by the
93116   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
93117   ** a free-list page.
93118   */
93119   int iTab = pTab->tnum;
93120   int iDestroyed = 0;
93121 
93122   while( 1 ){
93123     Index *pIdx;
93124     int iLargest = 0;
93125 
93126     if( iDestroyed==0 || iTab<iDestroyed ){
93127       iLargest = iTab;
93128     }
93129     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
93130       int iIdx = pIdx->tnum;
93131       assert( pIdx->pSchema==pTab->pSchema );
93132       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
93133         iLargest = iIdx;
93134       }
93135     }
93136     if( iLargest==0 ){
93137       return;
93138     }else{
93139       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
93140       assert( iDb>=0 && iDb<pParse->db->nDb );
93141       destroyRootPage(pParse, iLargest, iDb);
93142       iDestroyed = iLargest;
93143     }
93144   }
93145 #endif
93146 }
93147 
93148 /*
93149 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
93150 ** after a DROP INDEX or DROP TABLE command.
93151 */
93152 static void sqlite3ClearStatTables(
93153   Parse *pParse,         /* The parsing context */
93154   int iDb,               /* The database number */
93155   const char *zType,     /* "idx" or "tbl" */
93156   const char *zName      /* Name of index or table */
93157 ){
93158   int i;
93159   const char *zDbName = pParse->db->aDb[iDb].zName;
93160   for(i=1; i<=4; i++){
93161     char zTab[24];
93162     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
93163     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
93164       sqlite3NestedParse(pParse,
93165         "DELETE FROM %Q.%s WHERE %s=%Q",
93166         zDbName, zTab, zType, zName
93167       );
93168     }
93169   }
93170 }
93171 
93172 /*
93173 ** Generate code to drop a table.
93174 */
93175 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
93176   Vdbe *v;
93177   sqlite3 *db = pParse->db;
93178   Trigger *pTrigger;
93179   Db *pDb = &db->aDb[iDb];
93180 
93181   v = sqlite3GetVdbe(pParse);
93182   assert( v!=0 );
93183   sqlite3BeginWriteOperation(pParse, 1, iDb);
93184 
93185 #ifndef SQLITE_OMIT_VIRTUALTABLE
93186   if( IsVirtual(pTab) ){
93187     sqlite3VdbeAddOp0(v, OP_VBegin);
93188   }
93189 #endif
93190 
93191   /* Drop all triggers associated with the table being dropped. Code
93192   ** is generated to remove entries from sqlite_master and/or
93193   ** sqlite_temp_master if required.
93194   */
93195   pTrigger = sqlite3TriggerList(pParse, pTab);
93196   while( pTrigger ){
93197     assert( pTrigger->pSchema==pTab->pSchema ||
93198         pTrigger->pSchema==db->aDb[1].pSchema );
93199     sqlite3DropTriggerPtr(pParse, pTrigger);
93200     pTrigger = pTrigger->pNext;
93201   }
93202 
93203 #ifndef SQLITE_OMIT_AUTOINCREMENT
93204   /* Remove any entries of the sqlite_sequence table associated with
93205   ** the table being dropped. This is done before the table is dropped
93206   ** at the btree level, in case the sqlite_sequence table needs to
93207   ** move as a result of the drop (can happen in auto-vacuum mode).
93208   */
93209   if( pTab->tabFlags & TF_Autoincrement ){
93210     sqlite3NestedParse(pParse,
93211       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
93212       pDb->zName, pTab->zName
93213     );
93214   }
93215 #endif
93216 
93217   /* Drop all SQLITE_MASTER table and index entries that refer to the
93218   ** table. The program name loops through the master table and deletes
93219   ** every row that refers to a table of the same name as the one being
93220   ** dropped. Triggers are handled separately because a trigger can be
93221   ** created in the temp database that refers to a table in another
93222   ** database.
93223   */
93224   sqlite3NestedParse(pParse,
93225       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
93226       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
93227   if( !isView && !IsVirtual(pTab) ){
93228     destroyTable(pParse, pTab);
93229   }
93230 
93231   /* Remove the table entry from SQLite's internal schema and modify
93232   ** the schema cookie.
93233   */
93234   if( IsVirtual(pTab) ){
93235     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
93236   }
93237   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
93238   sqlite3ChangeCookie(pParse, iDb);
93239   sqliteViewResetAll(db, iDb);
93240 }
93241 
93242 /*
93243 ** This routine is called to do the work of a DROP TABLE statement.
93244 ** pName is the name of the table to be dropped.
93245 */
93246 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
93247   Table *pTab;
93248   Vdbe *v;
93249   sqlite3 *db = pParse->db;
93250   int iDb;
93251 
93252   if( db->mallocFailed ){
93253     goto exit_drop_table;
93254   }
93255   assert( pParse->nErr==0 );
93256   assert( pName->nSrc==1 );
93257   if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
93258   if( noErr ) db->suppressErr++;
93259   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
93260   if( noErr ) db->suppressErr--;
93261 
93262   if( pTab==0 ){
93263     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
93264     goto exit_drop_table;
93265   }
93266   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
93267   assert( iDb>=0 && iDb<db->nDb );
93268 
93269   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
93270   ** it is initialized.
93271   */
93272   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
93273     goto exit_drop_table;
93274   }
93275 #ifndef SQLITE_OMIT_AUTHORIZATION
93276   {
93277     int code;
93278     const char *zTab = SCHEMA_TABLE(iDb);
93279     const char *zDb = db->aDb[iDb].zName;
93280     const char *zArg2 = 0;
93281     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
93282       goto exit_drop_table;
93283     }
93284     if( isView ){
93285       if( !OMIT_TEMPDB && iDb==1 ){
93286         code = SQLITE_DROP_TEMP_VIEW;
93287       }else{
93288         code = SQLITE_DROP_VIEW;
93289       }
93290 #ifndef SQLITE_OMIT_VIRTUALTABLE
93291     }else if( IsVirtual(pTab) ){
93292       code = SQLITE_DROP_VTABLE;
93293       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
93294 #endif
93295     }else{
93296       if( !OMIT_TEMPDB && iDb==1 ){
93297         code = SQLITE_DROP_TEMP_TABLE;
93298       }else{
93299         code = SQLITE_DROP_TABLE;
93300       }
93301     }
93302     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
93303       goto exit_drop_table;
93304     }
93305     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
93306       goto exit_drop_table;
93307     }
93308   }
93309 #endif
93310   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
93311     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
93312     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
93313     goto exit_drop_table;
93314   }
93315 
93316 #ifndef SQLITE_OMIT_VIEW
93317   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
93318   ** on a table.
93319   */
93320   if( isView && pTab->pSelect==0 ){
93321     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
93322     goto exit_drop_table;
93323   }
93324   if( !isView && pTab->pSelect ){
93325     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
93326     goto exit_drop_table;
93327   }
93328 #endif
93329 
93330   /* Generate code to remove the table from the master table
93331   ** on disk.
93332   */
93333   v = sqlite3GetVdbe(pParse);
93334   if( v ){
93335     sqlite3BeginWriteOperation(pParse, 1, iDb);
93336     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
93337     sqlite3FkDropTable(pParse, pName, pTab);
93338     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
93339   }
93340 
93341 exit_drop_table:
93342   sqlite3SrcListDelete(db, pName);
93343 }
93344 
93345 /*
93346 ** This routine is called to create a new foreign key on the table
93347 ** currently under construction.  pFromCol determines which columns
93348 ** in the current table point to the foreign key.  If pFromCol==0 then
93349 ** connect the key to the last column inserted.  pTo is the name of
93350 ** the table referred to (a.k.a the "parent" table).  pToCol is a list
93351 ** of tables in the parent pTo table.  flags contains all
93352 ** information about the conflict resolution algorithms specified
93353 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
93354 **
93355 ** An FKey structure is created and added to the table currently
93356 ** under construction in the pParse->pNewTable field.
93357 **
93358 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
93359 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
93360 */
93361 SQLITE_PRIVATE void sqlite3CreateForeignKey(
93362   Parse *pParse,       /* Parsing context */
93363   ExprList *pFromCol,  /* Columns in this table that point to other table */
93364   Token *pTo,          /* Name of the other table */
93365   ExprList *pToCol,    /* Columns in the other table */
93366   int flags            /* Conflict resolution algorithms. */
93367 ){
93368   sqlite3 *db = pParse->db;
93369 #ifndef SQLITE_OMIT_FOREIGN_KEY
93370   FKey *pFKey = 0;
93371   FKey *pNextTo;
93372   Table *p = pParse->pNewTable;
93373   int nByte;
93374   int i;
93375   int nCol;
93376   char *z;
93377 
93378   assert( pTo!=0 );
93379   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
93380   if( pFromCol==0 ){
93381     int iCol = p->nCol-1;
93382     if( NEVER(iCol<0) ) goto fk_end;
93383     if( pToCol && pToCol->nExpr!=1 ){
93384       sqlite3ErrorMsg(pParse, "foreign key on %s"
93385          " should reference only one column of table %T",
93386          p->aCol[iCol].zName, pTo);
93387       goto fk_end;
93388     }
93389     nCol = 1;
93390   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
93391     sqlite3ErrorMsg(pParse,
93392         "number of columns in foreign key does not match the number of "
93393         "columns in the referenced table");
93394     goto fk_end;
93395   }else{
93396     nCol = pFromCol->nExpr;
93397   }
93398   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
93399   if( pToCol ){
93400     for(i=0; i<pToCol->nExpr; i++){
93401       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
93402     }
93403   }
93404   pFKey = sqlite3DbMallocZero(db, nByte );
93405   if( pFKey==0 ){
93406     goto fk_end;
93407   }
93408   pFKey->pFrom = p;
93409   pFKey->pNextFrom = p->pFKey;
93410   z = (char*)&pFKey->aCol[nCol];
93411   pFKey->zTo = z;
93412   memcpy(z, pTo->z, pTo->n);
93413   z[pTo->n] = 0;
93414   sqlite3Dequote(z);
93415   z += pTo->n+1;
93416   pFKey->nCol = nCol;
93417   if( pFromCol==0 ){
93418     pFKey->aCol[0].iFrom = p->nCol-1;
93419   }else{
93420     for(i=0; i<nCol; i++){
93421       int j;
93422       for(j=0; j<p->nCol; j++){
93423         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
93424           pFKey->aCol[i].iFrom = j;
93425           break;
93426         }
93427       }
93428       if( j>=p->nCol ){
93429         sqlite3ErrorMsg(pParse,
93430           "unknown column \"%s\" in foreign key definition",
93431           pFromCol->a[i].zName);
93432         goto fk_end;
93433       }
93434     }
93435   }
93436   if( pToCol ){
93437     for(i=0; i<nCol; i++){
93438       int n = sqlite3Strlen30(pToCol->a[i].zName);
93439       pFKey->aCol[i].zCol = z;
93440       memcpy(z, pToCol->a[i].zName, n);
93441       z[n] = 0;
93442       z += n+1;
93443     }
93444   }
93445   pFKey->isDeferred = 0;
93446   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
93447   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
93448 
93449   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
93450   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
93451       pFKey->zTo, (void *)pFKey
93452   );
93453   if( pNextTo==pFKey ){
93454     db->mallocFailed = 1;
93455     goto fk_end;
93456   }
93457   if( pNextTo ){
93458     assert( pNextTo->pPrevTo==0 );
93459     pFKey->pNextTo = pNextTo;
93460     pNextTo->pPrevTo = pFKey;
93461   }
93462 
93463   /* Link the foreign key to the table as the last step.
93464   */
93465   p->pFKey = pFKey;
93466   pFKey = 0;
93467 
93468 fk_end:
93469   sqlite3DbFree(db, pFKey);
93470 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
93471   sqlite3ExprListDelete(db, pFromCol);
93472   sqlite3ExprListDelete(db, pToCol);
93473 }
93474 
93475 /*
93476 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
93477 ** clause is seen as part of a foreign key definition.  The isDeferred
93478 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
93479 ** The behavior of the most recently created foreign key is adjusted
93480 ** accordingly.
93481 */
93482 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
93483 #ifndef SQLITE_OMIT_FOREIGN_KEY
93484   Table *pTab;
93485   FKey *pFKey;
93486   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
93487   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
93488   pFKey->isDeferred = (u8)isDeferred;
93489 #endif
93490 }
93491 
93492 /*
93493 ** Generate code that will erase and refill index *pIdx.  This is
93494 ** used to initialize a newly created index or to recompute the
93495 ** content of an index in response to a REINDEX command.
93496 **
93497 ** if memRootPage is not negative, it means that the index is newly
93498 ** created.  The register specified by memRootPage contains the
93499 ** root page number of the index.  If memRootPage is negative, then
93500 ** the index already exists and must be cleared before being refilled and
93501 ** the root page number of the index is taken from pIndex->tnum.
93502 */
93503 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
93504   Table *pTab = pIndex->pTable;  /* The table that is indexed */
93505   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
93506   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
93507   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
93508   int addr1;                     /* Address of top of loop */
93509   int addr2;                     /* Address to jump to for next iteration */
93510   int tnum;                      /* Root page of index */
93511   int iPartIdxLabel;             /* Jump to this label to skip a row */
93512   Vdbe *v;                       /* Generate code into this virtual machine */
93513   KeyInfo *pKey;                 /* KeyInfo for index */
93514   int regRecord;                 /* Register holding assembled index record */
93515   sqlite3 *db = pParse->db;      /* The database connection */
93516   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
93517 
93518 #ifndef SQLITE_OMIT_AUTHORIZATION
93519   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
93520       db->aDb[iDb].zName ) ){
93521     return;
93522   }
93523 #endif
93524 
93525   /* Require a write-lock on the table to perform this operation */
93526   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
93527 
93528   v = sqlite3GetVdbe(pParse);
93529   if( v==0 ) return;
93530   if( memRootPage>=0 ){
93531     tnum = memRootPage;
93532   }else{
93533     tnum = pIndex->tnum;
93534   }
93535   pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
93536 
93537   /* Open the sorter cursor if we are to use one. */
93538   iSorter = pParse->nTab++;
93539   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
93540                     sqlite3KeyInfoRef(pKey), P4_KEYINFO);
93541 
93542   /* Open the table. Loop through all rows of the table, inserting index
93543   ** records into the sorter. */
93544   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
93545   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
93546   regRecord = sqlite3GetTempReg(pParse);
93547 
93548   sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
93549   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
93550   sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
93551   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
93552   sqlite3VdbeJumpHere(v, addr1);
93553   if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
93554   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
93555                     (char *)pKey, P4_KEYINFO);
93556   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
93557 
93558   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
93559   assert( pKey!=0 || db->mallocFailed || pParse->nErr );
93560   if( IsUniqueIndex(pIndex) && pKey!=0 ){
93561     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
93562     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
93563     addr2 = sqlite3VdbeCurrentAddr(v);
93564     sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
93565                          pIndex->nKeyCol); VdbeCoverage(v);
93566     sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
93567   }else{
93568     addr2 = sqlite3VdbeCurrentAddr(v);
93569   }
93570   sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
93571   sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
93572   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
93573   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
93574   sqlite3ReleaseTempReg(pParse, regRecord);
93575   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
93576   sqlite3VdbeJumpHere(v, addr1);
93577 
93578   sqlite3VdbeAddOp1(v, OP_Close, iTab);
93579   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
93580   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
93581 }
93582 
93583 /*
93584 ** Allocate heap space to hold an Index object with nCol columns.
93585 **
93586 ** Increase the allocation size to provide an extra nExtra bytes
93587 ** of 8-byte aligned space after the Index object and return a
93588 ** pointer to this extra space in *ppExtra.
93589 */
93590 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
93591   sqlite3 *db,         /* Database connection */
93592   i16 nCol,            /* Total number of columns in the index */
93593   int nExtra,          /* Number of bytes of extra space to alloc */
93594   char **ppExtra       /* Pointer to the "extra" space */
93595 ){
93596   Index *p;            /* Allocated index object */
93597   int nByte;           /* Bytes of space for Index object + arrays */
93598 
93599   nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
93600           ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
93601           ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
93602                  sizeof(i16)*nCol +            /* Index.aiColumn   */
93603                  sizeof(u8)*nCol);             /* Index.aSortOrder */
93604   p = sqlite3DbMallocZero(db, nByte + nExtra);
93605   if( p ){
93606     char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
93607     p->azColl = (char**)pExtra;       pExtra += ROUND8(sizeof(char*)*nCol);
93608     p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
93609     p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
93610     p->aSortOrder = (u8*)pExtra;
93611     p->nColumn = nCol;
93612     p->nKeyCol = nCol - 1;
93613     *ppExtra = ((char*)p) + nByte;
93614   }
93615   return p;
93616 }
93617 
93618 /*
93619 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
93620 ** and pTblList is the name of the table that is to be indexed.  Both will
93621 ** be NULL for a primary key or an index that is created to satisfy a
93622 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
93623 ** as the table to be indexed.  pParse->pNewTable is a table that is
93624 ** currently being constructed by a CREATE TABLE statement.
93625 **
93626 ** pList is a list of columns to be indexed.  pList will be NULL if this
93627 ** is a primary key or unique-constraint on the most recent column added
93628 ** to the table currently under construction.
93629 **
93630 ** If the index is created successfully, return a pointer to the new Index
93631 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
93632 ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
93633 */
93634 SQLITE_PRIVATE Index *sqlite3CreateIndex(
93635   Parse *pParse,     /* All information about this parse */
93636   Token *pName1,     /* First part of index name. May be NULL */
93637   Token *pName2,     /* Second part of index name. May be NULL */
93638   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
93639   ExprList *pList,   /* A list of columns to be indexed */
93640   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
93641   Token *pStart,     /* The CREATE token that begins this statement */
93642   Expr *pPIWhere,    /* WHERE clause for partial indices */
93643   int sortOrder,     /* Sort order of primary key when pList==NULL */
93644   int ifNotExist     /* Omit error if index already exists */
93645 ){
93646   Index *pRet = 0;     /* Pointer to return */
93647   Table *pTab = 0;     /* Table to be indexed */
93648   Index *pIndex = 0;   /* The index to be created */
93649   char *zName = 0;     /* Name of the index */
93650   int nName;           /* Number of characters in zName */
93651   int i, j;
93652   DbFixer sFix;        /* For assigning database names to pTable */
93653   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
93654   sqlite3 *db = pParse->db;
93655   Db *pDb;             /* The specific table containing the indexed database */
93656   int iDb;             /* Index of the database that is being written */
93657   Token *pName = 0;    /* Unqualified name of the index to create */
93658   struct ExprList_item *pListItem; /* For looping over pList */
93659   const Column *pTabCol;           /* A column in the table */
93660   int nExtra = 0;                  /* Space allocated for zExtra[] */
93661   int nExtraCol;                   /* Number of extra columns needed */
93662   char *zExtra = 0;                /* Extra space after the Index object */
93663   Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
93664 
93665   if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){
93666     goto exit_create_index;
93667   }
93668   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
93669     goto exit_create_index;
93670   }
93671 
93672   /*
93673   ** Find the table that is to be indexed.  Return early if not found.
93674   */
93675   if( pTblName!=0 ){
93676 
93677     /* Use the two-part index name to determine the database
93678     ** to search for the table. 'Fix' the table name to this db
93679     ** before looking up the table.
93680     */
93681     assert( pName1 && pName2 );
93682     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
93683     if( iDb<0 ) goto exit_create_index;
93684     assert( pName && pName->z );
93685 
93686 #ifndef SQLITE_OMIT_TEMPDB
93687     /* If the index name was unqualified, check if the table
93688     ** is a temp table. If so, set the database to 1. Do not do this
93689     ** if initialising a database schema.
93690     */
93691     if( !db->init.busy ){
93692       pTab = sqlite3SrcListLookup(pParse, pTblName);
93693       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
93694         iDb = 1;
93695       }
93696     }
93697 #endif
93698 
93699     sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
93700     if( sqlite3FixSrcList(&sFix, pTblName) ){
93701       /* Because the parser constructs pTblName from a single identifier,
93702       ** sqlite3FixSrcList can never fail. */
93703       assert(0);
93704     }
93705     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
93706     assert( db->mallocFailed==0 || pTab==0 );
93707     if( pTab==0 ) goto exit_create_index;
93708     if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
93709       sqlite3ErrorMsg(pParse,
93710            "cannot create a TEMP index on non-TEMP table \"%s\"",
93711            pTab->zName);
93712       goto exit_create_index;
93713     }
93714     if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
93715   }else{
93716     assert( pName==0 );
93717     assert( pStart==0 );
93718     pTab = pParse->pNewTable;
93719     if( !pTab ) goto exit_create_index;
93720     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
93721   }
93722   pDb = &db->aDb[iDb];
93723 
93724   assert( pTab!=0 );
93725   assert( pParse->nErr==0 );
93726   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
93727        && db->init.busy==0
93728 #if SQLITE_USER_AUTHENTICATION
93729        && sqlite3UserAuthTable(pTab->zName)==0
93730 #endif
93731        && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
93732     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
93733     goto exit_create_index;
93734   }
93735 #ifndef SQLITE_OMIT_VIEW
93736   if( pTab->pSelect ){
93737     sqlite3ErrorMsg(pParse, "views may not be indexed");
93738     goto exit_create_index;
93739   }
93740 #endif
93741 #ifndef SQLITE_OMIT_VIRTUALTABLE
93742   if( IsVirtual(pTab) ){
93743     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
93744     goto exit_create_index;
93745   }
93746 #endif
93747 
93748   /*
93749   ** Find the name of the index.  Make sure there is not already another
93750   ** index or table with the same name.
93751   **
93752   ** Exception:  If we are reading the names of permanent indices from the
93753   ** sqlite_master table (because some other process changed the schema) and
93754   ** one of the index names collides with the name of a temporary table or
93755   ** index, then we will continue to process this index.
93756   **
93757   ** If pName==0 it means that we are
93758   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
93759   ** own name.
93760   */
93761   if( pName ){
93762     zName = sqlite3NameFromToken(db, pName);
93763     if( zName==0 ) goto exit_create_index;
93764     assert( pName->z!=0 );
93765     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
93766       goto exit_create_index;
93767     }
93768     if( !db->init.busy ){
93769       if( sqlite3FindTable(db, zName, 0)!=0 ){
93770         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
93771         goto exit_create_index;
93772       }
93773     }
93774     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
93775       if( !ifNotExist ){
93776         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
93777       }else{
93778         assert( !db->init.busy );
93779         sqlite3CodeVerifySchema(pParse, iDb);
93780       }
93781       goto exit_create_index;
93782     }
93783   }else{
93784     int n;
93785     Index *pLoop;
93786     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
93787     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
93788     if( zName==0 ){
93789       goto exit_create_index;
93790     }
93791   }
93792 
93793   /* Check for authorization to create an index.
93794   */
93795 #ifndef SQLITE_OMIT_AUTHORIZATION
93796   {
93797     const char *zDb = pDb->zName;
93798     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
93799       goto exit_create_index;
93800     }
93801     i = SQLITE_CREATE_INDEX;
93802     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
93803     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
93804       goto exit_create_index;
93805     }
93806   }
93807 #endif
93808 
93809   /* If pList==0, it means this routine was called to make a primary
93810   ** key out of the last column added to the table under construction.
93811   ** So create a fake list to simulate this.
93812   */
93813   if( pList==0 ){
93814     pList = sqlite3ExprListAppend(pParse, 0, 0);
93815     if( pList==0 ) goto exit_create_index;
93816     pList->a[0].zName = sqlite3DbStrDup(pParse->db,
93817                                         pTab->aCol[pTab->nCol-1].zName);
93818     pList->a[0].sortOrder = (u8)sortOrder;
93819   }
93820 
93821   /* Figure out how many bytes of space are required to store explicitly
93822   ** specified collation sequence names.
93823   */
93824   for(i=0; i<pList->nExpr; i++){
93825     Expr *pExpr = pList->a[i].pExpr;
93826     if( pExpr ){
93827       assert( pExpr->op==TK_COLLATE );
93828       nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
93829     }
93830   }
93831 
93832   /*
93833   ** Allocate the index structure.
93834   */
93835   nName = sqlite3Strlen30(zName);
93836   nExtraCol = pPk ? pPk->nKeyCol : 1;
93837   pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
93838                                       nName + nExtra + 1, &zExtra);
93839   if( db->mallocFailed ){
93840     goto exit_create_index;
93841   }
93842   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
93843   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
93844   pIndex->zName = zExtra;
93845   zExtra += nName + 1;
93846   memcpy(pIndex->zName, zName, nName+1);
93847   pIndex->pTable = pTab;
93848   pIndex->onError = (u8)onError;
93849   pIndex->uniqNotNull = onError!=OE_None;
93850   pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
93851   pIndex->pSchema = db->aDb[iDb].pSchema;
93852   pIndex->nKeyCol = pList->nExpr;
93853   if( pPIWhere ){
93854     sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
93855     pIndex->pPartIdxWhere = pPIWhere;
93856     pPIWhere = 0;
93857   }
93858   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93859 
93860   /* Check to see if we should honor DESC requests on index columns
93861   */
93862   if( pDb->pSchema->file_format>=4 ){
93863     sortOrderMask = -1;   /* Honor DESC */
93864   }else{
93865     sortOrderMask = 0;    /* Ignore DESC */
93866   }
93867 
93868   /* Scan the names of the columns of the table to be indexed and
93869   ** load the column indices into the Index structure.  Report an error
93870   ** if any column is not found.
93871   **
93872   ** TODO:  Add a test to make sure that the same column is not named
93873   ** more than once within the same index.  Only the first instance of
93874   ** the column will ever be used by the optimizer.  Note that using the
93875   ** same column more than once cannot be an error because that would
93876   ** break backwards compatibility - it needs to be a warning.
93877   */
93878   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
93879     const char *zColName = pListItem->zName;
93880     int requestedSortOrder;
93881     char *zColl;                   /* Collation sequence name */
93882 
93883     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
93884       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
93885     }
93886     if( j>=pTab->nCol ){
93887       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
93888         pTab->zName, zColName);
93889       pParse->checkSchema = 1;
93890       goto exit_create_index;
93891     }
93892     assert( j<=0x7fff );
93893     pIndex->aiColumn[i] = (i16)j;
93894     if( pListItem->pExpr ){
93895       int nColl;
93896       assert( pListItem->pExpr->op==TK_COLLATE );
93897       zColl = pListItem->pExpr->u.zToken;
93898       nColl = sqlite3Strlen30(zColl) + 1;
93899       assert( nExtra>=nColl );
93900       memcpy(zExtra, zColl, nColl);
93901       zColl = zExtra;
93902       zExtra += nColl;
93903       nExtra -= nColl;
93904     }else{
93905       zColl = pTab->aCol[j].zColl;
93906       if( !zColl ) zColl = "BINARY";
93907     }
93908     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
93909       goto exit_create_index;
93910     }
93911     pIndex->azColl[i] = zColl;
93912     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
93913     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
93914     if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
93915   }
93916   if( pPk ){
93917     for(j=0; j<pPk->nKeyCol; j++){
93918       int x = pPk->aiColumn[j];
93919       if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
93920         pIndex->nColumn--;
93921       }else{
93922         pIndex->aiColumn[i] = x;
93923         pIndex->azColl[i] = pPk->azColl[j];
93924         pIndex->aSortOrder[i] = pPk->aSortOrder[j];
93925         i++;
93926       }
93927     }
93928     assert( i==pIndex->nColumn );
93929   }else{
93930     pIndex->aiColumn[i] = -1;
93931     pIndex->azColl[i] = "BINARY";
93932   }
93933   sqlite3DefaultRowEst(pIndex);
93934   if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
93935 
93936   if( pTab==pParse->pNewTable ){
93937     /* This routine has been called to create an automatic index as a
93938     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
93939     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
93940     ** i.e. one of:
93941     **
93942     ** CREATE TABLE t(x PRIMARY KEY, y);
93943     ** CREATE TABLE t(x, y, UNIQUE(x, y));
93944     **
93945     ** Either way, check to see if the table already has such an index. If
93946     ** so, don't bother creating this one. This only applies to
93947     ** automatically created indices. Users can do as they wish with
93948     ** explicit indices.
93949     **
93950     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
93951     ** (and thus suppressing the second one) even if they have different
93952     ** sort orders.
93953     **
93954     ** If there are different collating sequences or if the columns of
93955     ** the constraint occur in different orders, then the constraints are
93956     ** considered distinct and both result in separate indices.
93957     */
93958     Index *pIdx;
93959     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
93960       int k;
93961       assert( IsUniqueIndex(pIdx) );
93962       assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
93963       assert( IsUniqueIndex(pIndex) );
93964 
93965       if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
93966       for(k=0; k<pIdx->nKeyCol; k++){
93967         const char *z1;
93968         const char *z2;
93969         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
93970         z1 = pIdx->azColl[k];
93971         z2 = pIndex->azColl[k];
93972         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
93973       }
93974       if( k==pIdx->nKeyCol ){
93975         if( pIdx->onError!=pIndex->onError ){
93976           /* This constraint creates the same index as a previous
93977           ** constraint specified somewhere in the CREATE TABLE statement.
93978           ** However the ON CONFLICT clauses are different. If both this
93979           ** constraint and the previous equivalent constraint have explicit
93980           ** ON CONFLICT clauses this is an error. Otherwise, use the
93981           ** explicitly specified behavior for the index.
93982           */
93983           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
93984             sqlite3ErrorMsg(pParse,
93985                 "conflicting ON CONFLICT clauses specified", 0);
93986           }
93987           if( pIdx->onError==OE_Default ){
93988             pIdx->onError = pIndex->onError;
93989           }
93990         }
93991         pRet = pIdx;
93992         goto exit_create_index;
93993       }
93994     }
93995   }
93996 
93997   /* Link the new Index structure to its table and to the other
93998   ** in-memory database structures.
93999   */
94000   if( db->init.busy ){
94001     Index *p;
94002     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
94003     p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
94004                           pIndex->zName, pIndex);
94005     if( p ){
94006       assert( p==pIndex );  /* Malloc must have failed */
94007       db->mallocFailed = 1;
94008       goto exit_create_index;
94009     }
94010     db->flags |= SQLITE_InternChanges;
94011     if( pTblName!=0 ){
94012       pIndex->tnum = db->init.newTnum;
94013     }
94014   }
94015 
94016   /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
94017   ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
94018   ** emit code to allocate the index rootpage on disk and make an entry for
94019   ** the index in the sqlite_master table and populate the index with
94020   ** content.  But, do not do this if we are simply reading the sqlite_master
94021   ** table to parse the schema, or if this index is the PRIMARY KEY index
94022   ** of a WITHOUT ROWID table.
94023   **
94024   ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
94025   ** or UNIQUE index in a CREATE TABLE statement.  Since the table
94026   ** has just been created, it contains no data and the index initialization
94027   ** step can be skipped.
94028   */
94029   else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
94030     Vdbe *v;
94031     char *zStmt;
94032     int iMem = ++pParse->nMem;
94033 
94034     v = sqlite3GetVdbe(pParse);
94035     if( v==0 ) goto exit_create_index;
94036 
94037 
94038     /* Create the rootpage for the index
94039     */
94040     sqlite3BeginWriteOperation(pParse, 1, iDb);
94041     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
94042 
94043     /* Gather the complete text of the CREATE INDEX statement into
94044     ** the zStmt variable
94045     */
94046     if( pStart ){
94047       int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
94048       if( pName->z[n-1]==';' ) n--;
94049       /* A named index with an explicit CREATE INDEX statement */
94050       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
94051         onError==OE_None ? "" : " UNIQUE", n, pName->z);
94052     }else{
94053       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
94054       /* zStmt = sqlite3MPrintf(""); */
94055       zStmt = 0;
94056     }
94057 
94058     /* Add an entry in sqlite_master for this index
94059     */
94060     sqlite3NestedParse(pParse,
94061         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
94062         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
94063         pIndex->zName,
94064         pTab->zName,
94065         iMem,
94066         zStmt
94067     );
94068     sqlite3DbFree(db, zStmt);
94069 
94070     /* Fill the index with data and reparse the schema. Code an OP_Expire
94071     ** to invalidate all pre-compiled statements.
94072     */
94073     if( pTblName ){
94074       sqlite3RefillIndex(pParse, pIndex, iMem);
94075       sqlite3ChangeCookie(pParse, iDb);
94076       sqlite3VdbeAddParseSchemaOp(v, iDb,
94077          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
94078       sqlite3VdbeAddOp1(v, OP_Expire, 0);
94079     }
94080   }
94081 
94082   /* When adding an index to the list of indices for a table, make
94083   ** sure all indices labeled OE_Replace come after all those labeled
94084   ** OE_Ignore.  This is necessary for the correct constraint check
94085   ** processing (in sqlite3GenerateConstraintChecks()) as part of
94086   ** UPDATE and INSERT statements.
94087   */
94088   if( db->init.busy || pTblName==0 ){
94089     if( onError!=OE_Replace || pTab->pIndex==0
94090          || pTab->pIndex->onError==OE_Replace){
94091       pIndex->pNext = pTab->pIndex;
94092       pTab->pIndex = pIndex;
94093     }else{
94094       Index *pOther = pTab->pIndex;
94095       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
94096         pOther = pOther->pNext;
94097       }
94098       pIndex->pNext = pOther->pNext;
94099       pOther->pNext = pIndex;
94100     }
94101     pRet = pIndex;
94102     pIndex = 0;
94103   }
94104 
94105   /* Clean up before exiting */
94106 exit_create_index:
94107   if( pIndex ) freeIndex(db, pIndex);
94108   sqlite3ExprDelete(db, pPIWhere);
94109   sqlite3ExprListDelete(db, pList);
94110   sqlite3SrcListDelete(db, pTblName);
94111   sqlite3DbFree(db, zName);
94112   return pRet;
94113 }
94114 
94115 /*
94116 ** Fill the Index.aiRowEst[] array with default information - information
94117 ** to be used when we have not run the ANALYZE command.
94118 **
94119 ** aiRowEst[0] is supposed to contain the number of elements in the index.
94120 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
94121 ** number of rows in the table that match any particular value of the
94122 ** first column of the index.  aiRowEst[2] is an estimate of the number
94123 ** of rows that match any particular combination of the first 2 columns
94124 ** of the index.  And so forth.  It must always be the case that
94125 *
94126 **           aiRowEst[N]<=aiRowEst[N-1]
94127 **           aiRowEst[N]>=1
94128 **
94129 ** Apart from that, we have little to go on besides intuition as to
94130 ** how aiRowEst[] should be initialized.  The numbers generated here
94131 ** are based on typical values found in actual indices.
94132 */
94133 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
94134   /*                10,  9,  8,  7,  6 */
94135   LogEst aVal[] = { 33, 32, 30, 28, 26 };
94136   LogEst *a = pIdx->aiRowLogEst;
94137   int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
94138   int i;
94139 
94140   /* Set the first entry (number of rows in the index) to the estimated
94141   ** number of rows in the table. Or 10, if the estimated number of rows
94142   ** in the table is less than that.  */
94143   a[0] = pIdx->pTable->nRowLogEst;
94144   if( a[0]<33 ) a[0] = 33;        assert( 33==sqlite3LogEst(10) );
94145 
94146   /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
94147   ** 6 and each subsequent value (if any) is 5.  */
94148   memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
94149   for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
94150     a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
94151   }
94152 
94153   assert( 0==sqlite3LogEst(1) );
94154   if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
94155 }
94156 
94157 /*
94158 ** This routine will drop an existing named index.  This routine
94159 ** implements the DROP INDEX statement.
94160 */
94161 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
94162   Index *pIndex;
94163   Vdbe *v;
94164   sqlite3 *db = pParse->db;
94165   int iDb;
94166 
94167   assert( pParse->nErr==0 );   /* Never called with prior errors */
94168   if( db->mallocFailed ){
94169     goto exit_drop_index;
94170   }
94171   assert( pName->nSrc==1 );
94172   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
94173     goto exit_drop_index;
94174   }
94175   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
94176   if( pIndex==0 ){
94177     if( !ifExists ){
94178       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
94179     }else{
94180       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
94181     }
94182     pParse->checkSchema = 1;
94183     goto exit_drop_index;
94184   }
94185   if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
94186     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
94187       "or PRIMARY KEY constraint cannot be dropped", 0);
94188     goto exit_drop_index;
94189   }
94190   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
94191 #ifndef SQLITE_OMIT_AUTHORIZATION
94192   {
94193     int code = SQLITE_DROP_INDEX;
94194     Table *pTab = pIndex->pTable;
94195     const char *zDb = db->aDb[iDb].zName;
94196     const char *zTab = SCHEMA_TABLE(iDb);
94197     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
94198       goto exit_drop_index;
94199     }
94200     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
94201     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
94202       goto exit_drop_index;
94203     }
94204   }
94205 #endif
94206 
94207   /* Generate code to remove the index and from the master table */
94208   v = sqlite3GetVdbe(pParse);
94209   if( v ){
94210     sqlite3BeginWriteOperation(pParse, 1, iDb);
94211     sqlite3NestedParse(pParse,
94212        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
94213        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
94214     );
94215     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
94216     sqlite3ChangeCookie(pParse, iDb);
94217     destroyRootPage(pParse, pIndex->tnum, iDb);
94218     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
94219   }
94220 
94221 exit_drop_index:
94222   sqlite3SrcListDelete(db, pName);
94223 }
94224 
94225 /*
94226 ** pArray is a pointer to an array of objects. Each object in the
94227 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
94228 ** to extend the array so that there is space for a new object at the end.
94229 **
94230 ** When this function is called, *pnEntry contains the current size of
94231 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
94232 ** in total).
94233 **
94234 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
94235 ** space allocated for the new object is zeroed, *pnEntry updated to
94236 ** reflect the new size of the array and a pointer to the new allocation
94237 ** returned. *pIdx is set to the index of the new array entry in this case.
94238 **
94239 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
94240 ** unchanged and a copy of pArray returned.
94241 */
94242 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
94243   sqlite3 *db,      /* Connection to notify of malloc failures */
94244   void *pArray,     /* Array of objects.  Might be reallocated */
94245   int szEntry,      /* Size of each object in the array */
94246   int *pnEntry,     /* Number of objects currently in use */
94247   int *pIdx         /* Write the index of a new slot here */
94248 ){
94249   char *z;
94250   int n = *pnEntry;
94251   if( (n & (n-1))==0 ){
94252     int sz = (n==0) ? 1 : 2*n;
94253     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
94254     if( pNew==0 ){
94255       *pIdx = -1;
94256       return pArray;
94257     }
94258     pArray = pNew;
94259   }
94260   z = (char*)pArray;
94261   memset(&z[n * szEntry], 0, szEntry);
94262   *pIdx = n;
94263   ++*pnEntry;
94264   return pArray;
94265 }
94266 
94267 /*
94268 ** Append a new element to the given IdList.  Create a new IdList if
94269 ** need be.
94270 **
94271 ** A new IdList is returned, or NULL if malloc() fails.
94272 */
94273 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
94274   int i;
94275   if( pList==0 ){
94276     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
94277     if( pList==0 ) return 0;
94278   }
94279   pList->a = sqlite3ArrayAllocate(
94280       db,
94281       pList->a,
94282       sizeof(pList->a[0]),
94283       &pList->nId,
94284       &i
94285   );
94286   if( i<0 ){
94287     sqlite3IdListDelete(db, pList);
94288     return 0;
94289   }
94290   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
94291   return pList;
94292 }
94293 
94294 /*
94295 ** Delete an IdList.
94296 */
94297 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
94298   int i;
94299   if( pList==0 ) return;
94300   for(i=0; i<pList->nId; i++){
94301     sqlite3DbFree(db, pList->a[i].zName);
94302   }
94303   sqlite3DbFree(db, pList->a);
94304   sqlite3DbFree(db, pList);
94305 }
94306 
94307 /*
94308 ** Return the index in pList of the identifier named zId.  Return -1
94309 ** if not found.
94310 */
94311 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
94312   int i;
94313   if( pList==0 ) return -1;
94314   for(i=0; i<pList->nId; i++){
94315     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
94316   }
94317   return -1;
94318 }
94319 
94320 /*
94321 ** Expand the space allocated for the given SrcList object by
94322 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
94323 ** New slots are zeroed.
94324 **
94325 ** For example, suppose a SrcList initially contains two entries: A,B.
94326 ** To append 3 new entries onto the end, do this:
94327 **
94328 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
94329 **
94330 ** After the call above it would contain:  A, B, nil, nil, nil.
94331 ** If the iStart argument had been 1 instead of 2, then the result
94332 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
94333 ** the iStart value would be 0.  The result then would
94334 ** be: nil, nil, nil, A, B.
94335 **
94336 ** If a memory allocation fails the SrcList is unchanged.  The
94337 ** db->mallocFailed flag will be set to true.
94338 */
94339 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
94340   sqlite3 *db,       /* Database connection to notify of OOM errors */
94341   SrcList *pSrc,     /* The SrcList to be enlarged */
94342   int nExtra,        /* Number of new slots to add to pSrc->a[] */
94343   int iStart         /* Index in pSrc->a[] of first new slot */
94344 ){
94345   int i;
94346 
94347   /* Sanity checking on calling parameters */
94348   assert( iStart>=0 );
94349   assert( nExtra>=1 );
94350   assert( pSrc!=0 );
94351   assert( iStart<=pSrc->nSrc );
94352 
94353   /* Allocate additional space if needed */
94354   if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
94355     SrcList *pNew;
94356     int nAlloc = pSrc->nSrc+nExtra;
94357     int nGot;
94358     pNew = sqlite3DbRealloc(db, pSrc,
94359                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
94360     if( pNew==0 ){
94361       assert( db->mallocFailed );
94362       return pSrc;
94363     }
94364     pSrc = pNew;
94365     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
94366     pSrc->nAlloc = nGot;
94367   }
94368 
94369   /* Move existing slots that come after the newly inserted slots
94370   ** out of the way */
94371   for(i=pSrc->nSrc-1; i>=iStart; i--){
94372     pSrc->a[i+nExtra] = pSrc->a[i];
94373   }
94374   pSrc->nSrc += nExtra;
94375 
94376   /* Zero the newly allocated slots */
94377   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
94378   for(i=iStart; i<iStart+nExtra; i++){
94379     pSrc->a[i].iCursor = -1;
94380   }
94381 
94382   /* Return a pointer to the enlarged SrcList */
94383   return pSrc;
94384 }
94385 
94386 
94387 /*
94388 ** Append a new table name to the given SrcList.  Create a new SrcList if
94389 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
94390 **
94391 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
94392 ** SrcList might be the same as the SrcList that was input or it might be
94393 ** a new one.  If an OOM error does occurs, then the prior value of pList
94394 ** that is input to this routine is automatically freed.
94395 **
94396 ** If pDatabase is not null, it means that the table has an optional
94397 ** database name prefix.  Like this:  "database.table".  The pDatabase
94398 ** points to the table name and the pTable points to the database name.
94399 ** The SrcList.a[].zName field is filled with the table name which might
94400 ** come from pTable (if pDatabase is NULL) or from pDatabase.
94401 ** SrcList.a[].zDatabase is filled with the database name from pTable,
94402 ** or with NULL if no database is specified.
94403 **
94404 ** In other words, if call like this:
94405 **
94406 **         sqlite3SrcListAppend(D,A,B,0);
94407 **
94408 ** Then B is a table name and the database name is unspecified.  If called
94409 ** like this:
94410 **
94411 **         sqlite3SrcListAppend(D,A,B,C);
94412 **
94413 ** Then C is the table name and B is the database name.  If C is defined
94414 ** then so is B.  In other words, we never have a case where:
94415 **
94416 **         sqlite3SrcListAppend(D,A,0,C);
94417 **
94418 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
94419 ** before being added to the SrcList.
94420 */
94421 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
94422   sqlite3 *db,        /* Connection to notify of malloc failures */
94423   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
94424   Token *pTable,      /* Table to append */
94425   Token *pDatabase    /* Database of the table */
94426 ){
94427   struct SrcList_item *pItem;
94428   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
94429   if( pList==0 ){
94430     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
94431     if( pList==0 ) return 0;
94432     pList->nAlloc = 1;
94433   }
94434   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
94435   if( db->mallocFailed ){
94436     sqlite3SrcListDelete(db, pList);
94437     return 0;
94438   }
94439   pItem = &pList->a[pList->nSrc-1];
94440   if( pDatabase && pDatabase->z==0 ){
94441     pDatabase = 0;
94442   }
94443   if( pDatabase ){
94444     Token *pTemp = pDatabase;
94445     pDatabase = pTable;
94446     pTable = pTemp;
94447   }
94448   pItem->zName = sqlite3NameFromToken(db, pTable);
94449   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
94450   return pList;
94451 }
94452 
94453 /*
94454 ** Assign VdbeCursor index numbers to all tables in a SrcList
94455 */
94456 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
94457   int i;
94458   struct SrcList_item *pItem;
94459   assert(pList || pParse->db->mallocFailed );
94460   if( pList ){
94461     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
94462       if( pItem->iCursor>=0 ) break;
94463       pItem->iCursor = pParse->nTab++;
94464       if( pItem->pSelect ){
94465         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
94466       }
94467     }
94468   }
94469 }
94470 
94471 /*
94472 ** Delete an entire SrcList including all its substructure.
94473 */
94474 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
94475   int i;
94476   struct SrcList_item *pItem;
94477   if( pList==0 ) return;
94478   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
94479     sqlite3DbFree(db, pItem->zDatabase);
94480     sqlite3DbFree(db, pItem->zName);
94481     sqlite3DbFree(db, pItem->zAlias);
94482     sqlite3DbFree(db, pItem->zIndex);
94483     sqlite3DeleteTable(db, pItem->pTab);
94484     sqlite3SelectDelete(db, pItem->pSelect);
94485     sqlite3ExprDelete(db, pItem->pOn);
94486     sqlite3IdListDelete(db, pItem->pUsing);
94487   }
94488   sqlite3DbFree(db, pList);
94489 }
94490 
94491 /*
94492 ** This routine is called by the parser to add a new term to the
94493 ** end of a growing FROM clause.  The "p" parameter is the part of
94494 ** the FROM clause that has already been constructed.  "p" is NULL
94495 ** if this is the first term of the FROM clause.  pTable and pDatabase
94496 ** are the name of the table and database named in the FROM clause term.
94497 ** pDatabase is NULL if the database name qualifier is missing - the
94498 ** usual case.  If the term has an alias, then pAlias points to the
94499 ** alias token.  If the term is a subquery, then pSubquery is the
94500 ** SELECT statement that the subquery encodes.  The pTable and
94501 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
94502 ** parameters are the content of the ON and USING clauses.
94503 **
94504 ** Return a new SrcList which encodes is the FROM with the new
94505 ** term added.
94506 */
94507 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
94508   Parse *pParse,          /* Parsing context */
94509   SrcList *p,             /* The left part of the FROM clause already seen */
94510   Token *pTable,          /* Name of the table to add to the FROM clause */
94511   Token *pDatabase,       /* Name of the database containing pTable */
94512   Token *pAlias,          /* The right-hand side of the AS subexpression */
94513   Select *pSubquery,      /* A subquery used in place of a table name */
94514   Expr *pOn,              /* The ON clause of a join */
94515   IdList *pUsing          /* The USING clause of a join */
94516 ){
94517   struct SrcList_item *pItem;
94518   sqlite3 *db = pParse->db;
94519   if( !p && (pOn || pUsing) ){
94520     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
94521       (pOn ? "ON" : "USING")
94522     );
94523     goto append_from_error;
94524   }
94525   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
94526   if( p==0 || NEVER(p->nSrc==0) ){
94527     goto append_from_error;
94528   }
94529   pItem = &p->a[p->nSrc-1];
94530   assert( pAlias!=0 );
94531   if( pAlias->n ){
94532     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
94533   }
94534   pItem->pSelect = pSubquery;
94535   pItem->pOn = pOn;
94536   pItem->pUsing = pUsing;
94537   return p;
94538 
94539  append_from_error:
94540   assert( p==0 );
94541   sqlite3ExprDelete(db, pOn);
94542   sqlite3IdListDelete(db, pUsing);
94543   sqlite3SelectDelete(db, pSubquery);
94544   return 0;
94545 }
94546 
94547 /*
94548 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
94549 ** element of the source-list passed as the second argument.
94550 */
94551 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
94552   assert( pIndexedBy!=0 );
94553   if( p && ALWAYS(p->nSrc>0) ){
94554     struct SrcList_item *pItem = &p->a[p->nSrc-1];
94555     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
94556     if( pIndexedBy->n==1 && !pIndexedBy->z ){
94557       /* A "NOT INDEXED" clause was supplied. See parse.y
94558       ** construct "indexed_opt" for details. */
94559       pItem->notIndexed = 1;
94560     }else{
94561       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
94562     }
94563   }
94564 }
94565 
94566 /*
94567 ** When building up a FROM clause in the parser, the join operator
94568 ** is initially attached to the left operand.  But the code generator
94569 ** expects the join operator to be on the right operand.  This routine
94570 ** Shifts all join operators from left to right for an entire FROM
94571 ** clause.
94572 **
94573 ** Example: Suppose the join is like this:
94574 **
94575 **           A natural cross join B
94576 **
94577 ** The operator is "natural cross join".  The A and B operands are stored
94578 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
94579 ** operator with A.  This routine shifts that operator over to B.
94580 */
94581 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
94582   if( p ){
94583     int i;
94584     for(i=p->nSrc-1; i>0; i--){
94585       p->a[i].jointype = p->a[i-1].jointype;
94586     }
94587     p->a[0].jointype = 0;
94588   }
94589 }
94590 
94591 /*
94592 ** Begin a transaction
94593 */
94594 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
94595   sqlite3 *db;
94596   Vdbe *v;
94597   int i;
94598 
94599   assert( pParse!=0 );
94600   db = pParse->db;
94601   assert( db!=0 );
94602 /*  if( db->aDb[0].pBt==0 ) return; */
94603   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
94604     return;
94605   }
94606   v = sqlite3GetVdbe(pParse);
94607   if( !v ) return;
94608   if( type!=TK_DEFERRED ){
94609     for(i=0; i<db->nDb; i++){
94610       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
94611       sqlite3VdbeUsesBtree(v, i);
94612     }
94613   }
94614   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
94615 }
94616 
94617 /*
94618 ** Commit a transaction
94619 */
94620 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
94621   Vdbe *v;
94622 
94623   assert( pParse!=0 );
94624   assert( pParse->db!=0 );
94625   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
94626     return;
94627   }
94628   v = sqlite3GetVdbe(pParse);
94629   if( v ){
94630     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
94631   }
94632 }
94633 
94634 /*
94635 ** Rollback a transaction
94636 */
94637 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
94638   Vdbe *v;
94639 
94640   assert( pParse!=0 );
94641   assert( pParse->db!=0 );
94642   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
94643     return;
94644   }
94645   v = sqlite3GetVdbe(pParse);
94646   if( v ){
94647     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
94648   }
94649 }
94650 
94651 /*
94652 ** This function is called by the parser when it parses a command to create,
94653 ** release or rollback an SQL savepoint.
94654 */
94655 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
94656   char *zName = sqlite3NameFromToken(pParse->db, pName);
94657   if( zName ){
94658     Vdbe *v = sqlite3GetVdbe(pParse);
94659 #ifndef SQLITE_OMIT_AUTHORIZATION
94660     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
94661     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
94662 #endif
94663     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
94664       sqlite3DbFree(pParse->db, zName);
94665       return;
94666     }
94667     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
94668   }
94669 }
94670 
94671 /*
94672 ** Make sure the TEMP database is open and available for use.  Return
94673 ** the number of errors.  Leave any error messages in the pParse structure.
94674 */
94675 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
94676   sqlite3 *db = pParse->db;
94677   if( db->aDb[1].pBt==0 && !pParse->explain ){
94678     int rc;
94679     Btree *pBt;
94680     static const int flags =
94681           SQLITE_OPEN_READWRITE |
94682           SQLITE_OPEN_CREATE |
94683           SQLITE_OPEN_EXCLUSIVE |
94684           SQLITE_OPEN_DELETEONCLOSE |
94685           SQLITE_OPEN_TEMP_DB;
94686 
94687     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
94688     if( rc!=SQLITE_OK ){
94689       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
94690         "file for storing temporary tables");
94691       pParse->rc = rc;
94692       return 1;
94693     }
94694     db->aDb[1].pBt = pBt;
94695     assert( db->aDb[1].pSchema );
94696     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
94697       db->mallocFailed = 1;
94698       return 1;
94699     }
94700   }
94701   return 0;
94702 }
94703 
94704 /*
94705 ** Record the fact that the schema cookie will need to be verified
94706 ** for database iDb.  The code to actually verify the schema cookie
94707 ** will occur at the end of the top-level VDBE and will be generated
94708 ** later, by sqlite3FinishCoding().
94709 */
94710 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
94711   Parse *pToplevel = sqlite3ParseToplevel(pParse);
94712   sqlite3 *db = pToplevel->db;
94713 
94714   assert( iDb>=0 && iDb<db->nDb );
94715   assert( db->aDb[iDb].pBt!=0 || iDb==1 );
94716   assert( iDb<SQLITE_MAX_ATTACHED+2 );
94717   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94718   if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
94719     DbMaskSet(pToplevel->cookieMask, iDb);
94720     pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
94721     if( !OMIT_TEMPDB && iDb==1 ){
94722       sqlite3OpenTempDatabase(pToplevel);
94723     }
94724   }
94725 }
94726 
94727 /*
94728 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
94729 ** attached database. Otherwise, invoke it for the database named zDb only.
94730 */
94731 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
94732   sqlite3 *db = pParse->db;
94733   int i;
94734   for(i=0; i<db->nDb; i++){
94735     Db *pDb = &db->aDb[i];
94736     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
94737       sqlite3CodeVerifySchema(pParse, i);
94738     }
94739   }
94740 }
94741 
94742 /*
94743 ** Generate VDBE code that prepares for doing an operation that
94744 ** might change the database.
94745 **
94746 ** This routine starts a new transaction if we are not already within
94747 ** a transaction.  If we are already within a transaction, then a checkpoint
94748 ** is set if the setStatement parameter is true.  A checkpoint should
94749 ** be set for operations that might fail (due to a constraint) part of
94750 ** the way through and which will need to undo some writes without having to
94751 ** rollback the whole transaction.  For operations where all constraints
94752 ** can be checked before any changes are made to the database, it is never
94753 ** necessary to undo a write and the checkpoint should not be set.
94754 */
94755 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
94756   Parse *pToplevel = sqlite3ParseToplevel(pParse);
94757   sqlite3CodeVerifySchema(pParse, iDb);
94758   DbMaskSet(pToplevel->writeMask, iDb);
94759   pToplevel->isMultiWrite |= setStatement;
94760 }
94761 
94762 /*
94763 ** Indicate that the statement currently under construction might write
94764 ** more than one entry (example: deleting one row then inserting another,
94765 ** inserting multiple rows in a table, or inserting a row and index entries.)
94766 ** If an abort occurs after some of these writes have completed, then it will
94767 ** be necessary to undo the completed writes.
94768 */
94769 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
94770   Parse *pToplevel = sqlite3ParseToplevel(pParse);
94771   pToplevel->isMultiWrite = 1;
94772 }
94773 
94774 /*
94775 ** The code generator calls this routine if is discovers that it is
94776 ** possible to abort a statement prior to completion.  In order to
94777 ** perform this abort without corrupting the database, we need to make
94778 ** sure that the statement is protected by a statement transaction.
94779 **
94780 ** Technically, we only need to set the mayAbort flag if the
94781 ** isMultiWrite flag was previously set.  There is a time dependency
94782 ** such that the abort must occur after the multiwrite.  This makes
94783 ** some statements involving the REPLACE conflict resolution algorithm
94784 ** go a little faster.  But taking advantage of this time dependency
94785 ** makes it more difficult to prove that the code is correct (in
94786 ** particular, it prevents us from writing an effective
94787 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
94788 ** to take the safe route and skip the optimization.
94789 */
94790 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
94791   Parse *pToplevel = sqlite3ParseToplevel(pParse);
94792   pToplevel->mayAbort = 1;
94793 }
94794 
94795 /*
94796 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
94797 ** error. The onError parameter determines which (if any) of the statement
94798 ** and/or current transaction is rolled back.
94799 */
94800 SQLITE_PRIVATE void sqlite3HaltConstraint(
94801   Parse *pParse,    /* Parsing context */
94802   int errCode,      /* extended error code */
94803   int onError,      /* Constraint type */
94804   char *p4,         /* Error message */
94805   i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
94806   u8 p5Errmsg       /* P5_ErrMsg type */
94807 ){
94808   Vdbe *v = sqlite3GetVdbe(pParse);
94809   assert( (errCode&0xff)==SQLITE_CONSTRAINT );
94810   if( onError==OE_Abort ){
94811     sqlite3MayAbort(pParse);
94812   }
94813   sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
94814   if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
94815 }
94816 
94817 /*
94818 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
94819 */
94820 SQLITE_PRIVATE void sqlite3UniqueConstraint(
94821   Parse *pParse,    /* Parsing context */
94822   int onError,      /* Constraint type */
94823   Index *pIdx       /* The index that triggers the constraint */
94824 ){
94825   char *zErr;
94826   int j;
94827   StrAccum errMsg;
94828   Table *pTab = pIdx->pTable;
94829 
94830   sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
94831   for(j=0; j<pIdx->nKeyCol; j++){
94832     char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
94833     if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
94834     sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
94835     sqlite3StrAccumAppend(&errMsg, ".", 1);
94836     sqlite3StrAccumAppendAll(&errMsg, zCol);
94837   }
94838   zErr = sqlite3StrAccumFinish(&errMsg);
94839   sqlite3HaltConstraint(pParse,
94840     IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
94841                             : SQLITE_CONSTRAINT_UNIQUE,
94842     onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
94843 }
94844 
94845 
94846 /*
94847 ** Code an OP_Halt due to non-unique rowid.
94848 */
94849 SQLITE_PRIVATE void sqlite3RowidConstraint(
94850   Parse *pParse,    /* Parsing context */
94851   int onError,      /* Conflict resolution algorithm */
94852   Table *pTab       /* The table with the non-unique rowid */
94853 ){
94854   char *zMsg;
94855   int rc;
94856   if( pTab->iPKey>=0 ){
94857     zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
94858                           pTab->aCol[pTab->iPKey].zName);
94859     rc = SQLITE_CONSTRAINT_PRIMARYKEY;
94860   }else{
94861     zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
94862     rc = SQLITE_CONSTRAINT_ROWID;
94863   }
94864   sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
94865                         P5_ConstraintUnique);
94866 }
94867 
94868 /*
94869 ** Check to see if pIndex uses the collating sequence pColl.  Return
94870 ** true if it does and false if it does not.
94871 */
94872 #ifndef SQLITE_OMIT_REINDEX
94873 static int collationMatch(const char *zColl, Index *pIndex){
94874   int i;
94875   assert( zColl!=0 );
94876   for(i=0; i<pIndex->nColumn; i++){
94877     const char *z = pIndex->azColl[i];
94878     assert( z!=0 || pIndex->aiColumn[i]<0 );
94879     if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
94880       return 1;
94881     }
94882   }
94883   return 0;
94884 }
94885 #endif
94886 
94887 /*
94888 ** Recompute all indices of pTab that use the collating sequence pColl.
94889 ** If pColl==0 then recompute all indices of pTab.
94890 */
94891 #ifndef SQLITE_OMIT_REINDEX
94892 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
94893   Index *pIndex;              /* An index associated with pTab */
94894 
94895   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
94896     if( zColl==0 || collationMatch(zColl, pIndex) ){
94897       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
94898       sqlite3BeginWriteOperation(pParse, 0, iDb);
94899       sqlite3RefillIndex(pParse, pIndex, -1);
94900     }
94901   }
94902 }
94903 #endif
94904 
94905 /*
94906 ** Recompute all indices of all tables in all databases where the
94907 ** indices use the collating sequence pColl.  If pColl==0 then recompute
94908 ** all indices everywhere.
94909 */
94910 #ifndef SQLITE_OMIT_REINDEX
94911 static void reindexDatabases(Parse *pParse, char const *zColl){
94912   Db *pDb;                    /* A single database */
94913   int iDb;                    /* The database index number */
94914   sqlite3 *db = pParse->db;   /* The database connection */
94915   HashElem *k;                /* For looping over tables in pDb */
94916   Table *pTab;                /* A table in the database */
94917 
94918   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
94919   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
94920     assert( pDb!=0 );
94921     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
94922       pTab = (Table*)sqliteHashData(k);
94923       reindexTable(pParse, pTab, zColl);
94924     }
94925   }
94926 }
94927 #endif
94928 
94929 /*
94930 ** Generate code for the REINDEX command.
94931 **
94932 **        REINDEX                            -- 1
94933 **        REINDEX  <collation>               -- 2
94934 **        REINDEX  ?<database>.?<tablename>  -- 3
94935 **        REINDEX  ?<database>.?<indexname>  -- 4
94936 **
94937 ** Form 1 causes all indices in all attached databases to be rebuilt.
94938 ** Form 2 rebuilds all indices in all databases that use the named
94939 ** collating function.  Forms 3 and 4 rebuild the named index or all
94940 ** indices associated with the named table.
94941 */
94942 #ifndef SQLITE_OMIT_REINDEX
94943 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
94944   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
94945   char *z;                    /* Name of a table or index */
94946   const char *zDb;            /* Name of the database */
94947   Table *pTab;                /* A table in the database */
94948   Index *pIndex;              /* An index associated with pTab */
94949   int iDb;                    /* The database index number */
94950   sqlite3 *db = pParse->db;   /* The database connection */
94951   Token *pObjName;            /* Name of the table or index to be reindexed */
94952 
94953   /* Read the database schema. If an error occurs, leave an error message
94954   ** and code in pParse and return NULL. */
94955   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
94956     return;
94957   }
94958 
94959   if( pName1==0 ){
94960     reindexDatabases(pParse, 0);
94961     return;
94962   }else if( NEVER(pName2==0) || pName2->z==0 ){
94963     char *zColl;
94964     assert( pName1->z );
94965     zColl = sqlite3NameFromToken(pParse->db, pName1);
94966     if( !zColl ) return;
94967     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
94968     if( pColl ){
94969       reindexDatabases(pParse, zColl);
94970       sqlite3DbFree(db, zColl);
94971       return;
94972     }
94973     sqlite3DbFree(db, zColl);
94974   }
94975   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
94976   if( iDb<0 ) return;
94977   z = sqlite3NameFromToken(db, pObjName);
94978   if( z==0 ) return;
94979   zDb = db->aDb[iDb].zName;
94980   pTab = sqlite3FindTable(db, z, zDb);
94981   if( pTab ){
94982     reindexTable(pParse, pTab, 0);
94983     sqlite3DbFree(db, z);
94984     return;
94985   }
94986   pIndex = sqlite3FindIndex(db, z, zDb);
94987   sqlite3DbFree(db, z);
94988   if( pIndex ){
94989     sqlite3BeginWriteOperation(pParse, 0, iDb);
94990     sqlite3RefillIndex(pParse, pIndex, -1);
94991     return;
94992   }
94993   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
94994 }
94995 #endif
94996 
94997 /*
94998 ** Return a KeyInfo structure that is appropriate for the given Index.
94999 **
95000 ** The KeyInfo structure for an index is cached in the Index object.
95001 ** So there might be multiple references to the returned pointer.  The
95002 ** caller should not try to modify the KeyInfo object.
95003 **
95004 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
95005 ** when it has finished using it.
95006 */
95007 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
95008   int i;
95009   int nCol = pIdx->nColumn;
95010   int nKey = pIdx->nKeyCol;
95011   KeyInfo *pKey;
95012   if( pParse->nErr ) return 0;
95013   if( pIdx->uniqNotNull ){
95014     pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
95015   }else{
95016     pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
95017   }
95018   if( pKey ){
95019     assert( sqlite3KeyInfoIsWriteable(pKey) );
95020     for(i=0; i<nCol; i++){
95021       char *zColl = pIdx->azColl[i];
95022       assert( zColl!=0 );
95023       pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
95024                         sqlite3LocateCollSeq(pParse, zColl);
95025       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
95026     }
95027     if( pParse->nErr ){
95028       sqlite3KeyInfoUnref(pKey);
95029       pKey = 0;
95030     }
95031   }
95032   return pKey;
95033 }
95034 
95035 #ifndef SQLITE_OMIT_CTE
95036 /*
95037 ** This routine is invoked once per CTE by the parser while parsing a
95038 ** WITH clause.
95039 */
95040 SQLITE_PRIVATE With *sqlite3WithAdd(
95041   Parse *pParse,          /* Parsing context */
95042   With *pWith,            /* Existing WITH clause, or NULL */
95043   Token *pName,           /* Name of the common-table */
95044   ExprList *pArglist,     /* Optional column name list for the table */
95045   Select *pQuery          /* Query used to initialize the table */
95046 ){
95047   sqlite3 *db = pParse->db;
95048   With *pNew;
95049   char *zName;
95050 
95051   /* Check that the CTE name is unique within this WITH clause. If
95052   ** not, store an error in the Parse structure. */
95053   zName = sqlite3NameFromToken(pParse->db, pName);
95054   if( zName && pWith ){
95055     int i;
95056     for(i=0; i<pWith->nCte; i++){
95057       if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
95058         sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
95059       }
95060     }
95061   }
95062 
95063   if( pWith ){
95064     int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
95065     pNew = sqlite3DbRealloc(db, pWith, nByte);
95066   }else{
95067     pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
95068   }
95069   assert( zName!=0 || pNew==0 );
95070   assert( db->mallocFailed==0 || pNew==0 );
95071 
95072   if( pNew==0 ){
95073     sqlite3ExprListDelete(db, pArglist);
95074     sqlite3SelectDelete(db, pQuery);
95075     sqlite3DbFree(db, zName);
95076     pNew = pWith;
95077   }else{
95078     pNew->a[pNew->nCte].pSelect = pQuery;
95079     pNew->a[pNew->nCte].pCols = pArglist;
95080     pNew->a[pNew->nCte].zName = zName;
95081     pNew->a[pNew->nCte].zErr = 0;
95082     pNew->nCte++;
95083   }
95084 
95085   return pNew;
95086 }
95087 
95088 /*
95089 ** Free the contents of the With object passed as the second argument.
95090 */
95091 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
95092   if( pWith ){
95093     int i;
95094     for(i=0; i<pWith->nCte; i++){
95095       struct Cte *pCte = &pWith->a[i];
95096       sqlite3ExprListDelete(db, pCte->pCols);
95097       sqlite3SelectDelete(db, pCte->pSelect);
95098       sqlite3DbFree(db, pCte->zName);
95099     }
95100     sqlite3DbFree(db, pWith);
95101   }
95102 }
95103 #endif /* !defined(SQLITE_OMIT_CTE) */
95104 
95105 /************** End of build.c ***********************************************/
95106 /************** Begin file callback.c ****************************************/
95107 /*
95108 ** 2005 May 23
95109 **
95110 ** The author disclaims copyright to this source code.  In place of
95111 ** a legal notice, here is a blessing:
95112 **
95113 **    May you do good and not evil.
95114 **    May you find forgiveness for yourself and forgive others.
95115 **    May you share freely, never taking more than you give.
95116 **
95117 *************************************************************************
95118 **
95119 ** This file contains functions used to access the internal hash tables
95120 ** of user defined functions and collation sequences.
95121 */
95122 
95123 
95124 /*
95125 ** Invoke the 'collation needed' callback to request a collation sequence
95126 ** in the encoding enc of name zName, length nName.
95127 */
95128 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
95129   assert( !db->xCollNeeded || !db->xCollNeeded16 );
95130   if( db->xCollNeeded ){
95131     char *zExternal = sqlite3DbStrDup(db, zName);
95132     if( !zExternal ) return;
95133     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
95134     sqlite3DbFree(db, zExternal);
95135   }
95136 #ifndef SQLITE_OMIT_UTF16
95137   if( db->xCollNeeded16 ){
95138     char const *zExternal;
95139     sqlite3_value *pTmp = sqlite3ValueNew(db);
95140     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
95141     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
95142     if( zExternal ){
95143       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
95144     }
95145     sqlite3ValueFree(pTmp);
95146   }
95147 #endif
95148 }
95149 
95150 /*
95151 ** This routine is called if the collation factory fails to deliver a
95152 ** collation function in the best encoding but there may be other versions
95153 ** of this collation function (for other text encodings) available. Use one
95154 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
95155 ** possible.
95156 */
95157 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
95158   CollSeq *pColl2;
95159   char *z = pColl->zName;
95160   int i;
95161   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
95162   for(i=0; i<3; i++){
95163     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
95164     if( pColl2->xCmp!=0 ){
95165       memcpy(pColl, pColl2, sizeof(CollSeq));
95166       pColl->xDel = 0;         /* Do not copy the destructor */
95167       return SQLITE_OK;
95168     }
95169   }
95170   return SQLITE_ERROR;
95171 }
95172 
95173 /*
95174 ** This function is responsible for invoking the collation factory callback
95175 ** or substituting a collation sequence of a different encoding when the
95176 ** requested collation sequence is not available in the desired encoding.
95177 **
95178 ** If it is not NULL, then pColl must point to the database native encoding
95179 ** collation sequence with name zName, length nName.
95180 **
95181 ** The return value is either the collation sequence to be used in database
95182 ** db for collation type name zName, length nName, or NULL, if no collation
95183 ** sequence can be found.  If no collation is found, leave an error message.
95184 **
95185 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
95186 */
95187 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
95188   Parse *pParse,        /* Parsing context */
95189   u8 enc,               /* The desired encoding for the collating sequence */
95190   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
95191   const char *zName     /* Collating sequence name */
95192 ){
95193   CollSeq *p;
95194   sqlite3 *db = pParse->db;
95195 
95196   p = pColl;
95197   if( !p ){
95198     p = sqlite3FindCollSeq(db, enc, zName, 0);
95199   }
95200   if( !p || !p->xCmp ){
95201     /* No collation sequence of this type for this encoding is registered.
95202     ** Call the collation factory to see if it can supply us with one.
95203     */
95204     callCollNeeded(db, enc, zName);
95205     p = sqlite3FindCollSeq(db, enc, zName, 0);
95206   }
95207   if( p && !p->xCmp && synthCollSeq(db, p) ){
95208     p = 0;
95209   }
95210   assert( !p || p->xCmp );
95211   if( p==0 ){
95212     sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
95213   }
95214   return p;
95215 }
95216 
95217 /*
95218 ** This routine is called on a collation sequence before it is used to
95219 ** check that it is defined. An undefined collation sequence exists when
95220 ** a database is loaded that contains references to collation sequences
95221 ** that have not been defined by sqlite3_create_collation() etc.
95222 **
95223 ** If required, this routine calls the 'collation needed' callback to
95224 ** request a definition of the collating sequence. If this doesn't work,
95225 ** an equivalent collating sequence that uses a text encoding different
95226 ** from the main database is substituted, if one is available.
95227 */
95228 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
95229   if( pColl ){
95230     const char *zName = pColl->zName;
95231     sqlite3 *db = pParse->db;
95232     CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
95233     if( !p ){
95234       return SQLITE_ERROR;
95235     }
95236     assert( p==pColl );
95237   }
95238   return SQLITE_OK;
95239 }
95240 
95241 
95242 
95243 /*
95244 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
95245 ** specified by zName and nName is not found and parameter 'create' is
95246 ** true, then create a new entry. Otherwise return NULL.
95247 **
95248 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
95249 ** array of three CollSeq structures. The first is the collation sequence
95250 ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
95251 **
95252 ** Stored immediately after the three collation sequences is a copy of
95253 ** the collation sequence name. A pointer to this string is stored in
95254 ** each collation sequence structure.
95255 */
95256 static CollSeq *findCollSeqEntry(
95257   sqlite3 *db,          /* Database connection */
95258   const char *zName,    /* Name of the collating sequence */
95259   int create            /* Create a new entry if true */
95260 ){
95261   CollSeq *pColl;
95262   pColl = sqlite3HashFind(&db->aCollSeq, zName);
95263 
95264   if( 0==pColl && create ){
95265     int nName = sqlite3Strlen30(zName);
95266     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
95267     if( pColl ){
95268       CollSeq *pDel = 0;
95269       pColl[0].zName = (char*)&pColl[3];
95270       pColl[0].enc = SQLITE_UTF8;
95271       pColl[1].zName = (char*)&pColl[3];
95272       pColl[1].enc = SQLITE_UTF16LE;
95273       pColl[2].zName = (char*)&pColl[3];
95274       pColl[2].enc = SQLITE_UTF16BE;
95275       memcpy(pColl[0].zName, zName, nName);
95276       pColl[0].zName[nName] = 0;
95277       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
95278 
95279       /* If a malloc() failure occurred in sqlite3HashInsert(), it will
95280       ** return the pColl pointer to be deleted (because it wasn't added
95281       ** to the hash table).
95282       */
95283       assert( pDel==0 || pDel==pColl );
95284       if( pDel!=0 ){
95285         db->mallocFailed = 1;
95286         sqlite3DbFree(db, pDel);
95287         pColl = 0;
95288       }
95289     }
95290   }
95291   return pColl;
95292 }
95293 
95294 /*
95295 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
95296 ** Return the CollSeq* pointer for the collation sequence named zName
95297 ** for the encoding 'enc' from the database 'db'.
95298 **
95299 ** If the entry specified is not found and 'create' is true, then create a
95300 ** new entry.  Otherwise return NULL.
95301 **
95302 ** A separate function sqlite3LocateCollSeq() is a wrapper around
95303 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
95304 ** if necessary and generates an error message if the collating sequence
95305 ** cannot be found.
95306 **
95307 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
95308 */
95309 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
95310   sqlite3 *db,
95311   u8 enc,
95312   const char *zName,
95313   int create
95314 ){
95315   CollSeq *pColl;
95316   if( zName ){
95317     pColl = findCollSeqEntry(db, zName, create);
95318   }else{
95319     pColl = db->pDfltColl;
95320   }
95321   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
95322   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
95323   if( pColl ) pColl += enc-1;
95324   return pColl;
95325 }
95326 
95327 /* During the search for the best function definition, this procedure
95328 ** is called to test how well the function passed as the first argument
95329 ** matches the request for a function with nArg arguments in a system
95330 ** that uses encoding enc. The value returned indicates how well the
95331 ** request is matched. A higher value indicates a better match.
95332 **
95333 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
95334 ** is also -1.  In other words, we are searching for a function that
95335 ** takes a variable number of arguments.
95336 **
95337 ** If nArg is -2 that means that we are searching for any function
95338 ** regardless of the number of arguments it uses, so return a positive
95339 ** match score for any
95340 **
95341 ** The returned value is always between 0 and 6, as follows:
95342 **
95343 ** 0: Not a match.
95344 ** 1: UTF8/16 conversion required and function takes any number of arguments.
95345 ** 2: UTF16 byte order change required and function takes any number of args.
95346 ** 3: encoding matches and function takes any number of arguments
95347 ** 4: UTF8/16 conversion required - argument count matches exactly
95348 ** 5: UTF16 byte order conversion required - argument count matches exactly
95349 ** 6: Perfect match:  encoding and argument count match exactly.
95350 **
95351 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
95352 ** a perfect match and any function with both xStep and xFunc NULL is
95353 ** a non-match.
95354 */
95355 #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
95356 static int matchQuality(
95357   FuncDef *p,     /* The function we are evaluating for match quality */
95358   int nArg,       /* Desired number of arguments.  (-1)==any */
95359   u8 enc          /* Desired text encoding */
95360 ){
95361   int match;
95362 
95363   /* nArg of -2 is a special case */
95364   if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
95365 
95366   /* Wrong number of arguments means "no match" */
95367   if( p->nArg!=nArg && p->nArg>=0 ) return 0;
95368 
95369   /* Give a better score to a function with a specific number of arguments
95370   ** than to function that accepts any number of arguments. */
95371   if( p->nArg==nArg ){
95372     match = 4;
95373   }else{
95374     match = 1;
95375   }
95376 
95377   /* Bonus points if the text encoding matches */
95378   if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
95379     match += 2;  /* Exact encoding match */
95380   }else if( (enc & p->funcFlags & 2)!=0 ){
95381     match += 1;  /* Both are UTF16, but with different byte orders */
95382   }
95383 
95384   return match;
95385 }
95386 
95387 /*
95388 ** Search a FuncDefHash for a function with the given name.  Return
95389 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
95390 */
95391 static FuncDef *functionSearch(
95392   FuncDefHash *pHash,  /* Hash table to search */
95393   int h,               /* Hash of the name */
95394   const char *zFunc,   /* Name of function */
95395   int nFunc            /* Number of bytes in zFunc */
95396 ){
95397   FuncDef *p;
95398   for(p=pHash->a[h]; p; p=p->pHash){
95399     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
95400       return p;
95401     }
95402   }
95403   return 0;
95404 }
95405 
95406 /*
95407 ** Insert a new FuncDef into a FuncDefHash hash table.
95408 */
95409 SQLITE_PRIVATE void sqlite3FuncDefInsert(
95410   FuncDefHash *pHash,  /* The hash table into which to insert */
95411   FuncDef *pDef        /* The function definition to insert */
95412 ){
95413   FuncDef *pOther;
95414   int nName = sqlite3Strlen30(pDef->zName);
95415   u8 c1 = (u8)pDef->zName[0];
95416   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
95417   pOther = functionSearch(pHash, h, pDef->zName, nName);
95418   if( pOther ){
95419     assert( pOther!=pDef && pOther->pNext!=pDef );
95420     pDef->pNext = pOther->pNext;
95421     pOther->pNext = pDef;
95422   }else{
95423     pDef->pNext = 0;
95424     pDef->pHash = pHash->a[h];
95425     pHash->a[h] = pDef;
95426   }
95427 }
95428 
95429 
95430 
95431 /*
95432 ** Locate a user function given a name, a number of arguments and a flag
95433 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
95434 ** pointer to the FuncDef structure that defines that function, or return
95435 ** NULL if the function does not exist.
95436 **
95437 ** If the createFlag argument is true, then a new (blank) FuncDef
95438 ** structure is created and liked into the "db" structure if a
95439 ** no matching function previously existed.
95440 **
95441 ** If nArg is -2, then the first valid function found is returned.  A
95442 ** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
95443 ** case is used to see if zName is a valid function name for some number
95444 ** of arguments.  If nArg is -2, then createFlag must be 0.
95445 **
95446 ** If createFlag is false, then a function with the required name and
95447 ** number of arguments may be returned even if the eTextRep flag does not
95448 ** match that requested.
95449 */
95450 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
95451   sqlite3 *db,       /* An open database */
95452   const char *zName, /* Name of the function.  Not null-terminated */
95453   int nName,         /* Number of characters in the name */
95454   int nArg,          /* Number of arguments.  -1 means any number */
95455   u8 enc,            /* Preferred text encoding */
95456   u8 createFlag      /* Create new entry if true and does not otherwise exist */
95457 ){
95458   FuncDef *p;         /* Iterator variable */
95459   FuncDef *pBest = 0; /* Best match found so far */
95460   int bestScore = 0;  /* Score of best match */
95461   int h;              /* Hash value */
95462 
95463   assert( nArg>=(-2) );
95464   assert( nArg>=(-1) || createFlag==0 );
95465   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
95466 
95467   /* First search for a match amongst the application-defined functions.
95468   */
95469   p = functionSearch(&db->aFunc, h, zName, nName);
95470   while( p ){
95471     int score = matchQuality(p, nArg, enc);
95472     if( score>bestScore ){
95473       pBest = p;
95474       bestScore = score;
95475     }
95476     p = p->pNext;
95477   }
95478 
95479   /* If no match is found, search the built-in functions.
95480   **
95481   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
95482   ** functions even if a prior app-defined function was found.  And give
95483   ** priority to built-in functions.
95484   **
95485   ** Except, if createFlag is true, that means that we are trying to
95486   ** install a new function.  Whatever FuncDef structure is returned it will
95487   ** have fields overwritten with new information appropriate for the
95488   ** new function.  But the FuncDefs for built-in functions are read-only.
95489   ** So we must not search for built-ins when creating a new function.
95490   */
95491   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
95492     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
95493     bestScore = 0;
95494     p = functionSearch(pHash, h, zName, nName);
95495     while( p ){
95496       int score = matchQuality(p, nArg, enc);
95497       if( score>bestScore ){
95498         pBest = p;
95499         bestScore = score;
95500       }
95501       p = p->pNext;
95502     }
95503   }
95504 
95505   /* If the createFlag parameter is true and the search did not reveal an
95506   ** exact match for the name, number of arguments and encoding, then add a
95507   ** new entry to the hash table and return it.
95508   */
95509   if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
95510       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
95511     pBest->zName = (char *)&pBest[1];
95512     pBest->nArg = (u16)nArg;
95513     pBest->funcFlags = enc;
95514     memcpy(pBest->zName, zName, nName);
95515     pBest->zName[nName] = 0;
95516     sqlite3FuncDefInsert(&db->aFunc, pBest);
95517   }
95518 
95519   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
95520     return pBest;
95521   }
95522   return 0;
95523 }
95524 
95525 /*
95526 ** Free all resources held by the schema structure. The void* argument points
95527 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
95528 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
95529 ** of the schema hash tables).
95530 **
95531 ** The Schema.cache_size variable is not cleared.
95532 */
95533 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
95534   Hash temp1;
95535   Hash temp2;
95536   HashElem *pElem;
95537   Schema *pSchema = (Schema *)p;
95538 
95539   temp1 = pSchema->tblHash;
95540   temp2 = pSchema->trigHash;
95541   sqlite3HashInit(&pSchema->trigHash);
95542   sqlite3HashClear(&pSchema->idxHash);
95543   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
95544     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
95545   }
95546   sqlite3HashClear(&temp2);
95547   sqlite3HashInit(&pSchema->tblHash);
95548   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
95549     Table *pTab = sqliteHashData(pElem);
95550     sqlite3DeleteTable(0, pTab);
95551   }
95552   sqlite3HashClear(&temp1);
95553   sqlite3HashClear(&pSchema->fkeyHash);
95554   pSchema->pSeqTab = 0;
95555   if( pSchema->schemaFlags & DB_SchemaLoaded ){
95556     pSchema->iGeneration++;
95557     pSchema->schemaFlags &= ~DB_SchemaLoaded;
95558   }
95559 }
95560 
95561 /*
95562 ** Find and return the schema associated with a BTree.  Create
95563 ** a new one if necessary.
95564 */
95565 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
95566   Schema * p;
95567   if( pBt ){
95568     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
95569   }else{
95570     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
95571   }
95572   if( !p ){
95573     db->mallocFailed = 1;
95574   }else if ( 0==p->file_format ){
95575     sqlite3HashInit(&p->tblHash);
95576     sqlite3HashInit(&p->idxHash);
95577     sqlite3HashInit(&p->trigHash);
95578     sqlite3HashInit(&p->fkeyHash);
95579     p->enc = SQLITE_UTF8;
95580   }
95581   return p;
95582 }
95583 
95584 /************** End of callback.c ********************************************/
95585 /************** Begin file delete.c ******************************************/
95586 /*
95587 ** 2001 September 15
95588 **
95589 ** The author disclaims copyright to this source code.  In place of
95590 ** a legal notice, here is a blessing:
95591 **
95592 **    May you do good and not evil.
95593 **    May you find forgiveness for yourself and forgive others.
95594 **    May you share freely, never taking more than you give.
95595 **
95596 *************************************************************************
95597 ** This file contains C code routines that are called by the parser
95598 ** in order to generate code for DELETE FROM statements.
95599 */
95600 
95601 /*
95602 ** While a SrcList can in general represent multiple tables and subqueries
95603 ** (as in the FROM clause of a SELECT statement) in this case it contains
95604 ** the name of a single table, as one might find in an INSERT, DELETE,
95605 ** or UPDATE statement.  Look up that table in the symbol table and
95606 ** return a pointer.  Set an error message and return NULL if the table
95607 ** name is not found or if any other error occurs.
95608 **
95609 ** The following fields are initialized appropriate in pSrc:
95610 **
95611 **    pSrc->a[0].pTab       Pointer to the Table object
95612 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
95613 **
95614 */
95615 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
95616   struct SrcList_item *pItem = pSrc->a;
95617   Table *pTab;
95618   assert( pItem && pSrc->nSrc==1 );
95619   pTab = sqlite3LocateTableItem(pParse, 0, pItem);
95620   sqlite3DeleteTable(pParse->db, pItem->pTab);
95621   pItem->pTab = pTab;
95622   if( pTab ){
95623     pTab->nRef++;
95624   }
95625   if( sqlite3IndexedByLookup(pParse, pItem) ){
95626     pTab = 0;
95627   }
95628   return pTab;
95629 }
95630 
95631 /*
95632 ** Check to make sure the given table is writable.  If it is not
95633 ** writable, generate an error message and return 1.  If it is
95634 ** writable return 0;
95635 */
95636 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
95637   /* A table is not writable under the following circumstances:
95638   **
95639   **   1) It is a virtual table and no implementation of the xUpdate method
95640   **      has been provided, or
95641   **   2) It is a system table (i.e. sqlite_master), this call is not
95642   **      part of a nested parse and writable_schema pragma has not
95643   **      been specified.
95644   **
95645   ** In either case leave an error message in pParse and return non-zero.
95646   */
95647   if( ( IsVirtual(pTab)
95648      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
95649    || ( (pTab->tabFlags & TF_Readonly)!=0
95650      && (pParse->db->flags & SQLITE_WriteSchema)==0
95651      && pParse->nested==0 )
95652   ){
95653     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
95654     return 1;
95655   }
95656 
95657 #ifndef SQLITE_OMIT_VIEW
95658   if( !viewOk && pTab->pSelect ){
95659     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
95660     return 1;
95661   }
95662 #endif
95663   return 0;
95664 }
95665 
95666 
95667 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
95668 /*
95669 ** Evaluate a view and store its result in an ephemeral table.  The
95670 ** pWhere argument is an optional WHERE clause that restricts the
95671 ** set of rows in the view that are to be added to the ephemeral table.
95672 */
95673 SQLITE_PRIVATE void sqlite3MaterializeView(
95674   Parse *pParse,       /* Parsing context */
95675   Table *pView,        /* View definition */
95676   Expr *pWhere,        /* Optional WHERE clause to be added */
95677   int iCur             /* Cursor number for ephemeral table */
95678 ){
95679   SelectDest dest;
95680   Select *pSel;
95681   SrcList *pFrom;
95682   sqlite3 *db = pParse->db;
95683   int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
95684   pWhere = sqlite3ExprDup(db, pWhere, 0);
95685   pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
95686   if( pFrom ){
95687     assert( pFrom->nSrc==1 );
95688     pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
95689     pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
95690     assert( pFrom->a[0].pOn==0 );
95691     assert( pFrom->a[0].pUsing==0 );
95692   }
95693   pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
95694   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
95695   sqlite3Select(pParse, pSel, &dest);
95696   sqlite3SelectDelete(db, pSel);
95697 }
95698 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
95699 
95700 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
95701 /*
95702 ** Generate an expression tree to implement the WHERE, ORDER BY,
95703 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
95704 **
95705 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
95706 **                            \__________________________/
95707 **                               pLimitWhere (pInClause)
95708 */
95709 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
95710   Parse *pParse,               /* The parser context */
95711   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
95712   Expr *pWhere,                /* The WHERE clause.  May be null */
95713   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
95714   Expr *pLimit,                /* The LIMIT clause.  May be null */
95715   Expr *pOffset,               /* The OFFSET clause.  May be null */
95716   char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
95717 ){
95718   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
95719   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
95720   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
95721   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
95722   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
95723   Select *pSelect = NULL;      /* Complete SELECT tree */
95724 
95725   /* Check that there isn't an ORDER BY without a LIMIT clause.
95726   */
95727   if( pOrderBy && (pLimit == 0) ) {
95728     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
95729     goto limit_where_cleanup_2;
95730   }
95731 
95732   /* We only need to generate a select expression if there
95733   ** is a limit/offset term to enforce.
95734   */
95735   if( pLimit == 0 ) {
95736     /* if pLimit is null, pOffset will always be null as well. */
95737     assert( pOffset == 0 );
95738     return pWhere;
95739   }
95740 
95741   /* Generate a select expression tree to enforce the limit/offset
95742   ** term for the DELETE or UPDATE statement.  For example:
95743   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
95744   ** becomes:
95745   **   DELETE FROM table_a WHERE rowid IN (
95746   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
95747   **   );
95748   */
95749 
95750   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
95751   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
95752   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
95753   if( pEList == 0 ) goto limit_where_cleanup_2;
95754 
95755   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
95756   ** and the SELECT subtree. */
95757   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
95758   if( pSelectSrc == 0 ) {
95759     sqlite3ExprListDelete(pParse->db, pEList);
95760     goto limit_where_cleanup_2;
95761   }
95762 
95763   /* generate the SELECT expression tree. */
95764   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
95765                              pOrderBy,0,pLimit,pOffset);
95766   if( pSelect == 0 ) return 0;
95767 
95768   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
95769   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
95770   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
95771   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
95772   if( pInClause == 0 ) goto limit_where_cleanup_1;
95773 
95774   pInClause->x.pSelect = pSelect;
95775   pInClause->flags |= EP_xIsSelect;
95776   sqlite3ExprSetHeightAndFlags(pParse, pInClause);
95777   return pInClause;
95778 
95779   /* something went wrong. clean up anything allocated. */
95780 limit_where_cleanup_1:
95781   sqlite3SelectDelete(pParse->db, pSelect);
95782   return 0;
95783 
95784 limit_where_cleanup_2:
95785   sqlite3ExprDelete(pParse->db, pWhere);
95786   sqlite3ExprListDelete(pParse->db, pOrderBy);
95787   sqlite3ExprDelete(pParse->db, pLimit);
95788   sqlite3ExprDelete(pParse->db, pOffset);
95789   return 0;
95790 }
95791 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
95792        /*      && !defined(SQLITE_OMIT_SUBQUERY) */
95793 
95794 /*
95795 ** Generate code for a DELETE FROM statement.
95796 **
95797 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
95798 **                 \________/       \________________/
95799 **                  pTabList              pWhere
95800 */
95801 SQLITE_PRIVATE void sqlite3DeleteFrom(
95802   Parse *pParse,         /* The parser context */
95803   SrcList *pTabList,     /* The table from which we should delete things */
95804   Expr *pWhere           /* The WHERE clause.  May be null */
95805 ){
95806   Vdbe *v;               /* The virtual database engine */
95807   Table *pTab;           /* The table from which records will be deleted */
95808   const char *zDb;       /* Name of database holding pTab */
95809   int i;                 /* Loop counter */
95810   WhereInfo *pWInfo;     /* Information about the WHERE clause */
95811   Index *pIdx;           /* For looping over indices of the table */
95812   int iTabCur;           /* Cursor number for the table */
95813   int iDataCur = 0;      /* VDBE cursor for the canonical data source */
95814   int iIdxCur = 0;       /* Cursor number of the first index */
95815   int nIdx;              /* Number of indices */
95816   sqlite3 *db;           /* Main database structure */
95817   AuthContext sContext;  /* Authorization context */
95818   NameContext sNC;       /* Name context to resolve expressions in */
95819   int iDb;               /* Database number */
95820   int memCnt = -1;       /* Memory cell used for change counting */
95821   int rcauth;            /* Value returned by authorization callback */
95822   int okOnePass;         /* True for one-pass algorithm without the FIFO */
95823   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
95824   u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
95825   Index *pPk;            /* The PRIMARY KEY index on the table */
95826   int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
95827   i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
95828   int iKey;              /* Memory cell holding key of row to be deleted */
95829   i16 nKey;              /* Number of memory cells in the row key */
95830   int iEphCur = 0;       /* Ephemeral table holding all primary key values */
95831   int iRowSet = 0;       /* Register for rowset of rows to delete */
95832   int addrBypass = 0;    /* Address of jump over the delete logic */
95833   int addrLoop = 0;      /* Top of the delete loop */
95834   int addrDelete = 0;    /* Jump directly to the delete logic */
95835   int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
95836 
95837 #ifndef SQLITE_OMIT_TRIGGER
95838   int isView;                  /* True if attempting to delete from a view */
95839   Trigger *pTrigger;           /* List of table triggers, if required */
95840 #endif
95841 
95842   memset(&sContext, 0, sizeof(sContext));
95843   db = pParse->db;
95844   if( pParse->nErr || db->mallocFailed ){
95845     goto delete_from_cleanup;
95846   }
95847   assert( pTabList->nSrc==1 );
95848 
95849   /* Locate the table which we want to delete.  This table has to be
95850   ** put in an SrcList structure because some of the subroutines we
95851   ** will be calling are designed to work with multiple tables and expect
95852   ** an SrcList* parameter instead of just a Table* parameter.
95853   */
95854   pTab = sqlite3SrcListLookup(pParse, pTabList);
95855   if( pTab==0 )  goto delete_from_cleanup;
95856 
95857   /* Figure out if we have any triggers and if the table being
95858   ** deleted from is a view
95859   */
95860 #ifndef SQLITE_OMIT_TRIGGER
95861   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
95862   isView = pTab->pSelect!=0;
95863 #else
95864 # define pTrigger 0
95865 # define isView 0
95866 #endif
95867 #ifdef SQLITE_OMIT_VIEW
95868 # undef isView
95869 # define isView 0
95870 #endif
95871 
95872   /* If pTab is really a view, make sure it has been initialized.
95873   */
95874   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
95875     goto delete_from_cleanup;
95876   }
95877 
95878   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
95879     goto delete_from_cleanup;
95880   }
95881   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
95882   assert( iDb<db->nDb );
95883   zDb = db->aDb[iDb].zName;
95884   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
95885   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
95886   if( rcauth==SQLITE_DENY ){
95887     goto delete_from_cleanup;
95888   }
95889   assert(!isView || pTrigger);
95890 
95891   /* Assign cursor numbers to the table and all its indices.
95892   */
95893   assert( pTabList->nSrc==1 );
95894   iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
95895   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
95896     pParse->nTab++;
95897   }
95898 
95899   /* Start the view context
95900   */
95901   if( isView ){
95902     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
95903   }
95904 
95905   /* Begin generating code.
95906   */
95907   v = sqlite3GetVdbe(pParse);
95908   if( v==0 ){
95909     goto delete_from_cleanup;
95910   }
95911   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
95912   sqlite3BeginWriteOperation(pParse, 1, iDb);
95913 
95914   /* If we are trying to delete from a view, realize that view into
95915   ** an ephemeral table.
95916   */
95917 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
95918   if( isView ){
95919     sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
95920     iDataCur = iIdxCur = iTabCur;
95921   }
95922 #endif
95923 
95924   /* Resolve the column names in the WHERE clause.
95925   */
95926   memset(&sNC, 0, sizeof(sNC));
95927   sNC.pParse = pParse;
95928   sNC.pSrcList = pTabList;
95929   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
95930     goto delete_from_cleanup;
95931   }
95932 
95933   /* Initialize the counter of the number of rows deleted, if
95934   ** we are counting rows.
95935   */
95936   if( db->flags & SQLITE_CountRows ){
95937     memCnt = ++pParse->nMem;
95938     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
95939   }
95940 
95941 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
95942   /* Special case: A DELETE without a WHERE clause deletes everything.
95943   ** It is easier just to erase the whole table. Prior to version 3.6.5,
95944   ** this optimization caused the row change count (the value returned by
95945   ** API function sqlite3_count_changes) to be set incorrectly.  */
95946   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
95947    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
95948   ){
95949     assert( !isView );
95950     sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
95951     if( HasRowid(pTab) ){
95952       sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
95953                         pTab->zName, P4_STATIC);
95954     }
95955     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95956       assert( pIdx->pSchema==pTab->pSchema );
95957       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
95958     }
95959   }else
95960 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
95961   {
95962     if( HasRowid(pTab) ){
95963       /* For a rowid table, initialize the RowSet to an empty set */
95964       pPk = 0;
95965       nPk = 1;
95966       iRowSet = ++pParse->nMem;
95967       sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
95968     }else{
95969       /* For a WITHOUT ROWID table, create an ephemeral table used to
95970       ** hold all primary keys for rows to be deleted. */
95971       pPk = sqlite3PrimaryKeyIndex(pTab);
95972       assert( pPk!=0 );
95973       nPk = pPk->nKeyCol;
95974       iPk = pParse->nMem+1;
95975       pParse->nMem += nPk;
95976       iEphCur = pParse->nTab++;
95977       addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
95978       sqlite3VdbeSetP4KeyInfo(pParse, pPk);
95979     }
95980 
95981     /* Construct a query to find the rowid or primary key for every row
95982     ** to be deleted, based on the WHERE clause.
95983     */
95984     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
95985                                WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK,
95986                                iTabCur+1);
95987     if( pWInfo==0 ) goto delete_from_cleanup;
95988     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
95989 
95990     /* Keep track of the number of rows to be deleted */
95991     if( db->flags & SQLITE_CountRows ){
95992       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
95993     }
95994 
95995     /* Extract the rowid or primary key for the current row */
95996     if( pPk ){
95997       for(i=0; i<nPk; i++){
95998         sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
95999                                         pPk->aiColumn[i], iPk+i);
96000       }
96001       iKey = iPk;
96002     }else{
96003       iKey = pParse->nMem + 1;
96004       iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
96005       if( iKey>pParse->nMem ) pParse->nMem = iKey;
96006     }
96007 
96008     if( okOnePass ){
96009       /* For ONEPASS, no need to store the rowid/primary-key.  There is only
96010       ** one, so just keep it in its register(s) and fall through to the
96011       ** delete code.
96012       */
96013       nKey = nPk; /* OP_Found will use an unpacked key */
96014       aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
96015       if( aToOpen==0 ){
96016         sqlite3WhereEnd(pWInfo);
96017         goto delete_from_cleanup;
96018       }
96019       memset(aToOpen, 1, nIdx+1);
96020       aToOpen[nIdx+1] = 0;
96021       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
96022       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
96023       if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
96024       addrDelete = sqlite3VdbeAddOp0(v, OP_Goto); /* Jump to DELETE logic */
96025     }else if( pPk ){
96026       /* Construct a composite key for the row to be deleted and remember it */
96027       iKey = ++pParse->nMem;
96028       nKey = 0;   /* Zero tells OP_Found to use a composite key */
96029       sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
96030                         sqlite3IndexAffinityStr(v, pPk), nPk);
96031       sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
96032     }else{
96033       /* Get the rowid of the row to be deleted and remember it in the RowSet */
96034       nKey = 1;  /* OP_Seek always uses a single rowid */
96035       sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
96036     }
96037 
96038     /* End of the WHERE loop */
96039     sqlite3WhereEnd(pWInfo);
96040     if( okOnePass ){
96041       /* Bypass the delete logic below if the WHERE loop found zero rows */
96042       addrBypass = sqlite3VdbeMakeLabel(v);
96043       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBypass);
96044       sqlite3VdbeJumpHere(v, addrDelete);
96045     }
96046 
96047     /* Unless this is a view, open cursors for the table we are
96048     ** deleting from and all its indices. If this is a view, then the
96049     ** only effect this statement has is to fire the INSTEAD OF
96050     ** triggers.
96051     */
96052     if( !isView ){
96053       testcase( IsVirtual(pTab) );
96054       sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
96055                                  &iDataCur, &iIdxCur);
96056       assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
96057       assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
96058     }
96059 
96060     /* Set up a loop over the rowids/primary-keys that were found in the
96061     ** where-clause loop above.
96062     */
96063     if( okOnePass ){
96064       /* Just one row.  Hence the top-of-loop is a no-op */
96065       assert( nKey==nPk );  /* OP_Found will use an unpacked key */
96066       assert( !IsVirtual(pTab) );
96067       if( aToOpen[iDataCur-iTabCur] ){
96068         assert( pPk!=0 || pTab->pSelect!=0 );
96069         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
96070         VdbeCoverage(v);
96071       }
96072     }else if( pPk ){
96073       addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
96074       sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
96075       assert( nKey==0 );  /* OP_Found will use a composite key */
96076     }else{
96077       addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
96078       VdbeCoverage(v);
96079       assert( nKey==1 );
96080     }
96081 
96082     /* Delete the row */
96083 #ifndef SQLITE_OMIT_VIRTUALTABLE
96084     if( IsVirtual(pTab) ){
96085       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
96086       sqlite3VtabMakeWritable(pParse, pTab);
96087       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
96088       sqlite3VdbeChangeP5(v, OE_Abort);
96089       sqlite3MayAbort(pParse);
96090     }else
96091 #endif
96092     {
96093       int count = (pParse->nested==0);    /* True to count changes */
96094       sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
96095                                iKey, nKey, count, OE_Default, okOnePass);
96096     }
96097 
96098     /* End of the loop over all rowids/primary-keys. */
96099     if( okOnePass ){
96100       sqlite3VdbeResolveLabel(v, addrBypass);
96101     }else if( pPk ){
96102       sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
96103       sqlite3VdbeJumpHere(v, addrLoop);
96104     }else{
96105       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrLoop);
96106       sqlite3VdbeJumpHere(v, addrLoop);
96107     }
96108 
96109     /* Close the cursors open on the table and its indexes. */
96110     if( !isView && !IsVirtual(pTab) ){
96111       if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
96112       for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
96113         sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
96114       }
96115     }
96116   } /* End non-truncate path */
96117 
96118   /* Update the sqlite_sequence table by storing the content of the
96119   ** maximum rowid counter values recorded while inserting into
96120   ** autoincrement tables.
96121   */
96122   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
96123     sqlite3AutoincrementEnd(pParse);
96124   }
96125 
96126   /* Return the number of rows that were deleted. If this routine is
96127   ** generating code because of a call to sqlite3NestedParse(), do not
96128   ** invoke the callback function.
96129   */
96130   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
96131     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
96132     sqlite3VdbeSetNumCols(v, 1);
96133     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
96134   }
96135 
96136 delete_from_cleanup:
96137   sqlite3AuthContextPop(&sContext);
96138   sqlite3SrcListDelete(db, pTabList);
96139   sqlite3ExprDelete(db, pWhere);
96140   sqlite3DbFree(db, aToOpen);
96141   return;
96142 }
96143 /* Make sure "isView" and other macros defined above are undefined. Otherwise
96144 ** they may interfere with compilation of other functions in this file
96145 ** (or in another file, if this file becomes part of the amalgamation).  */
96146 #ifdef isView
96147  #undef isView
96148 #endif
96149 #ifdef pTrigger
96150  #undef pTrigger
96151 #endif
96152 
96153 /*
96154 ** This routine generates VDBE code that causes a single row of a
96155 ** single table to be deleted.  Both the original table entry and
96156 ** all indices are removed.
96157 **
96158 ** Preconditions:
96159 **
96160 **   1.  iDataCur is an open cursor on the btree that is the canonical data
96161 **       store for the table.  (This will be either the table itself,
96162 **       in the case of a rowid table, or the PRIMARY KEY index in the case
96163 **       of a WITHOUT ROWID table.)
96164 **
96165 **   2.  Read/write cursors for all indices of pTab must be open as
96166 **       cursor number iIdxCur+i for the i-th index.
96167 **
96168 **   3.  The primary key for the row to be deleted must be stored in a
96169 **       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
96170 **       that a search record formed from OP_MakeRecord is contained in the
96171 **       single memory location iPk.
96172 */
96173 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
96174   Parse *pParse,     /* Parsing context */
96175   Table *pTab,       /* Table containing the row to be deleted */
96176   Trigger *pTrigger, /* List of triggers to (potentially) fire */
96177   int iDataCur,      /* Cursor from which column data is extracted */
96178   int iIdxCur,       /* First index cursor */
96179   int iPk,           /* First memory cell containing the PRIMARY KEY */
96180   i16 nPk,           /* Number of PRIMARY KEY memory cells */
96181   u8 count,          /* If non-zero, increment the row change counter */
96182   u8 onconf,         /* Default ON CONFLICT policy for triggers */
96183   u8 bNoSeek         /* iDataCur is already pointing to the row to delete */
96184 ){
96185   Vdbe *v = pParse->pVdbe;        /* Vdbe */
96186   int iOld = 0;                   /* First register in OLD.* array */
96187   int iLabel;                     /* Label resolved to end of generated code */
96188   u8 opSeek;                      /* Seek opcode */
96189 
96190   /* Vdbe is guaranteed to have been allocated by this stage. */
96191   assert( v );
96192   VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
96193                          iDataCur, iIdxCur, iPk, (int)nPk));
96194 
96195   /* Seek cursor iCur to the row to delete. If this row no longer exists
96196   ** (this can happen if a trigger program has already deleted it), do
96197   ** not attempt to delete it or fire any DELETE triggers.  */
96198   iLabel = sqlite3VdbeMakeLabel(v);
96199   opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
96200   if( !bNoSeek ){
96201     sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
96202     VdbeCoverageIf(v, opSeek==OP_NotExists);
96203     VdbeCoverageIf(v, opSeek==OP_NotFound);
96204   }
96205 
96206   /* If there are any triggers to fire, allocate a range of registers to
96207   ** use for the old.* references in the triggers.  */
96208   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
96209     u32 mask;                     /* Mask of OLD.* columns in use */
96210     int iCol;                     /* Iterator used while populating OLD.* */
96211     int addrStart;                /* Start of BEFORE trigger programs */
96212 
96213     /* TODO: Could use temporary registers here. Also could attempt to
96214     ** avoid copying the contents of the rowid register.  */
96215     mask = sqlite3TriggerColmask(
96216         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
96217     );
96218     mask |= sqlite3FkOldmask(pParse, pTab);
96219     iOld = pParse->nMem+1;
96220     pParse->nMem += (1 + pTab->nCol);
96221 
96222     /* Populate the OLD.* pseudo-table register array. These values will be
96223     ** used by any BEFORE and AFTER triggers that exist.  */
96224     sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
96225     for(iCol=0; iCol<pTab->nCol; iCol++){
96226       testcase( mask!=0xffffffff && iCol==31 );
96227       testcase( mask!=0xffffffff && iCol==32 );
96228       if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
96229         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
96230       }
96231     }
96232 
96233     /* Invoke BEFORE DELETE trigger programs. */
96234     addrStart = sqlite3VdbeCurrentAddr(v);
96235     sqlite3CodeRowTrigger(pParse, pTrigger,
96236         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
96237     );
96238 
96239     /* If any BEFORE triggers were coded, then seek the cursor to the
96240     ** row to be deleted again. It may be that the BEFORE triggers moved
96241     ** the cursor or of already deleted the row that the cursor was
96242     ** pointing to.
96243     */
96244     if( addrStart<sqlite3VdbeCurrentAddr(v) ){
96245       sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
96246       VdbeCoverageIf(v, opSeek==OP_NotExists);
96247       VdbeCoverageIf(v, opSeek==OP_NotFound);
96248     }
96249 
96250     /* Do FK processing. This call checks that any FK constraints that
96251     ** refer to this table (i.e. constraints attached to other tables)
96252     ** are not violated by deleting this row.  */
96253     sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
96254   }
96255 
96256   /* Delete the index and table entries. Skip this step if pTab is really
96257   ** a view (in which case the only effect of the DELETE statement is to
96258   ** fire the INSTEAD OF triggers).  */
96259   if( pTab->pSelect==0 ){
96260     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
96261     sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
96262     if( count ){
96263       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
96264     }
96265   }
96266 
96267   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
96268   ** handle rows (possibly in other tables) that refer via a foreign key
96269   ** to the row just deleted. */
96270   sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
96271 
96272   /* Invoke AFTER DELETE trigger programs. */
96273   sqlite3CodeRowTrigger(pParse, pTrigger,
96274       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
96275   );
96276 
96277   /* Jump here if the row had already been deleted before any BEFORE
96278   ** trigger programs were invoked. Or if a trigger program throws a
96279   ** RAISE(IGNORE) exception.  */
96280   sqlite3VdbeResolveLabel(v, iLabel);
96281   VdbeModuleComment((v, "END: GenRowDel()"));
96282 }
96283 
96284 /*
96285 ** This routine generates VDBE code that causes the deletion of all
96286 ** index entries associated with a single row of a single table, pTab
96287 **
96288 ** Preconditions:
96289 **
96290 **   1.  A read/write cursor "iDataCur" must be open on the canonical storage
96291 **       btree for the table pTab.  (This will be either the table itself
96292 **       for rowid tables or to the primary key index for WITHOUT ROWID
96293 **       tables.)
96294 **
96295 **   2.  Read/write cursors for all indices of pTab must be open as
96296 **       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
96297 **       index is the 0-th index.)
96298 **
96299 **   3.  The "iDataCur" cursor must be already be positioned on the row
96300 **       that is to be deleted.
96301 */
96302 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
96303   Parse *pParse,     /* Parsing and code generating context */
96304   Table *pTab,       /* Table containing the row to be deleted */
96305   int iDataCur,      /* Cursor of table holding data. */
96306   int iIdxCur,       /* First index cursor */
96307   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
96308 ){
96309   int i;             /* Index loop counter */
96310   int r1 = -1;       /* Register holding an index key */
96311   int iPartIdxLabel; /* Jump destination for skipping partial index entries */
96312   Index *pIdx;       /* Current index */
96313   Index *pPrior = 0; /* Prior index */
96314   Vdbe *v;           /* The prepared statement under construction */
96315   Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
96316 
96317   v = pParse->pVdbe;
96318   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
96319   for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
96320     assert( iIdxCur+i!=iDataCur || pPk==pIdx );
96321     if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
96322     if( pIdx==pPk ) continue;
96323     VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
96324     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
96325                                  &iPartIdxLabel, pPrior, r1);
96326     sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
96327                       pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
96328     sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
96329     pPrior = pIdx;
96330   }
96331 }
96332 
96333 /*
96334 ** Generate code that will assemble an index key and stores it in register
96335 ** regOut.  The key with be for index pIdx which is an index on pTab.
96336 ** iCur is the index of a cursor open on the pTab table and pointing to
96337 ** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
96338 ** iCur must be the cursor of the PRIMARY KEY index.
96339 **
96340 ** Return a register number which is the first in a block of
96341 ** registers that holds the elements of the index key.  The
96342 ** block of registers has already been deallocated by the time
96343 ** this routine returns.
96344 **
96345 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
96346 ** to that label if pIdx is a partial index that should be skipped.
96347 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
96348 ** A partial index should be skipped if its WHERE clause evaluates
96349 ** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
96350 ** will be set to zero which is an empty label that is ignored by
96351 ** sqlite3ResolvePartIdxLabel().
96352 **
96353 ** The pPrior and regPrior parameters are used to implement a cache to
96354 ** avoid unnecessary register loads.  If pPrior is not NULL, then it is
96355 ** a pointer to a different index for which an index key has just been
96356 ** computed into register regPrior.  If the current pIdx index is generating
96357 ** its key into the same sequence of registers and if pPrior and pIdx share
96358 ** a column in common, then the register corresponding to that column already
96359 ** holds the correct value and the loading of that register is skipped.
96360 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
96361 ** on a table with multiple indices, and especially with the ROWID or
96362 ** PRIMARY KEY columns of the index.
96363 */
96364 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
96365   Parse *pParse,       /* Parsing context */
96366   Index *pIdx,         /* The index for which to generate a key */
96367   int iDataCur,        /* Cursor number from which to take column data */
96368   int regOut,          /* Put the new key into this register if not 0 */
96369   int prefixOnly,      /* Compute only a unique prefix of the key */
96370   int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
96371   Index *pPrior,       /* Previously generated index key */
96372   int regPrior         /* Register holding previous generated key */
96373 ){
96374   Vdbe *v = pParse->pVdbe;
96375   int j;
96376   Table *pTab = pIdx->pTable;
96377   int regBase;
96378   int nCol;
96379 
96380   if( piPartIdxLabel ){
96381     if( pIdx->pPartIdxWhere ){
96382       *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
96383       pParse->iPartIdxTab = iDataCur;
96384       sqlite3ExprCachePush(pParse);
96385       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
96386                          SQLITE_JUMPIFNULL);
96387     }else{
96388       *piPartIdxLabel = 0;
96389     }
96390   }
96391   nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
96392   regBase = sqlite3GetTempRange(pParse, nCol);
96393   if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
96394   for(j=0; j<nCol; j++){
96395     if( pPrior && pPrior->aiColumn[j]==pIdx->aiColumn[j] ) continue;
96396     sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pIdx->aiColumn[j],
96397                                     regBase+j);
96398     /* If the column affinity is REAL but the number is an integer, then it
96399     ** might be stored in the table as an integer (using a compact
96400     ** representation) then converted to REAL by an OP_RealAffinity opcode.
96401     ** But we are getting ready to store this value back into an index, where
96402     ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
96403     ** opcode if it is present */
96404     sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
96405   }
96406   if( regOut ){
96407     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
96408   }
96409   sqlite3ReleaseTempRange(pParse, regBase, nCol);
96410   return regBase;
96411 }
96412 
96413 /*
96414 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
96415 ** because it was a partial index, then this routine should be called to
96416 ** resolve that label.
96417 */
96418 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
96419   if( iLabel ){
96420     sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
96421     sqlite3ExprCachePop(pParse);
96422   }
96423 }
96424 
96425 /************** End of delete.c **********************************************/
96426 /************** Begin file func.c ********************************************/
96427 /*
96428 ** 2002 February 23
96429 **
96430 ** The author disclaims copyright to this source code.  In place of
96431 ** a legal notice, here is a blessing:
96432 **
96433 **    May you do good and not evil.
96434 **    May you find forgiveness for yourself and forgive others.
96435 **    May you share freely, never taking more than you give.
96436 **
96437 *************************************************************************
96438 ** This file contains the C-language implementations for many of the SQL
96439 ** functions of SQLite.  (Some function, and in particular the date and
96440 ** time functions, are implemented separately.)
96441 */
96442 /* #include <stdlib.h> */
96443 /* #include <assert.h> */
96444 
96445 /*
96446 ** Return the collating function associated with a function.
96447 */
96448 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
96449   VdbeOp *pOp;
96450   assert( context->pVdbe!=0 );
96451   pOp = &context->pVdbe->aOp[context->iOp-1];
96452   assert( pOp->opcode==OP_CollSeq );
96453   assert( pOp->p4type==P4_COLLSEQ );
96454   return pOp->p4.pColl;
96455 }
96456 
96457 /*
96458 ** Indicate that the accumulator load should be skipped on this
96459 ** iteration of the aggregate loop.
96460 */
96461 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
96462   context->skipFlag = 1;
96463 }
96464 
96465 /*
96466 ** Implementation of the non-aggregate min() and max() functions
96467 */
96468 static void minmaxFunc(
96469   sqlite3_context *context,
96470   int argc,
96471   sqlite3_value **argv
96472 ){
96473   int i;
96474   int mask;    /* 0 for min() or 0xffffffff for max() */
96475   int iBest;
96476   CollSeq *pColl;
96477 
96478   assert( argc>1 );
96479   mask = sqlite3_user_data(context)==0 ? 0 : -1;
96480   pColl = sqlite3GetFuncCollSeq(context);
96481   assert( pColl );
96482   assert( mask==-1 || mask==0 );
96483   iBest = 0;
96484   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
96485   for(i=1; i<argc; i++){
96486     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
96487     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
96488       testcase( mask==0 );
96489       iBest = i;
96490     }
96491   }
96492   sqlite3_result_value(context, argv[iBest]);
96493 }
96494 
96495 /*
96496 ** Return the type of the argument.
96497 */
96498 static void typeofFunc(
96499   sqlite3_context *context,
96500   int NotUsed,
96501   sqlite3_value **argv
96502 ){
96503   const char *z = 0;
96504   UNUSED_PARAMETER(NotUsed);
96505   switch( sqlite3_value_type(argv[0]) ){
96506     case SQLITE_INTEGER: z = "integer"; break;
96507     case SQLITE_TEXT:    z = "text";    break;
96508     case SQLITE_FLOAT:   z = "real";    break;
96509     case SQLITE_BLOB:    z = "blob";    break;
96510     default:             z = "null";    break;
96511   }
96512   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
96513 }
96514 
96515 
96516 /*
96517 ** Implementation of the length() function
96518 */
96519 static void lengthFunc(
96520   sqlite3_context *context,
96521   int argc,
96522   sqlite3_value **argv
96523 ){
96524   int len;
96525 
96526   assert( argc==1 );
96527   UNUSED_PARAMETER(argc);
96528   switch( sqlite3_value_type(argv[0]) ){
96529     case SQLITE_BLOB:
96530     case SQLITE_INTEGER:
96531     case SQLITE_FLOAT: {
96532       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
96533       break;
96534     }
96535     case SQLITE_TEXT: {
96536       const unsigned char *z = sqlite3_value_text(argv[0]);
96537       if( z==0 ) return;
96538       len = 0;
96539       while( *z ){
96540         len++;
96541         SQLITE_SKIP_UTF8(z);
96542       }
96543       sqlite3_result_int(context, len);
96544       break;
96545     }
96546     default: {
96547       sqlite3_result_null(context);
96548       break;
96549     }
96550   }
96551 }
96552 
96553 /*
96554 ** Implementation of the abs() function.
96555 **
96556 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
96557 ** the numeric argument X.
96558 */
96559 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
96560   assert( argc==1 );
96561   UNUSED_PARAMETER(argc);
96562   switch( sqlite3_value_type(argv[0]) ){
96563     case SQLITE_INTEGER: {
96564       i64 iVal = sqlite3_value_int64(argv[0]);
96565       if( iVal<0 ){
96566         if( iVal==SMALLEST_INT64 ){
96567           /* IMP: R-31676-45509 If X is the integer -9223372036854775808
96568           ** then abs(X) throws an integer overflow error since there is no
96569           ** equivalent positive 64-bit two complement value. */
96570           sqlite3_result_error(context, "integer overflow", -1);
96571           return;
96572         }
96573         iVal = -iVal;
96574       }
96575       sqlite3_result_int64(context, iVal);
96576       break;
96577     }
96578     case SQLITE_NULL: {
96579       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
96580       sqlite3_result_null(context);
96581       break;
96582     }
96583     default: {
96584       /* Because sqlite3_value_double() returns 0.0 if the argument is not
96585       ** something that can be converted into a number, we have:
96586       ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
96587       ** that cannot be converted to a numeric value.
96588       */
96589       double rVal = sqlite3_value_double(argv[0]);
96590       if( rVal<0 ) rVal = -rVal;
96591       sqlite3_result_double(context, rVal);
96592       break;
96593     }
96594   }
96595 }
96596 
96597 /*
96598 ** Implementation of the instr() function.
96599 **
96600 ** instr(haystack,needle) finds the first occurrence of needle
96601 ** in haystack and returns the number of previous characters plus 1,
96602 ** or 0 if needle does not occur within haystack.
96603 **
96604 ** If both haystack and needle are BLOBs, then the result is one more than
96605 ** the number of bytes in haystack prior to the first occurrence of needle,
96606 ** or 0 if needle never occurs in haystack.
96607 */
96608 static void instrFunc(
96609   sqlite3_context *context,
96610   int argc,
96611   sqlite3_value **argv
96612 ){
96613   const unsigned char *zHaystack;
96614   const unsigned char *zNeedle;
96615   int nHaystack;
96616   int nNeedle;
96617   int typeHaystack, typeNeedle;
96618   int N = 1;
96619   int isText;
96620 
96621   UNUSED_PARAMETER(argc);
96622   typeHaystack = sqlite3_value_type(argv[0]);
96623   typeNeedle = sqlite3_value_type(argv[1]);
96624   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
96625   nHaystack = sqlite3_value_bytes(argv[0]);
96626   nNeedle = sqlite3_value_bytes(argv[1]);
96627   if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
96628     zHaystack = sqlite3_value_blob(argv[0]);
96629     zNeedle = sqlite3_value_blob(argv[1]);
96630     isText = 0;
96631   }else{
96632     zHaystack = sqlite3_value_text(argv[0]);
96633     zNeedle = sqlite3_value_text(argv[1]);
96634     isText = 1;
96635   }
96636   while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
96637     N++;
96638     do{
96639       nHaystack--;
96640       zHaystack++;
96641     }while( isText && (zHaystack[0]&0xc0)==0x80 );
96642   }
96643   if( nNeedle>nHaystack ) N = 0;
96644   sqlite3_result_int(context, N);
96645 }
96646 
96647 /*
96648 ** Implementation of the printf() function.
96649 */
96650 static void printfFunc(
96651   sqlite3_context *context,
96652   int argc,
96653   sqlite3_value **argv
96654 ){
96655   PrintfArguments x;
96656   StrAccum str;
96657   const char *zFormat;
96658   int n;
96659   sqlite3 *db = sqlite3_context_db_handle(context);
96660 
96661   if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
96662     x.nArg = argc-1;
96663     x.nUsed = 0;
96664     x.apArg = argv+1;
96665     sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
96666     sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
96667     n = str.nChar;
96668     sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
96669                         SQLITE_DYNAMIC);
96670   }
96671 }
96672 
96673 /*
96674 ** Implementation of the substr() function.
96675 **
96676 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
96677 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
96678 ** of x.  If x is text, then we actually count UTF-8 characters.
96679 ** If x is a blob, then we count bytes.
96680 **
96681 ** If p1 is negative, then we begin abs(p1) from the end of x[].
96682 **
96683 ** If p2 is negative, return the p2 characters preceding p1.
96684 */
96685 static void substrFunc(
96686   sqlite3_context *context,
96687   int argc,
96688   sqlite3_value **argv
96689 ){
96690   const unsigned char *z;
96691   const unsigned char *z2;
96692   int len;
96693   int p0type;
96694   i64 p1, p2;
96695   int negP2 = 0;
96696 
96697   assert( argc==3 || argc==2 );
96698   if( sqlite3_value_type(argv[1])==SQLITE_NULL
96699    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
96700   ){
96701     return;
96702   }
96703   p0type = sqlite3_value_type(argv[0]);
96704   p1 = sqlite3_value_int(argv[1]);
96705   if( p0type==SQLITE_BLOB ){
96706     len = sqlite3_value_bytes(argv[0]);
96707     z = sqlite3_value_blob(argv[0]);
96708     if( z==0 ) return;
96709     assert( len==sqlite3_value_bytes(argv[0]) );
96710   }else{
96711     z = sqlite3_value_text(argv[0]);
96712     if( z==0 ) return;
96713     len = 0;
96714     if( p1<0 ){
96715       for(z2=z; *z2; len++){
96716         SQLITE_SKIP_UTF8(z2);
96717       }
96718     }
96719   }
96720 #ifdef SQLITE_SUBSTR_COMPATIBILITY
96721   /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
96722   ** as substr(X,1,N) - it returns the first N characters of X.  This
96723   ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
96724   ** from 2009-02-02 for compatibility of applications that exploited the
96725   ** old buggy behavior. */
96726   if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
96727 #endif
96728   if( argc==3 ){
96729     p2 = sqlite3_value_int(argv[2]);
96730     if( p2<0 ){
96731       p2 = -p2;
96732       negP2 = 1;
96733     }
96734   }else{
96735     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
96736   }
96737   if( p1<0 ){
96738     p1 += len;
96739     if( p1<0 ){
96740       p2 += p1;
96741       if( p2<0 ) p2 = 0;
96742       p1 = 0;
96743     }
96744   }else if( p1>0 ){
96745     p1--;
96746   }else if( p2>0 ){
96747     p2--;
96748   }
96749   if( negP2 ){
96750     p1 -= p2;
96751     if( p1<0 ){
96752       p2 += p1;
96753       p1 = 0;
96754     }
96755   }
96756   assert( p1>=0 && p2>=0 );
96757   if( p0type!=SQLITE_BLOB ){
96758     while( *z && p1 ){
96759       SQLITE_SKIP_UTF8(z);
96760       p1--;
96761     }
96762     for(z2=z; *z2 && p2; p2--){
96763       SQLITE_SKIP_UTF8(z2);
96764     }
96765     sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
96766                           SQLITE_UTF8);
96767   }else{
96768     if( p1+p2>len ){
96769       p2 = len-p1;
96770       if( p2<0 ) p2 = 0;
96771     }
96772     sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
96773   }
96774 }
96775 
96776 /*
96777 ** Implementation of the round() function
96778 */
96779 #ifndef SQLITE_OMIT_FLOATING_POINT
96780 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
96781   int n = 0;
96782   double r;
96783   char *zBuf;
96784   assert( argc==1 || argc==2 );
96785   if( argc==2 ){
96786     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
96787     n = sqlite3_value_int(argv[1]);
96788     if( n>30 ) n = 30;
96789     if( n<0 ) n = 0;
96790   }
96791   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
96792   r = sqlite3_value_double(argv[0]);
96793   /* If Y==0 and X will fit in a 64-bit int,
96794   ** handle the rounding directly,
96795   ** otherwise use printf.
96796   */
96797   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
96798     r = (double)((sqlite_int64)(r+0.5));
96799   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
96800     r = -(double)((sqlite_int64)((-r)+0.5));
96801   }else{
96802     zBuf = sqlite3_mprintf("%.*f",n,r);
96803     if( zBuf==0 ){
96804       sqlite3_result_error_nomem(context);
96805       return;
96806     }
96807     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
96808     sqlite3_free(zBuf);
96809   }
96810   sqlite3_result_double(context, r);
96811 }
96812 #endif
96813 
96814 /*
96815 ** Allocate nByte bytes of space using sqlite3Malloc(). If the
96816 ** allocation fails, call sqlite3_result_error_nomem() to notify
96817 ** the database handle that malloc() has failed and return NULL.
96818 ** If nByte is larger than the maximum string or blob length, then
96819 ** raise an SQLITE_TOOBIG exception and return NULL.
96820 */
96821 static void *contextMalloc(sqlite3_context *context, i64 nByte){
96822   char *z;
96823   sqlite3 *db = sqlite3_context_db_handle(context);
96824   assert( nByte>0 );
96825   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
96826   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
96827   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
96828     sqlite3_result_error_toobig(context);
96829     z = 0;
96830   }else{
96831     z = sqlite3Malloc(nByte);
96832     if( !z ){
96833       sqlite3_result_error_nomem(context);
96834     }
96835   }
96836   return z;
96837 }
96838 
96839 /*
96840 ** Implementation of the upper() and lower() SQL functions.
96841 */
96842 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
96843   char *z1;
96844   const char *z2;
96845   int i, n;
96846   UNUSED_PARAMETER(argc);
96847   z2 = (char*)sqlite3_value_text(argv[0]);
96848   n = sqlite3_value_bytes(argv[0]);
96849   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
96850   assert( z2==(char*)sqlite3_value_text(argv[0]) );
96851   if( z2 ){
96852     z1 = contextMalloc(context, ((i64)n)+1);
96853     if( z1 ){
96854       for(i=0; i<n; i++){
96855         z1[i] = (char)sqlite3Toupper(z2[i]);
96856       }
96857       sqlite3_result_text(context, z1, n, sqlite3_free);
96858     }
96859   }
96860 }
96861 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
96862   char *z1;
96863   const char *z2;
96864   int i, n;
96865   UNUSED_PARAMETER(argc);
96866   z2 = (char*)sqlite3_value_text(argv[0]);
96867   n = sqlite3_value_bytes(argv[0]);
96868   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
96869   assert( z2==(char*)sqlite3_value_text(argv[0]) );
96870   if( z2 ){
96871     z1 = contextMalloc(context, ((i64)n)+1);
96872     if( z1 ){
96873       for(i=0; i<n; i++){
96874         z1[i] = sqlite3Tolower(z2[i]);
96875       }
96876       sqlite3_result_text(context, z1, n, sqlite3_free);
96877     }
96878   }
96879 }
96880 
96881 /*
96882 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
96883 ** as VDBE code so that unused argument values do not have to be computed.
96884 ** However, we still need some kind of function implementation for this
96885 ** routines in the function table.  The noopFunc macro provides this.
96886 ** noopFunc will never be called so it doesn't matter what the implementation
96887 ** is.  We might as well use the "version()" function as a substitute.
96888 */
96889 #define noopFunc versionFunc   /* Substitute function - never called */
96890 
96891 /*
96892 ** Implementation of random().  Return a random integer.
96893 */
96894 static void randomFunc(
96895   sqlite3_context *context,
96896   int NotUsed,
96897   sqlite3_value **NotUsed2
96898 ){
96899   sqlite_int64 r;
96900   UNUSED_PARAMETER2(NotUsed, NotUsed2);
96901   sqlite3_randomness(sizeof(r), &r);
96902   if( r<0 ){
96903     /* We need to prevent a random number of 0x8000000000000000
96904     ** (or -9223372036854775808) since when you do abs() of that
96905     ** number of you get the same value back again.  To do this
96906     ** in a way that is testable, mask the sign bit off of negative
96907     ** values, resulting in a positive value.  Then take the
96908     ** 2s complement of that positive value.  The end result can
96909     ** therefore be no less than -9223372036854775807.
96910     */
96911     r = -(r & LARGEST_INT64);
96912   }
96913   sqlite3_result_int64(context, r);
96914 }
96915 
96916 /*
96917 ** Implementation of randomblob(N).  Return a random blob
96918 ** that is N bytes long.
96919 */
96920 static void randomBlob(
96921   sqlite3_context *context,
96922   int argc,
96923   sqlite3_value **argv
96924 ){
96925   int n;
96926   unsigned char *p;
96927   assert( argc==1 );
96928   UNUSED_PARAMETER(argc);
96929   n = sqlite3_value_int(argv[0]);
96930   if( n<1 ){
96931     n = 1;
96932   }
96933   p = contextMalloc(context, n);
96934   if( p ){
96935     sqlite3_randomness(n, p);
96936     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
96937   }
96938 }
96939 
96940 /*
96941 ** Implementation of the last_insert_rowid() SQL function.  The return
96942 ** value is the same as the sqlite3_last_insert_rowid() API function.
96943 */
96944 static void last_insert_rowid(
96945   sqlite3_context *context,
96946   int NotUsed,
96947   sqlite3_value **NotUsed2
96948 ){
96949   sqlite3 *db = sqlite3_context_db_handle(context);
96950   UNUSED_PARAMETER2(NotUsed, NotUsed2);
96951   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
96952   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
96953   ** function. */
96954   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
96955 }
96956 
96957 /*
96958 ** Implementation of the changes() SQL function.
96959 **
96960 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
96961 ** around the sqlite3_changes() C/C++ function and hence follows the same
96962 ** rules for counting changes.
96963 */
96964 static void changes(
96965   sqlite3_context *context,
96966   int NotUsed,
96967   sqlite3_value **NotUsed2
96968 ){
96969   sqlite3 *db = sqlite3_context_db_handle(context);
96970   UNUSED_PARAMETER2(NotUsed, NotUsed2);
96971   sqlite3_result_int(context, sqlite3_changes(db));
96972 }
96973 
96974 /*
96975 ** Implementation of the total_changes() SQL function.  The return value is
96976 ** the same as the sqlite3_total_changes() API function.
96977 */
96978 static void total_changes(
96979   sqlite3_context *context,
96980   int NotUsed,
96981   sqlite3_value **NotUsed2
96982 ){
96983   sqlite3 *db = sqlite3_context_db_handle(context);
96984   UNUSED_PARAMETER2(NotUsed, NotUsed2);
96985   /* IMP: R-52756-41993 This function is a wrapper around the
96986   ** sqlite3_total_changes() C/C++ interface. */
96987   sqlite3_result_int(context, sqlite3_total_changes(db));
96988 }
96989 
96990 /*
96991 ** A structure defining how to do GLOB-style comparisons.
96992 */
96993 struct compareInfo {
96994   u8 matchAll;
96995   u8 matchOne;
96996   u8 matchSet;
96997   u8 noCase;
96998 };
96999 
97000 /*
97001 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
97002 ** character is exactly one byte in size.  Also, all characters are
97003 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
97004 ** whereas only characters less than 0x80 do in ASCII.
97005 */
97006 #if defined(SQLITE_EBCDIC)
97007 # define sqlite3Utf8Read(A)        (*((*A)++))
97008 # define GlobUpperToLower(A)       A = sqlite3UpperToLower[A]
97009 # define GlobUpperToLowerAscii(A)  A = sqlite3UpperToLower[A]
97010 #else
97011 # define GlobUpperToLower(A)       if( A<=0x7f ){ A = sqlite3UpperToLower[A]; }
97012 # define GlobUpperToLowerAscii(A)  A = sqlite3UpperToLower[A]
97013 #endif
97014 
97015 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
97016 /* The correct SQL-92 behavior is for the LIKE operator to ignore
97017 ** case.  Thus  'a' LIKE 'A' would be true. */
97018 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
97019 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
97020 ** is case sensitive causing 'a' LIKE 'A' to be false */
97021 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
97022 
97023 /*
97024 ** Compare two UTF-8 strings for equality where the first string can
97025 ** potentially be a "glob" or "like" expression.  Return true (1) if they
97026 ** are the same and false (0) if they are different.
97027 **
97028 ** Globbing rules:
97029 **
97030 **      '*'       Matches any sequence of zero or more characters.
97031 **
97032 **      '?'       Matches exactly one character.
97033 **
97034 **     [...]      Matches one character from the enclosed list of
97035 **                characters.
97036 **
97037 **     [^...]     Matches one character not in the enclosed list.
97038 **
97039 ** With the [...] and [^...] matching, a ']' character can be included
97040 ** in the list by making it the first character after '[' or '^'.  A
97041 ** range of characters can be specified using '-'.  Example:
97042 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
97043 ** it the last character in the list.
97044 **
97045 ** Like matching rules:
97046 **
97047 **      '%'       Matches any sequence of zero or more characters
97048 **
97049 ***     '_'       Matches any one character
97050 **
97051 **      Ec        Where E is the "esc" character and c is any other
97052 **                character, including '%', '_', and esc, match exactly c.
97053 **
97054 ** The comments through this routine usually assume glob matching.
97055 **
97056 ** This routine is usually quick, but can be N**2 in the worst case.
97057 */
97058 static int patternCompare(
97059   const u8 *zPattern,              /* The glob pattern */
97060   const u8 *zString,               /* The string to compare against the glob */
97061   const struct compareInfo *pInfo, /* Information about how to do the compare */
97062   u32 esc                          /* The escape character */
97063 ){
97064   u32 c, c2;                       /* Next pattern and input string chars */
97065   u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
97066   u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
97067   u32 matchOther;                  /* "[" or the escape character */
97068   u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
97069   const u8 *zEscaped = 0;          /* One past the last escaped input char */
97070 
97071   /* The GLOB operator does not have an ESCAPE clause.  And LIKE does not
97072   ** have the matchSet operator.  So we either have to look for one or
97073   ** the other, never both.  Hence the single variable matchOther is used
97074   ** to store the one we have to look for.
97075   */
97076   matchOther = esc ? esc : pInfo->matchSet;
97077 
97078   while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
97079     if( c==matchAll ){  /* Match "*" */
97080       /* Skip over multiple "*" characters in the pattern.  If there
97081       ** are also "?" characters, skip those as well, but consume a
97082       ** single character of the input string for each "?" skipped */
97083       while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
97084                || c == matchOne ){
97085         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
97086           return 0;
97087         }
97088       }
97089       if( c==0 ){
97090         return 1;   /* "*" at the end of the pattern matches */
97091       }else if( c==matchOther ){
97092         if( esc ){
97093           c = sqlite3Utf8Read(&zPattern);
97094           if( c==0 ) return 0;
97095         }else{
97096           /* "[...]" immediately follows the "*".  We have to do a slow
97097           ** recursive search in this case, but it is an unusual case. */
97098           assert( matchOther<0x80 );  /* '[' is a single-byte character */
97099           while( *zString
97100                  && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
97101             SQLITE_SKIP_UTF8(zString);
97102           }
97103           return *zString!=0;
97104         }
97105       }
97106 
97107       /* At this point variable c contains the first character of the
97108       ** pattern string past the "*".  Search in the input string for the
97109       ** first matching character and recursively contine the match from
97110       ** that point.
97111       **
97112       ** For a case-insensitive search, set variable cx to be the same as
97113       ** c but in the other case and search the input string for either
97114       ** c or cx.
97115       */
97116       if( c<=0x80 ){
97117         u32 cx;
97118         if( noCase ){
97119           cx = sqlite3Toupper(c);
97120           c = sqlite3Tolower(c);
97121         }else{
97122           cx = c;
97123         }
97124         while( (c2 = *(zString++))!=0 ){
97125           if( c2!=c && c2!=cx ) continue;
97126           if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
97127         }
97128       }else{
97129         while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
97130           if( c2!=c ) continue;
97131           if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
97132         }
97133       }
97134       return 0;
97135     }
97136     if( c==matchOther ){
97137       if( esc ){
97138         c = sqlite3Utf8Read(&zPattern);
97139         if( c==0 ) return 0;
97140         zEscaped = zPattern;
97141       }else{
97142         u32 prior_c = 0;
97143         int seen = 0;
97144         int invert = 0;
97145         c = sqlite3Utf8Read(&zString);
97146         if( c==0 ) return 0;
97147         c2 = sqlite3Utf8Read(&zPattern);
97148         if( c2=='^' ){
97149           invert = 1;
97150           c2 = sqlite3Utf8Read(&zPattern);
97151         }
97152         if( c2==']' ){
97153           if( c==']' ) seen = 1;
97154           c2 = sqlite3Utf8Read(&zPattern);
97155         }
97156         while( c2 && c2!=']' ){
97157           if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
97158             c2 = sqlite3Utf8Read(&zPattern);
97159             if( c>=prior_c && c<=c2 ) seen = 1;
97160             prior_c = 0;
97161           }else{
97162             if( c==c2 ){
97163               seen = 1;
97164             }
97165             prior_c = c2;
97166           }
97167           c2 = sqlite3Utf8Read(&zPattern);
97168         }
97169         if( c2==0 || (seen ^ invert)==0 ){
97170           return 0;
97171         }
97172         continue;
97173       }
97174     }
97175     c2 = sqlite3Utf8Read(&zString);
97176     if( c==c2 ) continue;
97177     if( noCase && c<0x80 && c2<0x80 && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
97178       continue;
97179     }
97180     if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
97181     return 0;
97182   }
97183   return *zString==0;
97184 }
97185 
97186 /*
97187 ** The sqlite3_strglob() interface.
97188 */
97189 SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlobPattern, const char *zString){
97190   return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
97191 }
97192 
97193 /*
97194 ** Count the number of times that the LIKE operator (or GLOB which is
97195 ** just a variation of LIKE) gets called.  This is used for testing
97196 ** only.
97197 */
97198 #ifdef SQLITE_TEST
97199 SQLITE_API int sqlite3_like_count = 0;
97200 #endif
97201 
97202 
97203 /*
97204 ** Implementation of the like() SQL function.  This function implements
97205 ** the build-in LIKE operator.  The first argument to the function is the
97206 ** pattern and the second argument is the string.  So, the SQL statements:
97207 **
97208 **       A LIKE B
97209 **
97210 ** is implemented as like(B,A).
97211 **
97212 ** This same function (with a different compareInfo structure) computes
97213 ** the GLOB operator.
97214 */
97215 static void likeFunc(
97216   sqlite3_context *context,
97217   int argc,
97218   sqlite3_value **argv
97219 ){
97220   const unsigned char *zA, *zB;
97221   u32 escape = 0;
97222   int nPat;
97223   sqlite3 *db = sqlite3_context_db_handle(context);
97224 
97225   zB = sqlite3_value_text(argv[0]);
97226   zA = sqlite3_value_text(argv[1]);
97227 
97228   /* Limit the length of the LIKE or GLOB pattern to avoid problems
97229   ** of deep recursion and N*N behavior in patternCompare().
97230   */
97231   nPat = sqlite3_value_bytes(argv[0]);
97232   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
97233   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
97234   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
97235     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
97236     return;
97237   }
97238   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
97239 
97240   if( argc==3 ){
97241     /* The escape character string must consist of a single UTF-8 character.
97242     ** Otherwise, return an error.
97243     */
97244     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
97245     if( zEsc==0 ) return;
97246     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
97247       sqlite3_result_error(context,
97248           "ESCAPE expression must be a single character", -1);
97249       return;
97250     }
97251     escape = sqlite3Utf8Read(&zEsc);
97252   }
97253   if( zA && zB ){
97254     struct compareInfo *pInfo = sqlite3_user_data(context);
97255 #ifdef SQLITE_TEST
97256     sqlite3_like_count++;
97257 #endif
97258 
97259     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
97260   }
97261 }
97262 
97263 /*
97264 ** Implementation of the NULLIF(x,y) function.  The result is the first
97265 ** argument if the arguments are different.  The result is NULL if the
97266 ** arguments are equal to each other.
97267 */
97268 static void nullifFunc(
97269   sqlite3_context *context,
97270   int NotUsed,
97271   sqlite3_value **argv
97272 ){
97273   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
97274   UNUSED_PARAMETER(NotUsed);
97275   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
97276     sqlite3_result_value(context, argv[0]);
97277   }
97278 }
97279 
97280 /*
97281 ** Implementation of the sqlite_version() function.  The result is the version
97282 ** of the SQLite library that is running.
97283 */
97284 static void versionFunc(
97285   sqlite3_context *context,
97286   int NotUsed,
97287   sqlite3_value **NotUsed2
97288 ){
97289   UNUSED_PARAMETER2(NotUsed, NotUsed2);
97290   /* IMP: R-48699-48617 This function is an SQL wrapper around the
97291   ** sqlite3_libversion() C-interface. */
97292   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
97293 }
97294 
97295 /*
97296 ** Implementation of the sqlite_source_id() function. The result is a string
97297 ** that identifies the particular version of the source code used to build
97298 ** SQLite.
97299 */
97300 static void sourceidFunc(
97301   sqlite3_context *context,
97302   int NotUsed,
97303   sqlite3_value **NotUsed2
97304 ){
97305   UNUSED_PARAMETER2(NotUsed, NotUsed2);
97306   /* IMP: R-24470-31136 This function is an SQL wrapper around the
97307   ** sqlite3_sourceid() C interface. */
97308   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
97309 }
97310 
97311 /*
97312 ** Implementation of the sqlite_log() function.  This is a wrapper around
97313 ** sqlite3_log().  The return value is NULL.  The function exists purely for
97314 ** its side-effects.
97315 */
97316 static void errlogFunc(
97317   sqlite3_context *context,
97318   int argc,
97319   sqlite3_value **argv
97320 ){
97321   UNUSED_PARAMETER(argc);
97322   UNUSED_PARAMETER(context);
97323   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
97324 }
97325 
97326 /*
97327 ** Implementation of the sqlite_compileoption_used() function.
97328 ** The result is an integer that identifies if the compiler option
97329 ** was used to build SQLite.
97330 */
97331 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
97332 static void compileoptionusedFunc(
97333   sqlite3_context *context,
97334   int argc,
97335   sqlite3_value **argv
97336 ){
97337   const char *zOptName;
97338   assert( argc==1 );
97339   UNUSED_PARAMETER(argc);
97340   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
97341   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
97342   ** function.
97343   */
97344   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
97345     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
97346   }
97347 }
97348 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
97349 
97350 /*
97351 ** Implementation of the sqlite_compileoption_get() function.
97352 ** The result is a string that identifies the compiler options
97353 ** used to build SQLite.
97354 */
97355 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
97356 static void compileoptiongetFunc(
97357   sqlite3_context *context,
97358   int argc,
97359   sqlite3_value **argv
97360 ){
97361   int n;
97362   assert( argc==1 );
97363   UNUSED_PARAMETER(argc);
97364   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
97365   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
97366   */
97367   n = sqlite3_value_int(argv[0]);
97368   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
97369 }
97370 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
97371 
97372 /* Array for converting from half-bytes (nybbles) into ASCII hex
97373 ** digits. */
97374 static const char hexdigits[] = {
97375   '0', '1', '2', '3', '4', '5', '6', '7',
97376   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
97377 };
97378 
97379 /*
97380 ** Implementation of the QUOTE() function.  This function takes a single
97381 ** argument.  If the argument is numeric, the return value is the same as
97382 ** the argument.  If the argument is NULL, the return value is the string
97383 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
97384 ** single-quote escapes.
97385 */
97386 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
97387   assert( argc==1 );
97388   UNUSED_PARAMETER(argc);
97389   switch( sqlite3_value_type(argv[0]) ){
97390     case SQLITE_FLOAT: {
97391       double r1, r2;
97392       char zBuf[50];
97393       r1 = sqlite3_value_double(argv[0]);
97394       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
97395       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
97396       if( r1!=r2 ){
97397         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
97398       }
97399       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
97400       break;
97401     }
97402     case SQLITE_INTEGER: {
97403       sqlite3_result_value(context, argv[0]);
97404       break;
97405     }
97406     case SQLITE_BLOB: {
97407       char *zText = 0;
97408       char const *zBlob = sqlite3_value_blob(argv[0]);
97409       int nBlob = sqlite3_value_bytes(argv[0]);
97410       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
97411       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
97412       if( zText ){
97413         int i;
97414         for(i=0; i<nBlob; i++){
97415           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
97416           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
97417         }
97418         zText[(nBlob*2)+2] = '\'';
97419         zText[(nBlob*2)+3] = '\0';
97420         zText[0] = 'X';
97421         zText[1] = '\'';
97422         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
97423         sqlite3_free(zText);
97424       }
97425       break;
97426     }
97427     case SQLITE_TEXT: {
97428       int i,j;
97429       u64 n;
97430       const unsigned char *zArg = sqlite3_value_text(argv[0]);
97431       char *z;
97432 
97433       if( zArg==0 ) return;
97434       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
97435       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
97436       if( z ){
97437         z[0] = '\'';
97438         for(i=0, j=1; zArg[i]; i++){
97439           z[j++] = zArg[i];
97440           if( zArg[i]=='\'' ){
97441             z[j++] = '\'';
97442           }
97443         }
97444         z[j++] = '\'';
97445         z[j] = 0;
97446         sqlite3_result_text(context, z, j, sqlite3_free);
97447       }
97448       break;
97449     }
97450     default: {
97451       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
97452       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
97453       break;
97454     }
97455   }
97456 }
97457 
97458 /*
97459 ** The unicode() function.  Return the integer unicode code-point value
97460 ** for the first character of the input string.
97461 */
97462 static void unicodeFunc(
97463   sqlite3_context *context,
97464   int argc,
97465   sqlite3_value **argv
97466 ){
97467   const unsigned char *z = sqlite3_value_text(argv[0]);
97468   (void)argc;
97469   if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
97470 }
97471 
97472 /*
97473 ** The char() function takes zero or more arguments, each of which is
97474 ** an integer.  It constructs a string where each character of the string
97475 ** is the unicode character for the corresponding integer argument.
97476 */
97477 static void charFunc(
97478   sqlite3_context *context,
97479   int argc,
97480   sqlite3_value **argv
97481 ){
97482   unsigned char *z, *zOut;
97483   int i;
97484   zOut = z = sqlite3_malloc64( argc*4+1 );
97485   if( z==0 ){
97486     sqlite3_result_error_nomem(context);
97487     return;
97488   }
97489   for(i=0; i<argc; i++){
97490     sqlite3_int64 x;
97491     unsigned c;
97492     x = sqlite3_value_int64(argv[i]);
97493     if( x<0 || x>0x10ffff ) x = 0xfffd;
97494     c = (unsigned)(x & 0x1fffff);
97495     if( c<0x00080 ){
97496       *zOut++ = (u8)(c&0xFF);
97497     }else if( c<0x00800 ){
97498       *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
97499       *zOut++ = 0x80 + (u8)(c & 0x3F);
97500     }else if( c<0x10000 ){
97501       *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
97502       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
97503       *zOut++ = 0x80 + (u8)(c & 0x3F);
97504     }else{
97505       *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
97506       *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
97507       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
97508       *zOut++ = 0x80 + (u8)(c & 0x3F);
97509     }                                                    \
97510   }
97511   sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
97512 }
97513 
97514 /*
97515 ** The hex() function.  Interpret the argument as a blob.  Return
97516 ** a hexadecimal rendering as text.
97517 */
97518 static void hexFunc(
97519   sqlite3_context *context,
97520   int argc,
97521   sqlite3_value **argv
97522 ){
97523   int i, n;
97524   const unsigned char *pBlob;
97525   char *zHex, *z;
97526   assert( argc==1 );
97527   UNUSED_PARAMETER(argc);
97528   pBlob = sqlite3_value_blob(argv[0]);
97529   n = sqlite3_value_bytes(argv[0]);
97530   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
97531   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
97532   if( zHex ){
97533     for(i=0; i<n; i++, pBlob++){
97534       unsigned char c = *pBlob;
97535       *(z++) = hexdigits[(c>>4)&0xf];
97536       *(z++) = hexdigits[c&0xf];
97537     }
97538     *z = 0;
97539     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
97540   }
97541 }
97542 
97543 /*
97544 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
97545 */
97546 static void zeroblobFunc(
97547   sqlite3_context *context,
97548   int argc,
97549   sqlite3_value **argv
97550 ){
97551   i64 n;
97552   sqlite3 *db = sqlite3_context_db_handle(context);
97553   assert( argc==1 );
97554   UNUSED_PARAMETER(argc);
97555   n = sqlite3_value_int64(argv[0]);
97556   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
97557   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
97558   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
97559     sqlite3_result_error_toobig(context);
97560   }else{
97561     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
97562   }
97563 }
97564 
97565 /*
97566 ** The replace() function.  Three arguments are all strings: call
97567 ** them A, B, and C. The result is also a string which is derived
97568 ** from A by replacing every occurrence of B with C.  The match
97569 ** must be exact.  Collating sequences are not used.
97570 */
97571 static void replaceFunc(
97572   sqlite3_context *context,
97573   int argc,
97574   sqlite3_value **argv
97575 ){
97576   const unsigned char *zStr;        /* The input string A */
97577   const unsigned char *zPattern;    /* The pattern string B */
97578   const unsigned char *zRep;        /* The replacement string C */
97579   unsigned char *zOut;              /* The output */
97580   int nStr;                /* Size of zStr */
97581   int nPattern;            /* Size of zPattern */
97582   int nRep;                /* Size of zRep */
97583   i64 nOut;                /* Maximum size of zOut */
97584   int loopLimit;           /* Last zStr[] that might match zPattern[] */
97585   int i, j;                /* Loop counters */
97586 
97587   assert( argc==3 );
97588   UNUSED_PARAMETER(argc);
97589   zStr = sqlite3_value_text(argv[0]);
97590   if( zStr==0 ) return;
97591   nStr = sqlite3_value_bytes(argv[0]);
97592   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
97593   zPattern = sqlite3_value_text(argv[1]);
97594   if( zPattern==0 ){
97595     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
97596             || sqlite3_context_db_handle(context)->mallocFailed );
97597     return;
97598   }
97599   if( zPattern[0]==0 ){
97600     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
97601     sqlite3_result_value(context, argv[0]);
97602     return;
97603   }
97604   nPattern = sqlite3_value_bytes(argv[1]);
97605   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
97606   zRep = sqlite3_value_text(argv[2]);
97607   if( zRep==0 ) return;
97608   nRep = sqlite3_value_bytes(argv[2]);
97609   assert( zRep==sqlite3_value_text(argv[2]) );
97610   nOut = nStr + 1;
97611   assert( nOut<SQLITE_MAX_LENGTH );
97612   zOut = contextMalloc(context, (i64)nOut);
97613   if( zOut==0 ){
97614     return;
97615   }
97616   loopLimit = nStr - nPattern;
97617   for(i=j=0; i<=loopLimit; i++){
97618     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
97619       zOut[j++] = zStr[i];
97620     }else{
97621       u8 *zOld;
97622       sqlite3 *db = sqlite3_context_db_handle(context);
97623       nOut += nRep - nPattern;
97624       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
97625       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
97626       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
97627         sqlite3_result_error_toobig(context);
97628         sqlite3_free(zOut);
97629         return;
97630       }
97631       zOld = zOut;
97632       zOut = sqlite3_realloc64(zOut, (int)nOut);
97633       if( zOut==0 ){
97634         sqlite3_result_error_nomem(context);
97635         sqlite3_free(zOld);
97636         return;
97637       }
97638       memcpy(&zOut[j], zRep, nRep);
97639       j += nRep;
97640       i += nPattern-1;
97641     }
97642   }
97643   assert( j+nStr-i+1==nOut );
97644   memcpy(&zOut[j], &zStr[i], nStr-i);
97645   j += nStr - i;
97646   assert( j<=nOut );
97647   zOut[j] = 0;
97648   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
97649 }
97650 
97651 /*
97652 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
97653 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
97654 */
97655 static void trimFunc(
97656   sqlite3_context *context,
97657   int argc,
97658   sqlite3_value **argv
97659 ){
97660   const unsigned char *zIn;         /* Input string */
97661   const unsigned char *zCharSet;    /* Set of characters to trim */
97662   int nIn;                          /* Number of bytes in input */
97663   int flags;                        /* 1: trimleft  2: trimright  3: trim */
97664   int i;                            /* Loop counter */
97665   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
97666   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
97667   int nChar;                        /* Number of characters in zCharSet */
97668 
97669   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
97670     return;
97671   }
97672   zIn = sqlite3_value_text(argv[0]);
97673   if( zIn==0 ) return;
97674   nIn = sqlite3_value_bytes(argv[0]);
97675   assert( zIn==sqlite3_value_text(argv[0]) );
97676   if( argc==1 ){
97677     static const unsigned char lenOne[] = { 1 };
97678     static unsigned char * const azOne[] = { (u8*)" " };
97679     nChar = 1;
97680     aLen = (u8*)lenOne;
97681     azChar = (unsigned char **)azOne;
97682     zCharSet = 0;
97683   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
97684     return;
97685   }else{
97686     const unsigned char *z;
97687     for(z=zCharSet, nChar=0; *z; nChar++){
97688       SQLITE_SKIP_UTF8(z);
97689     }
97690     if( nChar>0 ){
97691       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
97692       if( azChar==0 ){
97693         return;
97694       }
97695       aLen = (unsigned char*)&azChar[nChar];
97696       for(z=zCharSet, nChar=0; *z; nChar++){
97697         azChar[nChar] = (unsigned char *)z;
97698         SQLITE_SKIP_UTF8(z);
97699         aLen[nChar] = (u8)(z - azChar[nChar]);
97700       }
97701     }
97702   }
97703   if( nChar>0 ){
97704     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
97705     if( flags & 1 ){
97706       while( nIn>0 ){
97707         int len = 0;
97708         for(i=0; i<nChar; i++){
97709           len = aLen[i];
97710           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
97711         }
97712         if( i>=nChar ) break;
97713         zIn += len;
97714         nIn -= len;
97715       }
97716     }
97717     if( flags & 2 ){
97718       while( nIn>0 ){
97719         int len = 0;
97720         for(i=0; i<nChar; i++){
97721           len = aLen[i];
97722           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
97723         }
97724         if( i>=nChar ) break;
97725         nIn -= len;
97726       }
97727     }
97728     if( zCharSet ){
97729       sqlite3_free(azChar);
97730     }
97731   }
97732   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
97733 }
97734 
97735 
97736 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
97737 ** is only available if the SQLITE_SOUNDEX compile-time option is used
97738 ** when SQLite is built.
97739 */
97740 #ifdef SQLITE_SOUNDEX
97741 /*
97742 ** Compute the soundex encoding of a word.
97743 **
97744 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
97745 ** soundex encoding of the string X.
97746 */
97747 static void soundexFunc(
97748   sqlite3_context *context,
97749   int argc,
97750   sqlite3_value **argv
97751 ){
97752   char zResult[8];
97753   const u8 *zIn;
97754   int i, j;
97755   static const unsigned char iCode[] = {
97756     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
97757     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
97758     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
97759     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
97760     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
97761     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
97762     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
97763     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
97764   };
97765   assert( argc==1 );
97766   zIn = (u8*)sqlite3_value_text(argv[0]);
97767   if( zIn==0 ) zIn = (u8*)"";
97768   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
97769   if( zIn[i] ){
97770     u8 prevcode = iCode[zIn[i]&0x7f];
97771     zResult[0] = sqlite3Toupper(zIn[i]);
97772     for(j=1; j<4 && zIn[i]; i++){
97773       int code = iCode[zIn[i]&0x7f];
97774       if( code>0 ){
97775         if( code!=prevcode ){
97776           prevcode = code;
97777           zResult[j++] = code + '0';
97778         }
97779       }else{
97780         prevcode = 0;
97781       }
97782     }
97783     while( j<4 ){
97784       zResult[j++] = '0';
97785     }
97786     zResult[j] = 0;
97787     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
97788   }else{
97789     /* IMP: R-64894-50321 The string "?000" is returned if the argument
97790     ** is NULL or contains no ASCII alphabetic characters. */
97791     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
97792   }
97793 }
97794 #endif /* SQLITE_SOUNDEX */
97795 
97796 #ifndef SQLITE_OMIT_LOAD_EXTENSION
97797 /*
97798 ** A function that loads a shared-library extension then returns NULL.
97799 */
97800 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
97801   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
97802   const char *zProc;
97803   sqlite3 *db = sqlite3_context_db_handle(context);
97804   char *zErrMsg = 0;
97805 
97806   if( argc==2 ){
97807     zProc = (const char *)sqlite3_value_text(argv[1]);
97808   }else{
97809     zProc = 0;
97810   }
97811   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
97812     sqlite3_result_error(context, zErrMsg, -1);
97813     sqlite3_free(zErrMsg);
97814   }
97815 }
97816 #endif
97817 
97818 
97819 /*
97820 ** An instance of the following structure holds the context of a
97821 ** sum() or avg() aggregate computation.
97822 */
97823 typedef struct SumCtx SumCtx;
97824 struct SumCtx {
97825   double rSum;      /* Floating point sum */
97826   i64 iSum;         /* Integer sum */
97827   i64 cnt;          /* Number of elements summed */
97828   u8 overflow;      /* True if integer overflow seen */
97829   u8 approx;        /* True if non-integer value was input to the sum */
97830 };
97831 
97832 /*
97833 ** Routines used to compute the sum, average, and total.
97834 **
97835 ** The SUM() function follows the (broken) SQL standard which means
97836 ** that it returns NULL if it sums over no inputs.  TOTAL returns
97837 ** 0.0 in that case.  In addition, TOTAL always returns a float where
97838 ** SUM might return an integer if it never encounters a floating point
97839 ** value.  TOTAL never fails, but SUM might through an exception if
97840 ** it overflows an integer.
97841 */
97842 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
97843   SumCtx *p;
97844   int type;
97845   assert( argc==1 );
97846   UNUSED_PARAMETER(argc);
97847   p = sqlite3_aggregate_context(context, sizeof(*p));
97848   type = sqlite3_value_numeric_type(argv[0]);
97849   if( p && type!=SQLITE_NULL ){
97850     p->cnt++;
97851     if( type==SQLITE_INTEGER ){
97852       i64 v = sqlite3_value_int64(argv[0]);
97853       p->rSum += v;
97854       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
97855         p->overflow = 1;
97856       }
97857     }else{
97858       p->rSum += sqlite3_value_double(argv[0]);
97859       p->approx = 1;
97860     }
97861   }
97862 }
97863 static void sumFinalize(sqlite3_context *context){
97864   SumCtx *p;
97865   p = sqlite3_aggregate_context(context, 0);
97866   if( p && p->cnt>0 ){
97867     if( p->overflow ){
97868       sqlite3_result_error(context,"integer overflow",-1);
97869     }else if( p->approx ){
97870       sqlite3_result_double(context, p->rSum);
97871     }else{
97872       sqlite3_result_int64(context, p->iSum);
97873     }
97874   }
97875 }
97876 static void avgFinalize(sqlite3_context *context){
97877   SumCtx *p;
97878   p = sqlite3_aggregate_context(context, 0);
97879   if( p && p->cnt>0 ){
97880     sqlite3_result_double(context, p->rSum/(double)p->cnt);
97881   }
97882 }
97883 static void totalFinalize(sqlite3_context *context){
97884   SumCtx *p;
97885   p = sqlite3_aggregate_context(context, 0);
97886   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
97887   sqlite3_result_double(context, p ? p->rSum : (double)0);
97888 }
97889 
97890 /*
97891 ** The following structure keeps track of state information for the
97892 ** count() aggregate function.
97893 */
97894 typedef struct CountCtx CountCtx;
97895 struct CountCtx {
97896   i64 n;
97897 };
97898 
97899 /*
97900 ** Routines to implement the count() aggregate function.
97901 */
97902 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
97903   CountCtx *p;
97904   p = sqlite3_aggregate_context(context, sizeof(*p));
97905   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
97906     p->n++;
97907   }
97908 
97909 #ifndef SQLITE_OMIT_DEPRECATED
97910   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
97911   ** sure it still operates correctly, verify that its count agrees with our
97912   ** internal count when using count(*) and when the total count can be
97913   ** expressed as a 32-bit integer. */
97914   assert( argc==1 || p==0 || p->n>0x7fffffff
97915           || p->n==sqlite3_aggregate_count(context) );
97916 #endif
97917 }
97918 static void countFinalize(sqlite3_context *context){
97919   CountCtx *p;
97920   p = sqlite3_aggregate_context(context, 0);
97921   sqlite3_result_int64(context, p ? p->n : 0);
97922 }
97923 
97924 /*
97925 ** Routines to implement min() and max() aggregate functions.
97926 */
97927 static void minmaxStep(
97928   sqlite3_context *context,
97929   int NotUsed,
97930   sqlite3_value **argv
97931 ){
97932   Mem *pArg  = (Mem *)argv[0];
97933   Mem *pBest;
97934   UNUSED_PARAMETER(NotUsed);
97935 
97936   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
97937   if( !pBest ) return;
97938 
97939   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
97940     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
97941   }else if( pBest->flags ){
97942     int max;
97943     int cmp;
97944     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
97945     /* This step function is used for both the min() and max() aggregates,
97946     ** the only difference between the two being that the sense of the
97947     ** comparison is inverted. For the max() aggregate, the
97948     ** sqlite3_user_data() function returns (void *)-1. For min() it
97949     ** returns (void *)db, where db is the sqlite3* database pointer.
97950     ** Therefore the next statement sets variable 'max' to 1 for the max()
97951     ** aggregate, or 0 for min().
97952     */
97953     max = sqlite3_user_data(context)!=0;
97954     cmp = sqlite3MemCompare(pBest, pArg, pColl);
97955     if( (max && cmp<0) || (!max && cmp>0) ){
97956       sqlite3VdbeMemCopy(pBest, pArg);
97957     }else{
97958       sqlite3SkipAccumulatorLoad(context);
97959     }
97960   }else{
97961     pBest->db = sqlite3_context_db_handle(context);
97962     sqlite3VdbeMemCopy(pBest, pArg);
97963   }
97964 }
97965 static void minMaxFinalize(sqlite3_context *context){
97966   sqlite3_value *pRes;
97967   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
97968   if( pRes ){
97969     if( pRes->flags ){
97970       sqlite3_result_value(context, pRes);
97971     }
97972     sqlite3VdbeMemRelease(pRes);
97973   }
97974 }
97975 
97976 /*
97977 ** group_concat(EXPR, ?SEPARATOR?)
97978 */
97979 static void groupConcatStep(
97980   sqlite3_context *context,
97981   int argc,
97982   sqlite3_value **argv
97983 ){
97984   const char *zVal;
97985   StrAccum *pAccum;
97986   const char *zSep;
97987   int nVal, nSep;
97988   assert( argc==1 || argc==2 );
97989   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
97990   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
97991 
97992   if( pAccum ){
97993     sqlite3 *db = sqlite3_context_db_handle(context);
97994     int firstTerm = pAccum->mxAlloc==0;
97995     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
97996     if( !firstTerm ){
97997       if( argc==2 ){
97998         zSep = (char*)sqlite3_value_text(argv[1]);
97999         nSep = sqlite3_value_bytes(argv[1]);
98000       }else{
98001         zSep = ",";
98002         nSep = 1;
98003       }
98004       if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
98005     }
98006     zVal = (char*)sqlite3_value_text(argv[0]);
98007     nVal = sqlite3_value_bytes(argv[0]);
98008     if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
98009   }
98010 }
98011 static void groupConcatFinalize(sqlite3_context *context){
98012   StrAccum *pAccum;
98013   pAccum = sqlite3_aggregate_context(context, 0);
98014   if( pAccum ){
98015     if( pAccum->accError==STRACCUM_TOOBIG ){
98016       sqlite3_result_error_toobig(context);
98017     }else if( pAccum->accError==STRACCUM_NOMEM ){
98018       sqlite3_result_error_nomem(context);
98019     }else{
98020       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
98021                           sqlite3_free);
98022     }
98023   }
98024 }
98025 
98026 /*
98027 ** This routine does per-connection function registration.  Most
98028 ** of the built-in functions above are part of the global function set.
98029 ** This routine only deals with those that are not global.
98030 */
98031 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
98032   int rc = sqlite3_overload_function(db, "MATCH", 2);
98033   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
98034   if( rc==SQLITE_NOMEM ){
98035     db->mallocFailed = 1;
98036   }
98037 }
98038 
98039 /*
98040 ** Set the LIKEOPT flag on the 2-argument function with the given name.
98041 */
98042 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
98043   FuncDef *pDef;
98044   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
98045                              2, SQLITE_UTF8, 0);
98046   if( ALWAYS(pDef) ){
98047     pDef->funcFlags |= flagVal;
98048   }
98049 }
98050 
98051 /*
98052 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
98053 ** parameter determines whether or not the LIKE operator is case
98054 ** sensitive.  GLOB is always case sensitive.
98055 */
98056 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
98057   struct compareInfo *pInfo;
98058   if( caseSensitive ){
98059     pInfo = (struct compareInfo*)&likeInfoAlt;
98060   }else{
98061     pInfo = (struct compareInfo*)&likeInfoNorm;
98062   }
98063   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
98064   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
98065   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
98066       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
98067   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
98068   setLikeOptFlag(db, "like",
98069       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
98070 }
98071 
98072 /*
98073 ** pExpr points to an expression which implements a function.  If
98074 ** it is appropriate to apply the LIKE optimization to that function
98075 ** then set aWc[0] through aWc[2] to the wildcard characters and
98076 ** return TRUE.  If the function is not a LIKE-style function then
98077 ** return FALSE.
98078 **
98079 ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
98080 ** the function (default for LIKE).  If the function makes the distinction
98081 ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
98082 ** false.
98083 */
98084 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
98085   FuncDef *pDef;
98086   if( pExpr->op!=TK_FUNCTION
98087    || !pExpr->x.pList
98088    || pExpr->x.pList->nExpr!=2
98089   ){
98090     return 0;
98091   }
98092   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
98093   pDef = sqlite3FindFunction(db, pExpr->u.zToken,
98094                              sqlite3Strlen30(pExpr->u.zToken),
98095                              2, SQLITE_UTF8, 0);
98096   if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
98097     return 0;
98098   }
98099 
98100   /* The memcpy() statement assumes that the wildcard characters are
98101   ** the first three statements in the compareInfo structure.  The
98102   ** asserts() that follow verify that assumption
98103   */
98104   memcpy(aWc, pDef->pUserData, 3);
98105   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
98106   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
98107   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
98108   *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
98109   return 1;
98110 }
98111 
98112 /*
98113 ** All of the FuncDef structures in the aBuiltinFunc[] array above
98114 ** to the global function hash table.  This occurs at start-time (as
98115 ** a consequence of calling sqlite3_initialize()).
98116 **
98117 ** After this routine runs
98118 */
98119 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
98120   /*
98121   ** The following array holds FuncDef structures for all of the functions
98122   ** defined in this file.
98123   **
98124   ** The array cannot be constant since changes are made to the
98125   ** FuncDef.pHash elements at start-time.  The elements of this array
98126   ** are read-only after initialization is complete.
98127   */
98128   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
98129     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
98130     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
98131     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
98132     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
98133     FUNCTION(trim,               1, 3, 0, trimFunc         ),
98134     FUNCTION(trim,               2, 3, 0, trimFunc         ),
98135     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
98136     FUNCTION(min,                0, 0, 1, 0                ),
98137     AGGREGATE2(min,              1, 0, 1, minmaxStep,      minMaxFinalize,
98138                                           SQLITE_FUNC_MINMAX ),
98139     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
98140     FUNCTION(max,                0, 1, 1, 0                ),
98141     AGGREGATE2(max,              1, 1, 1, minmaxStep,      minMaxFinalize,
98142                                           SQLITE_FUNC_MINMAX ),
98143     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
98144     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
98145     FUNCTION(instr,              2, 0, 0, instrFunc        ),
98146     FUNCTION(substr,             2, 0, 0, substrFunc       ),
98147     FUNCTION(substr,             3, 0, 0, substrFunc       ),
98148     FUNCTION(printf,            -1, 0, 0, printfFunc       ),
98149     FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
98150     FUNCTION(char,              -1, 0, 0, charFunc         ),
98151     FUNCTION(abs,                1, 0, 0, absFunc          ),
98152 #ifndef SQLITE_OMIT_FLOATING_POINT
98153     FUNCTION(round,              1, 0, 0, roundFunc        ),
98154     FUNCTION(round,              2, 0, 0, roundFunc        ),
98155 #endif
98156     FUNCTION(upper,              1, 0, 0, upperFunc        ),
98157     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
98158     FUNCTION(coalesce,           1, 0, 0, 0                ),
98159     FUNCTION(coalesce,           0, 0, 0, 0                ),
98160     FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
98161     FUNCTION(hex,                1, 0, 0, hexFunc          ),
98162     FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
98163     FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
98164     FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
98165     FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
98166     VFUNCTION(random,            0, 0, 0, randomFunc       ),
98167     VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
98168     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
98169     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
98170     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
98171     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
98172 #if SQLITE_USER_AUTHENTICATION
98173     FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
98174 #endif
98175 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
98176     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
98177     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
98178 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
98179     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
98180     VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
98181     VFUNCTION(changes,           0, 0, 0, changes          ),
98182     VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
98183     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
98184     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
98185   #ifdef SQLITE_SOUNDEX
98186     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
98187   #endif
98188   #ifndef SQLITE_OMIT_LOAD_EXTENSION
98189     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
98190     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
98191   #endif
98192     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
98193     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
98194     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
98195     AGGREGATE2(count,            0, 0, 0, countStep,       countFinalize,
98196                SQLITE_FUNC_COUNT  ),
98197     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
98198     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
98199     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
98200 
98201     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
98202   #ifdef SQLITE_CASE_SENSITIVE_LIKE
98203     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
98204     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
98205   #else
98206     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
98207     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
98208   #endif
98209   };
98210 
98211   int i;
98212   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
98213   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
98214 
98215   for(i=0; i<ArraySize(aBuiltinFunc); i++){
98216     sqlite3FuncDefInsert(pHash, &aFunc[i]);
98217   }
98218   sqlite3RegisterDateTimeFunctions();
98219 #ifndef SQLITE_OMIT_ALTERTABLE
98220   sqlite3AlterFunctions();
98221 #endif
98222 #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
98223   sqlite3AnalyzeFunctions();
98224 #endif
98225 }
98226 
98227 /************** End of func.c ************************************************/
98228 /************** Begin file fkey.c ********************************************/
98229 /*
98230 **
98231 ** The author disclaims copyright to this source code.  In place of
98232 ** a legal notice, here is a blessing:
98233 **
98234 **    May you do good and not evil.
98235 **    May you find forgiveness for yourself and forgive others.
98236 **    May you share freely, never taking more than you give.
98237 **
98238 *************************************************************************
98239 ** This file contains code used by the compiler to add foreign key
98240 ** support to compiled SQL statements.
98241 */
98242 
98243 #ifndef SQLITE_OMIT_FOREIGN_KEY
98244 #ifndef SQLITE_OMIT_TRIGGER
98245 
98246 /*
98247 ** Deferred and Immediate FKs
98248 ** --------------------------
98249 **
98250 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
98251 ** If an immediate foreign key constraint is violated,
98252 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
98253 ** statement transaction rolled back. If a
98254 ** deferred foreign key constraint is violated, no action is taken
98255 ** immediately. However if the application attempts to commit the
98256 ** transaction before fixing the constraint violation, the attempt fails.
98257 **
98258 ** Deferred constraints are implemented using a simple counter associated
98259 ** with the database handle. The counter is set to zero each time a
98260 ** database transaction is opened. Each time a statement is executed
98261 ** that causes a foreign key violation, the counter is incremented. Each
98262 ** time a statement is executed that removes an existing violation from
98263 ** the database, the counter is decremented. When the transaction is
98264 ** committed, the commit fails if the current value of the counter is
98265 ** greater than zero. This scheme has two big drawbacks:
98266 **
98267 **   * When a commit fails due to a deferred foreign key constraint,
98268 **     there is no way to tell which foreign constraint is not satisfied,
98269 **     or which row it is not satisfied for.
98270 **
98271 **   * If the database contains foreign key violations when the
98272 **     transaction is opened, this may cause the mechanism to malfunction.
98273 **
98274 ** Despite these problems, this approach is adopted as it seems simpler
98275 ** than the alternatives.
98276 **
98277 ** INSERT operations:
98278 **
98279 **   I.1) For each FK for which the table is the child table, search
98280 **        the parent table for a match. If none is found increment the
98281 **        constraint counter.
98282 **
98283 **   I.2) For each FK for which the table is the parent table,
98284 **        search the child table for rows that correspond to the new
98285 **        row in the parent table. Decrement the counter for each row
98286 **        found (as the constraint is now satisfied).
98287 **
98288 ** DELETE operations:
98289 **
98290 **   D.1) For each FK for which the table is the child table,
98291 **        search the parent table for a row that corresponds to the
98292 **        deleted row in the child table. If such a row is not found,
98293 **        decrement the counter.
98294 **
98295 **   D.2) For each FK for which the table is the parent table, search
98296 **        the child table for rows that correspond to the deleted row
98297 **        in the parent table. For each found increment the counter.
98298 **
98299 ** UPDATE operations:
98300 **
98301 **   An UPDATE command requires that all 4 steps above are taken, but only
98302 **   for FK constraints for which the affected columns are actually
98303 **   modified (values must be compared at runtime).
98304 **
98305 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
98306 ** This simplifies the implementation a bit.
98307 **
98308 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
98309 ** resolution is considered to delete rows before the new row is inserted.
98310 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
98311 ** is thrown, even if the FK constraint would be satisfied after the new
98312 ** row is inserted.
98313 **
98314 ** Immediate constraints are usually handled similarly. The only difference
98315 ** is that the counter used is stored as part of each individual statement
98316 ** object (struct Vdbe). If, after the statement has run, its immediate
98317 ** constraint counter is greater than zero,
98318 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
98319 ** and the statement transaction is rolled back. An exception is an INSERT
98320 ** statement that inserts a single row only (no triggers). In this case,
98321 ** instead of using a counter, an exception is thrown immediately if the
98322 ** INSERT violates a foreign key constraint. This is necessary as such
98323 ** an INSERT does not open a statement transaction.
98324 **
98325 ** TODO: How should dropping a table be handled? How should renaming a
98326 ** table be handled?
98327 **
98328 **
98329 ** Query API Notes
98330 ** ---------------
98331 **
98332 ** Before coding an UPDATE or DELETE row operation, the code-generator
98333 ** for those two operations needs to know whether or not the operation
98334 ** requires any FK processing and, if so, which columns of the original
98335 ** row are required by the FK processing VDBE code (i.e. if FKs were
98336 ** implemented using triggers, which of the old.* columns would be
98337 ** accessed). No information is required by the code-generator before
98338 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
98339 ** generation code to query for this information are:
98340 **
98341 **   sqlite3FkRequired() - Test to see if FK processing is required.
98342 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
98343 **
98344 **
98345 ** Externally accessible module functions
98346 ** --------------------------------------
98347 **
98348 **   sqlite3FkCheck()    - Check for foreign key violations.
98349 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
98350 **   sqlite3FkDelete()   - Delete an FKey structure.
98351 */
98352 
98353 /*
98354 ** VDBE Calling Convention
98355 ** -----------------------
98356 **
98357 ** Example:
98358 **
98359 **   For the following INSERT statement:
98360 **
98361 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
98362 **     INSERT INTO t1 VALUES(1, 2, 3.1);
98363 **
98364 **   Register (x):        2    (type integer)
98365 **   Register (x+1):      1    (type integer)
98366 **   Register (x+2):      NULL (type NULL)
98367 **   Register (x+3):      3.1  (type real)
98368 */
98369 
98370 /*
98371 ** A foreign key constraint requires that the key columns in the parent
98372 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
98373 ** Given that pParent is the parent table for foreign key constraint pFKey,
98374 ** search the schema for a unique index on the parent key columns.
98375 **
98376 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
98377 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
98378 ** is set to point to the unique index.
98379 **
98380 ** If the parent key consists of a single column (the foreign key constraint
98381 ** is not a composite foreign key), output variable *paiCol is set to NULL.
98382 ** Otherwise, it is set to point to an allocated array of size N, where
98383 ** N is the number of columns in the parent key. The first element of the
98384 ** array is the index of the child table column that is mapped by the FK
98385 ** constraint to the parent table column stored in the left-most column
98386 ** of index *ppIdx. The second element of the array is the index of the
98387 ** child table column that corresponds to the second left-most column of
98388 ** *ppIdx, and so on.
98389 **
98390 ** If the required index cannot be found, either because:
98391 **
98392 **   1) The named parent key columns do not exist, or
98393 **
98394 **   2) The named parent key columns do exist, but are not subject to a
98395 **      UNIQUE or PRIMARY KEY constraint, or
98396 **
98397 **   3) No parent key columns were provided explicitly as part of the
98398 **      foreign key definition, and the parent table does not have a
98399 **      PRIMARY KEY, or
98400 **
98401 **   4) No parent key columns were provided explicitly as part of the
98402 **      foreign key definition, and the PRIMARY KEY of the parent table
98403 **      consists of a different number of columns to the child key in
98404 **      the child table.
98405 **
98406 ** then non-zero is returned, and a "foreign key mismatch" error loaded
98407 ** into pParse. If an OOM error occurs, non-zero is returned and the
98408 ** pParse->db->mallocFailed flag is set.
98409 */
98410 SQLITE_PRIVATE int sqlite3FkLocateIndex(
98411   Parse *pParse,                  /* Parse context to store any error in */
98412   Table *pParent,                 /* Parent table of FK constraint pFKey */
98413   FKey *pFKey,                    /* Foreign key to find index for */
98414   Index **ppIdx,                  /* OUT: Unique index on parent table */
98415   int **paiCol                    /* OUT: Map of index columns in pFKey */
98416 ){
98417   Index *pIdx = 0;                    /* Value to return via *ppIdx */
98418   int *aiCol = 0;                     /* Value to return via *paiCol */
98419   int nCol = pFKey->nCol;             /* Number of columns in parent key */
98420   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
98421 
98422   /* The caller is responsible for zeroing output parameters. */
98423   assert( ppIdx && *ppIdx==0 );
98424   assert( !paiCol || *paiCol==0 );
98425   assert( pParse );
98426 
98427   /* If this is a non-composite (single column) foreign key, check if it
98428   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
98429   ** and *paiCol set to zero and return early.
98430   **
98431   ** Otherwise, for a composite foreign key (more than one column), allocate
98432   ** space for the aiCol array (returned via output parameter *paiCol).
98433   ** Non-composite foreign keys do not require the aiCol array.
98434   */
98435   if( nCol==1 ){
98436     /* The FK maps to the IPK if any of the following are true:
98437     **
98438     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
98439     **      mapped to the primary key of table pParent, or
98440     **   2) The FK is explicitly mapped to a column declared as INTEGER
98441     **      PRIMARY KEY.
98442     */
98443     if( pParent->iPKey>=0 ){
98444       if( !zKey ) return 0;
98445       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
98446     }
98447   }else if( paiCol ){
98448     assert( nCol>1 );
98449     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
98450     if( !aiCol ) return 1;
98451     *paiCol = aiCol;
98452   }
98453 
98454   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
98455     if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
98456       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
98457       ** of columns. If each indexed column corresponds to a foreign key
98458       ** column of pFKey, then this index is a winner.  */
98459 
98460       if( zKey==0 ){
98461         /* If zKey is NULL, then this foreign key is implicitly mapped to
98462         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
98463         ** identified by the test.  */
98464         if( IsPrimaryKeyIndex(pIdx) ){
98465           if( aiCol ){
98466             int i;
98467             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
98468           }
98469           break;
98470         }
98471       }else{
98472         /* If zKey is non-NULL, then this foreign key was declared to
98473         ** map to an explicit list of columns in table pParent. Check if this
98474         ** index matches those columns. Also, check that the index uses
98475         ** the default collation sequences for each column. */
98476         int i, j;
98477         for(i=0; i<nCol; i++){
98478           i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
98479           char *zDfltColl;                  /* Def. collation for column */
98480           char *zIdxCol;                    /* Name of indexed column */
98481 
98482           /* If the index uses a collation sequence that is different from
98483           ** the default collation sequence for the column, this index is
98484           ** unusable. Bail out early in this case.  */
98485           zDfltColl = pParent->aCol[iCol].zColl;
98486           if( !zDfltColl ){
98487             zDfltColl = "BINARY";
98488           }
98489           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
98490 
98491           zIdxCol = pParent->aCol[iCol].zName;
98492           for(j=0; j<nCol; j++){
98493             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
98494               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
98495               break;
98496             }
98497           }
98498           if( j==nCol ) break;
98499         }
98500         if( i==nCol ) break;      /* pIdx is usable */
98501       }
98502     }
98503   }
98504 
98505   if( !pIdx ){
98506     if( !pParse->disableTriggers ){
98507       sqlite3ErrorMsg(pParse,
98508            "foreign key mismatch - \"%w\" referencing \"%w\"",
98509            pFKey->pFrom->zName, pFKey->zTo);
98510     }
98511     sqlite3DbFree(pParse->db, aiCol);
98512     return 1;
98513   }
98514 
98515   *ppIdx = pIdx;
98516   return 0;
98517 }
98518 
98519 /*
98520 ** This function is called when a row is inserted into or deleted from the
98521 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
98522 ** on the child table of pFKey, this function is invoked twice for each row
98523 ** affected - once to "delete" the old row, and then again to "insert" the
98524 ** new row.
98525 **
98526 ** Each time it is called, this function generates VDBE code to locate the
98527 ** row in the parent table that corresponds to the row being inserted into
98528 ** or deleted from the child table. If the parent row can be found, no
98529 ** special action is taken. Otherwise, if the parent row can *not* be
98530 ** found in the parent table:
98531 **
98532 **   Operation | FK type   | Action taken
98533 **   --------------------------------------------------------------------------
98534 **   INSERT      immediate   Increment the "immediate constraint counter".
98535 **
98536 **   DELETE      immediate   Decrement the "immediate constraint counter".
98537 **
98538 **   INSERT      deferred    Increment the "deferred constraint counter".
98539 **
98540 **   DELETE      deferred    Decrement the "deferred constraint counter".
98541 **
98542 ** These operations are identified in the comment at the top of this file
98543 ** (fkey.c) as "I.1" and "D.1".
98544 */
98545 static void fkLookupParent(
98546   Parse *pParse,        /* Parse context */
98547   int iDb,              /* Index of database housing pTab */
98548   Table *pTab,          /* Parent table of FK pFKey */
98549   Index *pIdx,          /* Unique index on parent key columns in pTab */
98550   FKey *pFKey,          /* Foreign key constraint */
98551   int *aiCol,           /* Map from parent key columns to child table columns */
98552   int regData,          /* Address of array containing child table row */
98553   int nIncr,            /* Increment constraint counter by this */
98554   int isIgnore          /* If true, pretend pTab contains all NULL values */
98555 ){
98556   int i;                                    /* Iterator variable */
98557   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
98558   int iCur = pParse->nTab - 1;              /* Cursor number to use */
98559   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
98560 
98561   /* If nIncr is less than zero, then check at runtime if there are any
98562   ** outstanding constraints to resolve. If there are not, there is no need
98563   ** to check if deleting this row resolves any outstanding violations.
98564   **
98565   ** Check if any of the key columns in the child table row are NULL. If
98566   ** any are, then the constraint is considered satisfied. No need to
98567   ** search for a matching row in the parent table.  */
98568   if( nIncr<0 ){
98569     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
98570     VdbeCoverage(v);
98571   }
98572   for(i=0; i<pFKey->nCol; i++){
98573     int iReg = aiCol[i] + regData + 1;
98574     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
98575   }
98576 
98577   if( isIgnore==0 ){
98578     if( pIdx==0 ){
98579       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
98580       ** column of the parent table (table pTab).  */
98581       int iMustBeInt;               /* Address of MustBeInt instruction */
98582       int regTemp = sqlite3GetTempReg(pParse);
98583 
98584       /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
98585       ** apply the affinity of the parent key). If this fails, then there
98586       ** is no matching parent key. Before using MustBeInt, make a copy of
98587       ** the value. Otherwise, the value inserted into the child key column
98588       ** will have INTEGER affinity applied to it, which may not be correct.  */
98589       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
98590       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
98591       VdbeCoverage(v);
98592 
98593       /* If the parent table is the same as the child table, and we are about
98594       ** to increment the constraint-counter (i.e. this is an INSERT operation),
98595       ** then check if the row being inserted matches itself. If so, do not
98596       ** increment the constraint-counter.  */
98597       if( pTab==pFKey->pFrom && nIncr==1 ){
98598         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
98599         sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
98600       }
98601 
98602       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
98603       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
98604       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
98605       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
98606       sqlite3VdbeJumpHere(v, iMustBeInt);
98607       sqlite3ReleaseTempReg(pParse, regTemp);
98608     }else{
98609       int nCol = pFKey->nCol;
98610       int regTemp = sqlite3GetTempRange(pParse, nCol);
98611       int regRec = sqlite3GetTempReg(pParse);
98612 
98613       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
98614       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
98615       for(i=0; i<nCol; i++){
98616         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
98617       }
98618 
98619       /* If the parent table is the same as the child table, and we are about
98620       ** to increment the constraint-counter (i.e. this is an INSERT operation),
98621       ** then check if the row being inserted matches itself. If so, do not
98622       ** increment the constraint-counter.
98623       **
98624       ** If any of the parent-key values are NULL, then the row cannot match
98625       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
98626       ** of the parent-key values are NULL (at this point it is known that
98627       ** none of the child key values are).
98628       */
98629       if( pTab==pFKey->pFrom && nIncr==1 ){
98630         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
98631         for(i=0; i<nCol; i++){
98632           int iChild = aiCol[i]+1+regData;
98633           int iParent = pIdx->aiColumn[i]+1+regData;
98634           assert( aiCol[i]!=pTab->iPKey );
98635           if( pIdx->aiColumn[i]==pTab->iPKey ){
98636             /* The parent key is a composite key that includes the IPK column */
98637             iParent = regData;
98638           }
98639           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
98640           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
98641         }
98642         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
98643       }
98644 
98645       sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
98646                         sqlite3IndexAffinityStr(v,pIdx), nCol);
98647       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
98648 
98649       sqlite3ReleaseTempReg(pParse, regRec);
98650       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
98651     }
98652   }
98653 
98654   if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
98655    && !pParse->pToplevel
98656    && !pParse->isMultiWrite
98657   ){
98658     /* Special case: If this is an INSERT statement that will insert exactly
98659     ** one row into the table, raise a constraint immediately instead of
98660     ** incrementing a counter. This is necessary as the VM code is being
98661     ** generated for will not open a statement transaction.  */
98662     assert( nIncr==1 );
98663     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
98664         OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
98665   }else{
98666     if( nIncr>0 && pFKey->isDeferred==0 ){
98667       sqlite3MayAbort(pParse);
98668     }
98669     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
98670   }
98671 
98672   sqlite3VdbeResolveLabel(v, iOk);
98673   sqlite3VdbeAddOp1(v, OP_Close, iCur);
98674 }
98675 
98676 
98677 /*
98678 ** Return an Expr object that refers to a memory register corresponding
98679 ** to column iCol of table pTab.
98680 **
98681 ** regBase is the first of an array of register that contains the data
98682 ** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
98683 ** column.  regBase+2 holds the second column, and so forth.
98684 */
98685 static Expr *exprTableRegister(
98686   Parse *pParse,     /* Parsing and code generating context */
98687   Table *pTab,       /* The table whose content is at r[regBase]... */
98688   int regBase,       /* Contents of table pTab */
98689   i16 iCol           /* Which column of pTab is desired */
98690 ){
98691   Expr *pExpr;
98692   Column *pCol;
98693   const char *zColl;
98694   sqlite3 *db = pParse->db;
98695 
98696   pExpr = sqlite3Expr(db, TK_REGISTER, 0);
98697   if( pExpr ){
98698     if( iCol>=0 && iCol!=pTab->iPKey ){
98699       pCol = &pTab->aCol[iCol];
98700       pExpr->iTable = regBase + iCol + 1;
98701       pExpr->affinity = pCol->affinity;
98702       zColl = pCol->zColl;
98703       if( zColl==0 ) zColl = db->pDfltColl->zName;
98704       pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
98705     }else{
98706       pExpr->iTable = regBase;
98707       pExpr->affinity = SQLITE_AFF_INTEGER;
98708     }
98709   }
98710   return pExpr;
98711 }
98712 
98713 /*
98714 ** Return an Expr object that refers to column iCol of table pTab which
98715 ** has cursor iCur.
98716 */
98717 static Expr *exprTableColumn(
98718   sqlite3 *db,      /* The database connection */
98719   Table *pTab,      /* The table whose column is desired */
98720   int iCursor,      /* The open cursor on the table */
98721   i16 iCol          /* The column that is wanted */
98722 ){
98723   Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
98724   if( pExpr ){
98725     pExpr->pTab = pTab;
98726     pExpr->iTable = iCursor;
98727     pExpr->iColumn = iCol;
98728   }
98729   return pExpr;
98730 }
98731 
98732 /*
98733 ** This function is called to generate code executed when a row is deleted
98734 ** from the parent table of foreign key constraint pFKey and, if pFKey is
98735 ** deferred, when a row is inserted into the same table. When generating
98736 ** code for an SQL UPDATE operation, this function may be called twice -
98737 ** once to "delete" the old row and once to "insert" the new row.
98738 **
98739 ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
98740 ** the number of FK violations in the db) or +1 when deleting one (as this
98741 ** may increase the number of FK constraint problems).
98742 **
98743 ** The code generated by this function scans through the rows in the child
98744 ** table that correspond to the parent table row being deleted or inserted.
98745 ** For each child row found, one of the following actions is taken:
98746 **
98747 **   Operation | FK type   | Action taken
98748 **   --------------------------------------------------------------------------
98749 **   DELETE      immediate   Increment the "immediate constraint counter".
98750 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
98751 **                           throw a "FOREIGN KEY constraint failed" exception.
98752 **
98753 **   INSERT      immediate   Decrement the "immediate constraint counter".
98754 **
98755 **   DELETE      deferred    Increment the "deferred constraint counter".
98756 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
98757 **                           throw a "FOREIGN KEY constraint failed" exception.
98758 **
98759 **   INSERT      deferred    Decrement the "deferred constraint counter".
98760 **
98761 ** These operations are identified in the comment at the top of this file
98762 ** (fkey.c) as "I.2" and "D.2".
98763 */
98764 static void fkScanChildren(
98765   Parse *pParse,                  /* Parse context */
98766   SrcList *pSrc,                  /* The child table to be scanned */
98767   Table *pTab,                    /* The parent table */
98768   Index *pIdx,                    /* Index on parent covering the foreign key */
98769   FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
98770   int *aiCol,                     /* Map from pIdx cols to child table cols */
98771   int regData,                    /* Parent row data starts here */
98772   int nIncr                       /* Amount to increment deferred counter by */
98773 ){
98774   sqlite3 *db = pParse->db;       /* Database handle */
98775   int i;                          /* Iterator variable */
98776   Expr *pWhere = 0;               /* WHERE clause to scan with */
98777   NameContext sNameContext;       /* Context used to resolve WHERE clause */
98778   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
98779   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
98780   Vdbe *v = sqlite3GetVdbe(pParse);
98781 
98782   assert( pIdx==0 || pIdx->pTable==pTab );
98783   assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
98784   assert( pIdx!=0 || pFKey->nCol==1 );
98785   assert( pIdx!=0 || HasRowid(pTab) );
98786 
98787   if( nIncr<0 ){
98788     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
98789     VdbeCoverage(v);
98790   }
98791 
98792   /* Create an Expr object representing an SQL expression like:
98793   **
98794   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
98795   **
98796   ** The collation sequence used for the comparison should be that of
98797   ** the parent key columns. The affinity of the parent key column should
98798   ** be applied to each child key value before the comparison takes place.
98799   */
98800   for(i=0; i<pFKey->nCol; i++){
98801     Expr *pLeft;                  /* Value from parent table row */
98802     Expr *pRight;                 /* Column ref to child table */
98803     Expr *pEq;                    /* Expression (pLeft = pRight) */
98804     i16 iCol;                     /* Index of column in child table */
98805     const char *zCol;             /* Name of column in child table */
98806 
98807     iCol = pIdx ? pIdx->aiColumn[i] : -1;
98808     pLeft = exprTableRegister(pParse, pTab, regData, iCol);
98809     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
98810     assert( iCol>=0 );
98811     zCol = pFKey->pFrom->aCol[iCol].zName;
98812     pRight = sqlite3Expr(db, TK_ID, zCol);
98813     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
98814     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
98815   }
98816 
98817   /* If the child table is the same as the parent table, then add terms
98818   ** to the WHERE clause that prevent this entry from being scanned.
98819   ** The added WHERE clause terms are like this:
98820   **
98821   **     $current_rowid!=rowid
98822   **     NOT( $current_a==a AND $current_b==b AND ... )
98823   **
98824   ** The first form is used for rowid tables.  The second form is used
98825   ** for WITHOUT ROWID tables.  In the second form, the primary key is
98826   ** (a,b,...)
98827   */
98828   if( pTab==pFKey->pFrom && nIncr>0 ){
98829     Expr *pNe;                    /* Expression (pLeft != pRight) */
98830     Expr *pLeft;                  /* Value from parent table row */
98831     Expr *pRight;                 /* Column ref to child table */
98832     if( HasRowid(pTab) ){
98833       pLeft = exprTableRegister(pParse, pTab, regData, -1);
98834       pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
98835       pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
98836     }else{
98837       Expr *pEq, *pAll = 0;
98838       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
98839       assert( pIdx!=0 );
98840       for(i=0; i<pPk->nKeyCol; i++){
98841         i16 iCol = pIdx->aiColumn[i];
98842         pLeft = exprTableRegister(pParse, pTab, regData, iCol);
98843         pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
98844         pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
98845         pAll = sqlite3ExprAnd(db, pAll, pEq);
98846       }
98847       pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
98848     }
98849     pWhere = sqlite3ExprAnd(db, pWhere, pNe);
98850   }
98851 
98852   /* Resolve the references in the WHERE clause. */
98853   memset(&sNameContext, 0, sizeof(NameContext));
98854   sNameContext.pSrcList = pSrc;
98855   sNameContext.pParse = pParse;
98856   sqlite3ResolveExprNames(&sNameContext, pWhere);
98857 
98858   /* Create VDBE to loop through the entries in pSrc that match the WHERE
98859   ** clause. For each row found, increment either the deferred or immediate
98860   ** foreign key constraint counter. */
98861   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
98862   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
98863   if( pWInfo ){
98864     sqlite3WhereEnd(pWInfo);
98865   }
98866 
98867   /* Clean up the WHERE clause constructed above. */
98868   sqlite3ExprDelete(db, pWhere);
98869   if( iFkIfZero ){
98870     sqlite3VdbeJumpHere(v, iFkIfZero);
98871   }
98872 }
98873 
98874 /*
98875 ** This function returns a linked list of FKey objects (connected by
98876 ** FKey.pNextTo) holding all children of table pTab.  For example,
98877 ** given the following schema:
98878 **
98879 **   CREATE TABLE t1(a PRIMARY KEY);
98880 **   CREATE TABLE t2(b REFERENCES t1(a);
98881 **
98882 ** Calling this function with table "t1" as an argument returns a pointer
98883 ** to the FKey structure representing the foreign key constraint on table
98884 ** "t2". Calling this function with "t2" as the argument would return a
98885 ** NULL pointer (as there are no FK constraints for which t2 is the parent
98886 ** table).
98887 */
98888 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
98889   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
98890 }
98891 
98892 /*
98893 ** The second argument is a Trigger structure allocated by the
98894 ** fkActionTrigger() routine. This function deletes the Trigger structure
98895 ** and all of its sub-components.
98896 **
98897 ** The Trigger structure or any of its sub-components may be allocated from
98898 ** the lookaside buffer belonging to database handle dbMem.
98899 */
98900 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
98901   if( p ){
98902     TriggerStep *pStep = p->step_list;
98903     sqlite3ExprDelete(dbMem, pStep->pWhere);
98904     sqlite3ExprListDelete(dbMem, pStep->pExprList);
98905     sqlite3SelectDelete(dbMem, pStep->pSelect);
98906     sqlite3ExprDelete(dbMem, p->pWhen);
98907     sqlite3DbFree(dbMem, p);
98908   }
98909 }
98910 
98911 /*
98912 ** This function is called to generate code that runs when table pTab is
98913 ** being dropped from the database. The SrcList passed as the second argument
98914 ** to this function contains a single entry guaranteed to resolve to
98915 ** table pTab.
98916 **
98917 ** Normally, no code is required. However, if either
98918 **
98919 **   (a) The table is the parent table of a FK constraint, or
98920 **   (b) The table is the child table of a deferred FK constraint and it is
98921 **       determined at runtime that there are outstanding deferred FK
98922 **       constraint violations in the database,
98923 **
98924 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
98925 ** the table from the database. Triggers are disabled while running this
98926 ** DELETE, but foreign key actions are not.
98927 */
98928 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
98929   sqlite3 *db = pParse->db;
98930   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
98931     int iSkip = 0;
98932     Vdbe *v = sqlite3GetVdbe(pParse);
98933 
98934     assert( v );                  /* VDBE has already been allocated */
98935     if( sqlite3FkReferences(pTab)==0 ){
98936       /* Search for a deferred foreign key constraint for which this table
98937       ** is the child table. If one cannot be found, return without
98938       ** generating any VDBE code. If one can be found, then jump over
98939       ** the entire DELETE if there are no outstanding deferred constraints
98940       ** when this statement is run.  */
98941       FKey *p;
98942       for(p=pTab->pFKey; p; p=p->pNextFrom){
98943         if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
98944       }
98945       if( !p ) return;
98946       iSkip = sqlite3VdbeMakeLabel(v);
98947       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
98948     }
98949 
98950     pParse->disableTriggers = 1;
98951     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
98952     pParse->disableTriggers = 0;
98953 
98954     /* If the DELETE has generated immediate foreign key constraint
98955     ** violations, halt the VDBE and return an error at this point, before
98956     ** any modifications to the schema are made. This is because statement
98957     ** transactions are not able to rollback schema changes.
98958     **
98959     ** If the SQLITE_DeferFKs flag is set, then this is not required, as
98960     ** the statement transaction will not be rolled back even if FK
98961     ** constraints are violated.
98962     */
98963     if( (db->flags & SQLITE_DeferFKs)==0 ){
98964       sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
98965       VdbeCoverage(v);
98966       sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
98967           OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
98968     }
98969 
98970     if( iSkip ){
98971       sqlite3VdbeResolveLabel(v, iSkip);
98972     }
98973   }
98974 }
98975 
98976 
98977 /*
98978 ** The second argument points to an FKey object representing a foreign key
98979 ** for which pTab is the child table. An UPDATE statement against pTab
98980 ** is currently being processed. For each column of the table that is
98981 ** actually updated, the corresponding element in the aChange[] array
98982 ** is zero or greater (if a column is unmodified the corresponding element
98983 ** is set to -1). If the rowid column is modified by the UPDATE statement
98984 ** the bChngRowid argument is non-zero.
98985 **
98986 ** This function returns true if any of the columns that are part of the
98987 ** child key for FK constraint *p are modified.
98988 */
98989 static int fkChildIsModified(
98990   Table *pTab,                    /* Table being updated */
98991   FKey *p,                        /* Foreign key for which pTab is the child */
98992   int *aChange,                   /* Array indicating modified columns */
98993   int bChngRowid                  /* True if rowid is modified by this update */
98994 ){
98995   int i;
98996   for(i=0; i<p->nCol; i++){
98997     int iChildKey = p->aCol[i].iFrom;
98998     if( aChange[iChildKey]>=0 ) return 1;
98999     if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
99000   }
99001   return 0;
99002 }
99003 
99004 /*
99005 ** The second argument points to an FKey object representing a foreign key
99006 ** for which pTab is the parent table. An UPDATE statement against pTab
99007 ** is currently being processed. For each column of the table that is
99008 ** actually updated, the corresponding element in the aChange[] array
99009 ** is zero or greater (if a column is unmodified the corresponding element
99010 ** is set to -1). If the rowid column is modified by the UPDATE statement
99011 ** the bChngRowid argument is non-zero.
99012 **
99013 ** This function returns true if any of the columns that are part of the
99014 ** parent key for FK constraint *p are modified.
99015 */
99016 static int fkParentIsModified(
99017   Table *pTab,
99018   FKey *p,
99019   int *aChange,
99020   int bChngRowid
99021 ){
99022   int i;
99023   for(i=0; i<p->nCol; i++){
99024     char *zKey = p->aCol[i].zCol;
99025     int iKey;
99026     for(iKey=0; iKey<pTab->nCol; iKey++){
99027       if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
99028         Column *pCol = &pTab->aCol[iKey];
99029         if( zKey ){
99030           if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
99031         }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
99032           return 1;
99033         }
99034       }
99035     }
99036   }
99037   return 0;
99038 }
99039 
99040 /*
99041 ** Return true if the parser passed as the first argument is being
99042 ** used to code a trigger that is really a "SET NULL" action belonging
99043 ** to trigger pFKey.
99044 */
99045 static int isSetNullAction(Parse *pParse, FKey *pFKey){
99046   Parse *pTop = sqlite3ParseToplevel(pParse);
99047   if( pTop->pTriggerPrg ){
99048     Trigger *p = pTop->pTriggerPrg->pTrigger;
99049     if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
99050      || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
99051     ){
99052       return 1;
99053     }
99054   }
99055   return 0;
99056 }
99057 
99058 /*
99059 ** This function is called when inserting, deleting or updating a row of
99060 ** table pTab to generate VDBE code to perform foreign key constraint
99061 ** processing for the operation.
99062 **
99063 ** For a DELETE operation, parameter regOld is passed the index of the
99064 ** first register in an array of (pTab->nCol+1) registers containing the
99065 ** rowid of the row being deleted, followed by each of the column values
99066 ** of the row being deleted, from left to right. Parameter regNew is passed
99067 ** zero in this case.
99068 **
99069 ** For an INSERT operation, regOld is passed zero and regNew is passed the
99070 ** first register of an array of (pTab->nCol+1) registers containing the new
99071 ** row data.
99072 **
99073 ** For an UPDATE operation, this function is called twice. Once before
99074 ** the original record is deleted from the table using the calling convention
99075 ** described for DELETE. Then again after the original record is deleted
99076 ** but before the new record is inserted using the INSERT convention.
99077 */
99078 SQLITE_PRIVATE void sqlite3FkCheck(
99079   Parse *pParse,                  /* Parse context */
99080   Table *pTab,                    /* Row is being deleted from this table */
99081   int regOld,                     /* Previous row data is stored here */
99082   int regNew,                     /* New row data is stored here */
99083   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
99084   int bChngRowid                  /* True if rowid is UPDATEd */
99085 ){
99086   sqlite3 *db = pParse->db;       /* Database handle */
99087   FKey *pFKey;                    /* Used to iterate through FKs */
99088   int iDb;                        /* Index of database containing pTab */
99089   const char *zDb;                /* Name of database containing pTab */
99090   int isIgnoreErrors = pParse->disableTriggers;
99091 
99092   /* Exactly one of regOld and regNew should be non-zero. */
99093   assert( (regOld==0)!=(regNew==0) );
99094 
99095   /* If foreign-keys are disabled, this function is a no-op. */
99096   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
99097 
99098   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99099   zDb = db->aDb[iDb].zName;
99100 
99101   /* Loop through all the foreign key constraints for which pTab is the
99102   ** child table (the table that the foreign key definition is part of).  */
99103   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
99104     Table *pTo;                   /* Parent table of foreign key pFKey */
99105     Index *pIdx = 0;              /* Index on key columns in pTo */
99106     int *aiFree = 0;
99107     int *aiCol;
99108     int iCol;
99109     int i;
99110     int bIgnore = 0;
99111 
99112     if( aChange
99113      && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
99114      && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
99115     ){
99116       continue;
99117     }
99118 
99119     /* Find the parent table of this foreign key. Also find a unique index
99120     ** on the parent key columns in the parent table. If either of these
99121     ** schema items cannot be located, set an error in pParse and return
99122     ** early.  */
99123     if( pParse->disableTriggers ){
99124       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
99125     }else{
99126       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
99127     }
99128     if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
99129       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
99130       if( !isIgnoreErrors || db->mallocFailed ) return;
99131       if( pTo==0 ){
99132         /* If isIgnoreErrors is true, then a table is being dropped. In this
99133         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
99134         ** before actually dropping it in order to check FK constraints.
99135         ** If the parent table of an FK constraint on the current table is
99136         ** missing, behave as if it is empty. i.e. decrement the relevant
99137         ** FK counter for each row of the current table with non-NULL keys.
99138         */
99139         Vdbe *v = sqlite3GetVdbe(pParse);
99140         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
99141         for(i=0; i<pFKey->nCol; i++){
99142           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
99143           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
99144         }
99145         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
99146       }
99147       continue;
99148     }
99149     assert( pFKey->nCol==1 || (aiFree && pIdx) );
99150 
99151     if( aiFree ){
99152       aiCol = aiFree;
99153     }else{
99154       iCol = pFKey->aCol[0].iFrom;
99155       aiCol = &iCol;
99156     }
99157     for(i=0; i<pFKey->nCol; i++){
99158       if( aiCol[i]==pTab->iPKey ){
99159         aiCol[i] = -1;
99160       }
99161 #ifndef SQLITE_OMIT_AUTHORIZATION
99162       /* Request permission to read the parent key columns. If the
99163       ** authorization callback returns SQLITE_IGNORE, behave as if any
99164       ** values read from the parent table are NULL. */
99165       if( db->xAuth ){
99166         int rcauth;
99167         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
99168         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
99169         bIgnore = (rcauth==SQLITE_IGNORE);
99170       }
99171 #endif
99172     }
99173 
99174     /* Take a shared-cache advisory read-lock on the parent table. Allocate
99175     ** a cursor to use to search the unique index on the parent key columns
99176     ** in the parent table.  */
99177     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
99178     pParse->nTab++;
99179 
99180     if( regOld!=0 ){
99181       /* A row is being removed from the child table. Search for the parent.
99182       ** If the parent does not exist, removing the child row resolves an
99183       ** outstanding foreign key constraint violation. */
99184       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
99185     }
99186     if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
99187       /* A row is being added to the child table. If a parent row cannot
99188       ** be found, adding the child row has violated the FK constraint.
99189       **
99190       ** If this operation is being performed as part of a trigger program
99191       ** that is actually a "SET NULL" action belonging to this very
99192       ** foreign key, then omit this scan altogether. As all child key
99193       ** values are guaranteed to be NULL, it is not possible for adding
99194       ** this row to cause an FK violation.  */
99195       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
99196     }
99197 
99198     sqlite3DbFree(db, aiFree);
99199   }
99200 
99201   /* Loop through all the foreign key constraints that refer to this table.
99202   ** (the "child" constraints) */
99203   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
99204     Index *pIdx = 0;              /* Foreign key index for pFKey */
99205     SrcList *pSrc;
99206     int *aiCol = 0;
99207 
99208     if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
99209       continue;
99210     }
99211 
99212     if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
99213      && !pParse->pToplevel && !pParse->isMultiWrite
99214     ){
99215       assert( regOld==0 && regNew!=0 );
99216       /* Inserting a single row into a parent table cannot cause (or fix)
99217       ** an immediate foreign key violation. So do nothing in this case.  */
99218       continue;
99219     }
99220 
99221     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
99222       if( !isIgnoreErrors || db->mallocFailed ) return;
99223       continue;
99224     }
99225     assert( aiCol || pFKey->nCol==1 );
99226 
99227     /* Create a SrcList structure containing the child table.  We need the
99228     ** child table as a SrcList for sqlite3WhereBegin() */
99229     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
99230     if( pSrc ){
99231       struct SrcList_item *pItem = pSrc->a;
99232       pItem->pTab = pFKey->pFrom;
99233       pItem->zName = pFKey->pFrom->zName;
99234       pItem->pTab->nRef++;
99235       pItem->iCursor = pParse->nTab++;
99236 
99237       if( regNew!=0 ){
99238         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
99239       }
99240       if( regOld!=0 ){
99241         int eAction = pFKey->aAction[aChange!=0];
99242         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
99243         /* If this is a deferred FK constraint, or a CASCADE or SET NULL
99244         ** action applies, then any foreign key violations caused by
99245         ** removing the parent key will be rectified by the action trigger.
99246         ** So do not set the "may-abort" flag in this case.
99247         **
99248         ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
99249         ** may-abort flag will eventually be set on this statement anyway
99250         ** (when this function is called as part of processing the UPDATE
99251         ** within the action trigger).
99252         **
99253         ** Note 2: At first glance it may seem like SQLite could simply omit
99254         ** all OP_FkCounter related scans when either CASCADE or SET NULL
99255         ** applies. The trouble starts if the CASCADE or SET NULL action
99256         ** trigger causes other triggers or action rules attached to the
99257         ** child table to fire. In these cases the fk constraint counters
99258         ** might be set incorrectly if any OP_FkCounter related scans are
99259         ** omitted.  */
99260         if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
99261           sqlite3MayAbort(pParse);
99262         }
99263       }
99264       pItem->zName = 0;
99265       sqlite3SrcListDelete(db, pSrc);
99266     }
99267     sqlite3DbFree(db, aiCol);
99268   }
99269 }
99270 
99271 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
99272 
99273 /*
99274 ** This function is called before generating code to update or delete a
99275 ** row contained in table pTab.
99276 */
99277 SQLITE_PRIVATE u32 sqlite3FkOldmask(
99278   Parse *pParse,                  /* Parse context */
99279   Table *pTab                     /* Table being modified */
99280 ){
99281   u32 mask = 0;
99282   if( pParse->db->flags&SQLITE_ForeignKeys ){
99283     FKey *p;
99284     int i;
99285     for(p=pTab->pFKey; p; p=p->pNextFrom){
99286       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
99287     }
99288     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
99289       Index *pIdx = 0;
99290       sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
99291       if( pIdx ){
99292         for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
99293       }
99294     }
99295   }
99296   return mask;
99297 }
99298 
99299 
99300 /*
99301 ** This function is called before generating code to update or delete a
99302 ** row contained in table pTab. If the operation is a DELETE, then
99303 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
99304 ** to an array of size N, where N is the number of columns in table pTab.
99305 ** If the i'th column is not modified by the UPDATE, then the corresponding
99306 ** entry in the aChange[] array is set to -1. If the column is modified,
99307 ** the value is 0 or greater. Parameter chngRowid is set to true if the
99308 ** UPDATE statement modifies the rowid fields of the table.
99309 **
99310 ** If any foreign key processing will be required, this function returns
99311 ** true. If there is no foreign key related processing, this function
99312 ** returns false.
99313 */
99314 SQLITE_PRIVATE int sqlite3FkRequired(
99315   Parse *pParse,                  /* Parse context */
99316   Table *pTab,                    /* Table being modified */
99317   int *aChange,                   /* Non-NULL for UPDATE operations */
99318   int chngRowid                   /* True for UPDATE that affects rowid */
99319 ){
99320   if( pParse->db->flags&SQLITE_ForeignKeys ){
99321     if( !aChange ){
99322       /* A DELETE operation. Foreign key processing is required if the
99323       ** table in question is either the child or parent table for any
99324       ** foreign key constraint.  */
99325       return (sqlite3FkReferences(pTab) || pTab->pFKey);
99326     }else{
99327       /* This is an UPDATE. Foreign key processing is only required if the
99328       ** operation modifies one or more child or parent key columns. */
99329       FKey *p;
99330 
99331       /* Check if any child key columns are being modified. */
99332       for(p=pTab->pFKey; p; p=p->pNextFrom){
99333         if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
99334       }
99335 
99336       /* Check if any parent key columns are being modified. */
99337       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
99338         if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
99339       }
99340     }
99341   }
99342   return 0;
99343 }
99344 
99345 /*
99346 ** This function is called when an UPDATE or DELETE operation is being
99347 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
99348 ** If the current operation is an UPDATE, then the pChanges parameter is
99349 ** passed a pointer to the list of columns being modified. If it is a
99350 ** DELETE, pChanges is passed a NULL pointer.
99351 **
99352 ** It returns a pointer to a Trigger structure containing a trigger
99353 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
99354 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
99355 ** returned (these actions require no special handling by the triggers
99356 ** sub-system, code for them is created by fkScanChildren()).
99357 **
99358 ** For example, if pFKey is the foreign key and pTab is table "p" in
99359 ** the following schema:
99360 **
99361 **   CREATE TABLE p(pk PRIMARY KEY);
99362 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
99363 **
99364 ** then the returned trigger structure is equivalent to:
99365 **
99366 **   CREATE TRIGGER ... DELETE ON p BEGIN
99367 **     DELETE FROM c WHERE ck = old.pk;
99368 **   END;
99369 **
99370 ** The returned pointer is cached as part of the foreign key object. It
99371 ** is eventually freed along with the rest of the foreign key object by
99372 ** sqlite3FkDelete().
99373 */
99374 static Trigger *fkActionTrigger(
99375   Parse *pParse,                  /* Parse context */
99376   Table *pTab,                    /* Table being updated or deleted from */
99377   FKey *pFKey,                    /* Foreign key to get action for */
99378   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
99379 ){
99380   sqlite3 *db = pParse->db;       /* Database handle */
99381   int action;                     /* One of OE_None, OE_Cascade etc. */
99382   Trigger *pTrigger;              /* Trigger definition to return */
99383   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
99384 
99385   action = pFKey->aAction[iAction];
99386   pTrigger = pFKey->apTrigger[iAction];
99387 
99388   if( action!=OE_None && !pTrigger ){
99389     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
99390     char const *zFrom;            /* Name of child table */
99391     int nFrom;                    /* Length in bytes of zFrom */
99392     Index *pIdx = 0;              /* Parent key index for this FK */
99393     int *aiCol = 0;               /* child table cols -> parent key cols */
99394     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
99395     Expr *pWhere = 0;             /* WHERE clause of trigger step */
99396     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
99397     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
99398     int i;                        /* Iterator variable */
99399     Expr *pWhen = 0;              /* WHEN clause for the trigger */
99400 
99401     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
99402     assert( aiCol || pFKey->nCol==1 );
99403 
99404     for(i=0; i<pFKey->nCol; i++){
99405       Token tOld = { "old", 3 };  /* Literal "old" token */
99406       Token tNew = { "new", 3 };  /* Literal "new" token */
99407       Token tFromCol;             /* Name of column in child table */
99408       Token tToCol;               /* Name of column in parent table */
99409       int iFromCol;               /* Idx of column in child table */
99410       Expr *pEq;                  /* tFromCol = OLD.tToCol */
99411 
99412       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
99413       assert( iFromCol>=0 );
99414       assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
99415       tToCol.z = pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName;
99416       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
99417 
99418       tToCol.n = sqlite3Strlen30(tToCol.z);
99419       tFromCol.n = sqlite3Strlen30(tFromCol.z);
99420 
99421       /* Create the expression "OLD.zToCol = zFromCol". It is important
99422       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
99423       ** that the affinity and collation sequence associated with the
99424       ** parent table are used for the comparison. */
99425       pEq = sqlite3PExpr(pParse, TK_EQ,
99426           sqlite3PExpr(pParse, TK_DOT,
99427             sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
99428             sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
99429           , 0),
99430           sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
99431       , 0);
99432       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
99433 
99434       /* For ON UPDATE, construct the next term of the WHEN clause.
99435       ** The final WHEN clause will be like this:
99436       **
99437       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
99438       */
99439       if( pChanges ){
99440         pEq = sqlite3PExpr(pParse, TK_IS,
99441             sqlite3PExpr(pParse, TK_DOT,
99442               sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
99443               sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
99444               0),
99445             sqlite3PExpr(pParse, TK_DOT,
99446               sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
99447               sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
99448               0),
99449             0);
99450         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
99451       }
99452 
99453       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
99454         Expr *pNew;
99455         if( action==OE_Cascade ){
99456           pNew = sqlite3PExpr(pParse, TK_DOT,
99457             sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
99458             sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
99459           , 0);
99460         }else if( action==OE_SetDflt ){
99461           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
99462           if( pDflt ){
99463             pNew = sqlite3ExprDup(db, pDflt, 0);
99464           }else{
99465             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
99466           }
99467         }else{
99468           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
99469         }
99470         pList = sqlite3ExprListAppend(pParse, pList, pNew);
99471         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
99472       }
99473     }
99474     sqlite3DbFree(db, aiCol);
99475 
99476     zFrom = pFKey->pFrom->zName;
99477     nFrom = sqlite3Strlen30(zFrom);
99478 
99479     if( action==OE_Restrict ){
99480       Token tFrom;
99481       Expr *pRaise;
99482 
99483       tFrom.z = zFrom;
99484       tFrom.n = nFrom;
99485       pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
99486       if( pRaise ){
99487         pRaise->affinity = OE_Abort;
99488       }
99489       pSelect = sqlite3SelectNew(pParse,
99490           sqlite3ExprListAppend(pParse, 0, pRaise),
99491           sqlite3SrcListAppend(db, 0, &tFrom, 0),
99492           pWhere,
99493           0, 0, 0, 0, 0, 0
99494       );
99495       pWhere = 0;
99496     }
99497 
99498     /* Disable lookaside memory allocation */
99499     enableLookaside = db->lookaside.bEnabled;
99500     db->lookaside.bEnabled = 0;
99501 
99502     pTrigger = (Trigger *)sqlite3DbMallocZero(db,
99503         sizeof(Trigger) +         /* struct Trigger */
99504         sizeof(TriggerStep) +     /* Single step in trigger program */
99505         nFrom + 1                 /* Space for pStep->zTarget */
99506     );
99507     if( pTrigger ){
99508       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
99509       pStep->zTarget = (char *)&pStep[1];
99510       memcpy((char *)pStep->zTarget, zFrom, nFrom);
99511 
99512       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
99513       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
99514       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
99515       if( pWhen ){
99516         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
99517         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
99518       }
99519     }
99520 
99521     /* Re-enable the lookaside buffer, if it was disabled earlier. */
99522     db->lookaside.bEnabled = enableLookaside;
99523 
99524     sqlite3ExprDelete(db, pWhere);
99525     sqlite3ExprDelete(db, pWhen);
99526     sqlite3ExprListDelete(db, pList);
99527     sqlite3SelectDelete(db, pSelect);
99528     if( db->mallocFailed==1 ){
99529       fkTriggerDelete(db, pTrigger);
99530       return 0;
99531     }
99532     assert( pStep!=0 );
99533 
99534     switch( action ){
99535       case OE_Restrict:
99536         pStep->op = TK_SELECT;
99537         break;
99538       case OE_Cascade:
99539         if( !pChanges ){
99540           pStep->op = TK_DELETE;
99541           break;
99542         }
99543       default:
99544         pStep->op = TK_UPDATE;
99545     }
99546     pStep->pTrig = pTrigger;
99547     pTrigger->pSchema = pTab->pSchema;
99548     pTrigger->pTabSchema = pTab->pSchema;
99549     pFKey->apTrigger[iAction] = pTrigger;
99550     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
99551   }
99552 
99553   return pTrigger;
99554 }
99555 
99556 /*
99557 ** This function is called when deleting or updating a row to implement
99558 ** any required CASCADE, SET NULL or SET DEFAULT actions.
99559 */
99560 SQLITE_PRIVATE void sqlite3FkActions(
99561   Parse *pParse,                  /* Parse context */
99562   Table *pTab,                    /* Table being updated or deleted from */
99563   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
99564   int regOld,                     /* Address of array containing old row */
99565   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
99566   int bChngRowid                  /* True if rowid is UPDATEd */
99567 ){
99568   /* If foreign-key support is enabled, iterate through all FKs that
99569   ** refer to table pTab. If there is an action associated with the FK
99570   ** for this operation (either update or delete), invoke the associated
99571   ** trigger sub-program.  */
99572   if( pParse->db->flags&SQLITE_ForeignKeys ){
99573     FKey *pFKey;                  /* Iterator variable */
99574     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
99575       if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
99576         Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
99577         if( pAct ){
99578           sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
99579         }
99580       }
99581     }
99582   }
99583 }
99584 
99585 #endif /* ifndef SQLITE_OMIT_TRIGGER */
99586 
99587 /*
99588 ** Free all memory associated with foreign key definitions attached to
99589 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
99590 ** hash table.
99591 */
99592 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
99593   FKey *pFKey;                    /* Iterator variable */
99594   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
99595 
99596   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
99597   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
99598 
99599     /* Remove the FK from the fkeyHash hash table. */
99600     if( !db || db->pnBytesFreed==0 ){
99601       if( pFKey->pPrevTo ){
99602         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
99603       }else{
99604         void *p = (void *)pFKey->pNextTo;
99605         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
99606         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
99607       }
99608       if( pFKey->pNextTo ){
99609         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
99610       }
99611     }
99612 
99613     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
99614     ** classified as either immediate or deferred.
99615     */
99616     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
99617 
99618     /* Delete any triggers created to implement actions for this FK. */
99619 #ifndef SQLITE_OMIT_TRIGGER
99620     fkTriggerDelete(db, pFKey->apTrigger[0]);
99621     fkTriggerDelete(db, pFKey->apTrigger[1]);
99622 #endif
99623 
99624     pNext = pFKey->pNextFrom;
99625     sqlite3DbFree(db, pFKey);
99626   }
99627 }
99628 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
99629 
99630 /************** End of fkey.c ************************************************/
99631 /************** Begin file insert.c ******************************************/
99632 /*
99633 ** 2001 September 15
99634 **
99635 ** The author disclaims copyright to this source code.  In place of
99636 ** a legal notice, here is a blessing:
99637 **
99638 **    May you do good and not evil.
99639 **    May you find forgiveness for yourself and forgive others.
99640 **    May you share freely, never taking more than you give.
99641 **
99642 *************************************************************************
99643 ** This file contains C code routines that are called by the parser
99644 ** to handle INSERT statements in SQLite.
99645 */
99646 
99647 /*
99648 ** Generate code that will
99649 **
99650 **   (1) acquire a lock for table pTab then
99651 **   (2) open pTab as cursor iCur.
99652 **
99653 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
99654 ** for that table that is actually opened.
99655 */
99656 SQLITE_PRIVATE void sqlite3OpenTable(
99657   Parse *pParse,  /* Generate code into this VDBE */
99658   int iCur,       /* The cursor number of the table */
99659   int iDb,        /* The database index in sqlite3.aDb[] */
99660   Table *pTab,    /* The table to be opened */
99661   int opcode      /* OP_OpenRead or OP_OpenWrite */
99662 ){
99663   Vdbe *v;
99664   assert( !IsVirtual(pTab) );
99665   v = sqlite3GetVdbe(pParse);
99666   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
99667   sqlite3TableLock(pParse, iDb, pTab->tnum,
99668                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
99669   if( HasRowid(pTab) ){
99670     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
99671     VdbeComment((v, "%s", pTab->zName));
99672   }else{
99673     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
99674     assert( pPk!=0 );
99675     assert( pPk->tnum=pTab->tnum );
99676     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
99677     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
99678     VdbeComment((v, "%s", pTab->zName));
99679   }
99680 }
99681 
99682 /*
99683 ** Return a pointer to the column affinity string associated with index
99684 ** pIdx. A column affinity string has one character for each column in
99685 ** the table, according to the affinity of the column:
99686 **
99687 **  Character      Column affinity
99688 **  ------------------------------
99689 **  'A'            NONE
99690 **  'B'            TEXT
99691 **  'C'            NUMERIC
99692 **  'D'            INTEGER
99693 **  'F'            REAL
99694 **
99695 ** An extra 'D' is appended to the end of the string to cover the
99696 ** rowid that appears as the last column in every index.
99697 **
99698 ** Memory for the buffer containing the column index affinity string
99699 ** is managed along with the rest of the Index structure. It will be
99700 ** released when sqlite3DeleteIndex() is called.
99701 */
99702 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
99703   if( !pIdx->zColAff ){
99704     /* The first time a column affinity string for a particular index is
99705     ** required, it is allocated and populated here. It is then stored as
99706     ** a member of the Index structure for subsequent use.
99707     **
99708     ** The column affinity string will eventually be deleted by
99709     ** sqliteDeleteIndex() when the Index structure itself is cleaned
99710     ** up.
99711     */
99712     int n;
99713     Table *pTab = pIdx->pTable;
99714     sqlite3 *db = sqlite3VdbeDb(v);
99715     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
99716     if( !pIdx->zColAff ){
99717       db->mallocFailed = 1;
99718       return 0;
99719     }
99720     for(n=0; n<pIdx->nColumn; n++){
99721       i16 x = pIdx->aiColumn[n];
99722       pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
99723     }
99724     pIdx->zColAff[n] = 0;
99725   }
99726 
99727   return pIdx->zColAff;
99728 }
99729 
99730 /*
99731 ** Compute the affinity string for table pTab, if it has not already been
99732 ** computed.  As an optimization, omit trailing SQLITE_AFF_NONE affinities.
99733 **
99734 ** If the affinity exists (if it is no entirely SQLITE_AFF_NONE values) and
99735 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
99736 ** for register iReg and following.  Or if affinities exists and iReg==0,
99737 ** then just set the P4 operand of the previous opcode (which should  be
99738 ** an OP_MakeRecord) to the affinity string.
99739 **
99740 ** A column affinity string has one character per column:
99741 **
99742 **  Character      Column affinity
99743 **  ------------------------------
99744 **  'A'            NONE
99745 **  'B'            TEXT
99746 **  'C'            NUMERIC
99747 **  'D'            INTEGER
99748 **  'E'            REAL
99749 */
99750 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
99751   int i;
99752   char *zColAff = pTab->zColAff;
99753   if( zColAff==0 ){
99754     sqlite3 *db = sqlite3VdbeDb(v);
99755     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
99756     if( !zColAff ){
99757       db->mallocFailed = 1;
99758       return;
99759     }
99760 
99761     for(i=0; i<pTab->nCol; i++){
99762       zColAff[i] = pTab->aCol[i].affinity;
99763     }
99764     do{
99765       zColAff[i--] = 0;
99766     }while( i>=0 && zColAff[i]==SQLITE_AFF_NONE );
99767     pTab->zColAff = zColAff;
99768   }
99769   i = sqlite3Strlen30(zColAff);
99770   if( i ){
99771     if( iReg ){
99772       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
99773     }else{
99774       sqlite3VdbeChangeP4(v, -1, zColAff, i);
99775     }
99776   }
99777 }
99778 
99779 /*
99780 ** Return non-zero if the table pTab in database iDb or any of its indices
99781 ** have been opened at any point in the VDBE program. This is used to see if
99782 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
99783 ** run without using a temporary table for the results of the SELECT.
99784 */
99785 static int readsTable(Parse *p, int iDb, Table *pTab){
99786   Vdbe *v = sqlite3GetVdbe(p);
99787   int i;
99788   int iEnd = sqlite3VdbeCurrentAddr(v);
99789 #ifndef SQLITE_OMIT_VIRTUALTABLE
99790   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
99791 #endif
99792 
99793   for(i=1; i<iEnd; i++){
99794     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
99795     assert( pOp!=0 );
99796     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
99797       Index *pIndex;
99798       int tnum = pOp->p2;
99799       if( tnum==pTab->tnum ){
99800         return 1;
99801       }
99802       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
99803         if( tnum==pIndex->tnum ){
99804           return 1;
99805         }
99806       }
99807     }
99808 #ifndef SQLITE_OMIT_VIRTUALTABLE
99809     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
99810       assert( pOp->p4.pVtab!=0 );
99811       assert( pOp->p4type==P4_VTAB );
99812       return 1;
99813     }
99814 #endif
99815   }
99816   return 0;
99817 }
99818 
99819 #ifndef SQLITE_OMIT_AUTOINCREMENT
99820 /*
99821 ** Locate or create an AutoincInfo structure associated with table pTab
99822 ** which is in database iDb.  Return the register number for the register
99823 ** that holds the maximum rowid.
99824 **
99825 ** There is at most one AutoincInfo structure per table even if the
99826 ** same table is autoincremented multiple times due to inserts within
99827 ** triggers.  A new AutoincInfo structure is created if this is the
99828 ** first use of table pTab.  On 2nd and subsequent uses, the original
99829 ** AutoincInfo structure is used.
99830 **
99831 ** Three memory locations are allocated:
99832 **
99833 **   (1)  Register to hold the name of the pTab table.
99834 **   (2)  Register to hold the maximum ROWID of pTab.
99835 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
99836 **
99837 ** The 2nd register is the one that is returned.  That is all the
99838 ** insert routine needs to know about.
99839 */
99840 static int autoIncBegin(
99841   Parse *pParse,      /* Parsing context */
99842   int iDb,            /* Index of the database holding pTab */
99843   Table *pTab         /* The table we are writing to */
99844 ){
99845   int memId = 0;      /* Register holding maximum rowid */
99846   if( pTab->tabFlags & TF_Autoincrement ){
99847     Parse *pToplevel = sqlite3ParseToplevel(pParse);
99848     AutoincInfo *pInfo;
99849 
99850     pInfo = pToplevel->pAinc;
99851     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
99852     if( pInfo==0 ){
99853       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
99854       if( pInfo==0 ) return 0;
99855       pInfo->pNext = pToplevel->pAinc;
99856       pToplevel->pAinc = pInfo;
99857       pInfo->pTab = pTab;
99858       pInfo->iDb = iDb;
99859       pToplevel->nMem++;                  /* Register to hold name of table */
99860       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
99861       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
99862     }
99863     memId = pInfo->regCtr;
99864   }
99865   return memId;
99866 }
99867 
99868 /*
99869 ** This routine generates code that will initialize all of the
99870 ** register used by the autoincrement tracker.
99871 */
99872 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
99873   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
99874   sqlite3 *db = pParse->db;  /* The database connection */
99875   Db *pDb;                   /* Database only autoinc table */
99876   int memId;                 /* Register holding max rowid */
99877   int addr;                  /* A VDBE address */
99878   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
99879 
99880   /* This routine is never called during trigger-generation.  It is
99881   ** only called from the top-level */
99882   assert( pParse->pTriggerTab==0 );
99883   assert( pParse==sqlite3ParseToplevel(pParse) );
99884 
99885   assert( v );   /* We failed long ago if this is not so */
99886   for(p = pParse->pAinc; p; p = p->pNext){
99887     pDb = &db->aDb[p->iDb];
99888     memId = p->regCtr;
99889     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
99890     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
99891     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
99892     addr = sqlite3VdbeCurrentAddr(v);
99893     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
99894     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
99895     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
99896     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
99897     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
99898     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
99899     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
99900     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
99901     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
99902     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
99903     sqlite3VdbeAddOp0(v, OP_Close);
99904   }
99905 }
99906 
99907 /*
99908 ** Update the maximum rowid for an autoincrement calculation.
99909 **
99910 ** This routine should be called when the top of the stack holds a
99911 ** new rowid that is about to be inserted.  If that new rowid is
99912 ** larger than the maximum rowid in the memId memory cell, then the
99913 ** memory cell is updated.  The stack is unchanged.
99914 */
99915 static void autoIncStep(Parse *pParse, int memId, int regRowid){
99916   if( memId>0 ){
99917     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
99918   }
99919 }
99920 
99921 /*
99922 ** This routine generates the code needed to write autoincrement
99923 ** maximum rowid values back into the sqlite_sequence register.
99924 ** Every statement that might do an INSERT into an autoincrement
99925 ** table (either directly or through triggers) needs to call this
99926 ** routine just before the "exit" code.
99927 */
99928 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
99929   AutoincInfo *p;
99930   Vdbe *v = pParse->pVdbe;
99931   sqlite3 *db = pParse->db;
99932 
99933   assert( v );
99934   for(p = pParse->pAinc; p; p = p->pNext){
99935     Db *pDb = &db->aDb[p->iDb];
99936     int j1;
99937     int iRec;
99938     int memId = p->regCtr;
99939 
99940     iRec = sqlite3GetTempReg(pParse);
99941     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
99942     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
99943     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
99944     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
99945     sqlite3VdbeJumpHere(v, j1);
99946     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
99947     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
99948     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
99949     sqlite3VdbeAddOp0(v, OP_Close);
99950     sqlite3ReleaseTempReg(pParse, iRec);
99951   }
99952 }
99953 #else
99954 /*
99955 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
99956 ** above are all no-ops
99957 */
99958 # define autoIncBegin(A,B,C) (0)
99959 # define autoIncStep(A,B,C)
99960 #endif /* SQLITE_OMIT_AUTOINCREMENT */
99961 
99962 
99963 /* Forward declaration */
99964 static int xferOptimization(
99965   Parse *pParse,        /* Parser context */
99966   Table *pDest,         /* The table we are inserting into */
99967   Select *pSelect,      /* A SELECT statement to use as the data source */
99968   int onError,          /* How to handle constraint errors */
99969   int iDbDest           /* The database of pDest */
99970 );
99971 
99972 /*
99973 ** This routine is called to handle SQL of the following forms:
99974 **
99975 **    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
99976 **    insert into TABLE (IDLIST) select
99977 **    insert into TABLE (IDLIST) default values
99978 **
99979 ** The IDLIST following the table name is always optional.  If omitted,
99980 ** then a list of all (non-hidden) columns for the table is substituted.
99981 ** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
99982 ** is omitted.
99983 **
99984 ** For the pSelect parameter holds the values to be inserted for the
99985 ** first two forms shown above.  A VALUES clause is really just short-hand
99986 ** for a SELECT statement that omits the FROM clause and everything else
99987 ** that follows.  If the pSelect parameter is NULL, that means that the
99988 ** DEFAULT VALUES form of the INSERT statement is intended.
99989 **
99990 ** The code generated follows one of four templates.  For a simple
99991 ** insert with data coming from a single-row VALUES clause, the code executes
99992 ** once straight down through.  Pseudo-code follows (we call this
99993 ** the "1st template"):
99994 **
99995 **         open write cursor to <table> and its indices
99996 **         put VALUES clause expressions into registers
99997 **         write the resulting record into <table>
99998 **         cleanup
99999 **
100000 ** The three remaining templates assume the statement is of the form
100001 **
100002 **   INSERT INTO <table> SELECT ...
100003 **
100004 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
100005 ** in other words if the SELECT pulls all columns from a single table
100006 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
100007 ** if <table2> and <table1> are distinct tables but have identical
100008 ** schemas, including all the same indices, then a special optimization
100009 ** is invoked that copies raw records from <table2> over to <table1>.
100010 ** See the xferOptimization() function for the implementation of this
100011 ** template.  This is the 2nd template.
100012 **
100013 **         open a write cursor to <table>
100014 **         open read cursor on <table2>
100015 **         transfer all records in <table2> over to <table>
100016 **         close cursors
100017 **         foreach index on <table>
100018 **           open a write cursor on the <table> index
100019 **           open a read cursor on the corresponding <table2> index
100020 **           transfer all records from the read to the write cursors
100021 **           close cursors
100022 **         end foreach
100023 **
100024 ** The 3rd template is for when the second template does not apply
100025 ** and the SELECT clause does not read from <table> at any time.
100026 ** The generated code follows this template:
100027 **
100028 **         X <- A
100029 **         goto B
100030 **      A: setup for the SELECT
100031 **         loop over the rows in the SELECT
100032 **           load values into registers R..R+n
100033 **           yield X
100034 **         end loop
100035 **         cleanup after the SELECT
100036 **         end-coroutine X
100037 **      B: open write cursor to <table> and its indices
100038 **      C: yield X, at EOF goto D
100039 **         insert the select result into <table> from R..R+n
100040 **         goto C
100041 **      D: cleanup
100042 **
100043 ** The 4th template is used if the insert statement takes its
100044 ** values from a SELECT but the data is being inserted into a table
100045 ** that is also read as part of the SELECT.  In the third form,
100046 ** we have to use an intermediate table to store the results of
100047 ** the select.  The template is like this:
100048 **
100049 **         X <- A
100050 **         goto B
100051 **      A: setup for the SELECT
100052 **         loop over the tables in the SELECT
100053 **           load value into register R..R+n
100054 **           yield X
100055 **         end loop
100056 **         cleanup after the SELECT
100057 **         end co-routine R
100058 **      B: open temp table
100059 **      L: yield X, at EOF goto M
100060 **         insert row from R..R+n into temp table
100061 **         goto L
100062 **      M: open write cursor to <table> and its indices
100063 **         rewind temp table
100064 **      C: loop over rows of intermediate table
100065 **           transfer values form intermediate table into <table>
100066 **         end loop
100067 **      D: cleanup
100068 */
100069 SQLITE_PRIVATE void sqlite3Insert(
100070   Parse *pParse,        /* Parser context */
100071   SrcList *pTabList,    /* Name of table into which we are inserting */
100072   Select *pSelect,      /* A SELECT statement to use as the data source */
100073   IdList *pColumn,      /* Column names corresponding to IDLIST. */
100074   int onError           /* How to handle constraint errors */
100075 ){
100076   sqlite3 *db;          /* The main database structure */
100077   Table *pTab;          /* The table to insert into.  aka TABLE */
100078   char *zTab;           /* Name of the table into which we are inserting */
100079   const char *zDb;      /* Name of the database holding this table */
100080   int i, j, idx;        /* Loop counters */
100081   Vdbe *v;              /* Generate code into this virtual machine */
100082   Index *pIdx;          /* For looping over indices of the table */
100083   int nColumn;          /* Number of columns in the data */
100084   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
100085   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
100086   int iIdxCur = 0;      /* First index cursor */
100087   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
100088   int endOfLoop;        /* Label for the end of the insertion loop */
100089   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
100090   int addrInsTop = 0;   /* Jump to label "D" */
100091   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
100092   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
100093   int iDb;              /* Index of database holding TABLE */
100094   Db *pDb;              /* The database containing table being inserted into */
100095   u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
100096   u8 appendFlag = 0;    /* True if the insert is likely to be an append */
100097   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
100098   u8 bIdListInOrder;    /* True if IDLIST is in table order */
100099   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
100100 
100101   /* Register allocations */
100102   int regFromSelect = 0;/* Base register for data coming from SELECT */
100103   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
100104   int regRowCount = 0;  /* Memory cell used for the row counter */
100105   int regIns;           /* Block of regs holding rowid+data being inserted */
100106   int regRowid;         /* registers holding insert rowid */
100107   int regData;          /* register holding first column to insert */
100108   int *aRegIdx = 0;     /* One register allocated to each index */
100109 
100110 #ifndef SQLITE_OMIT_TRIGGER
100111   int isView;                 /* True if attempting to insert into a view */
100112   Trigger *pTrigger;          /* List of triggers on pTab, if required */
100113   int tmask;                  /* Mask of trigger times */
100114 #endif
100115 
100116   db = pParse->db;
100117   memset(&dest, 0, sizeof(dest));
100118   if( pParse->nErr || db->mallocFailed ){
100119     goto insert_cleanup;
100120   }
100121 
100122   /* If the Select object is really just a simple VALUES() list with a
100123   ** single row (the common case) then keep that one row of values
100124   ** and discard the other (unused) parts of the pSelect object
100125   */
100126   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
100127     pList = pSelect->pEList;
100128     pSelect->pEList = 0;
100129     sqlite3SelectDelete(db, pSelect);
100130     pSelect = 0;
100131   }
100132 
100133   /* Locate the table into which we will be inserting new information.
100134   */
100135   assert( pTabList->nSrc==1 );
100136   zTab = pTabList->a[0].zName;
100137   if( NEVER(zTab==0) ) goto insert_cleanup;
100138   pTab = sqlite3SrcListLookup(pParse, pTabList);
100139   if( pTab==0 ){
100140     goto insert_cleanup;
100141   }
100142   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
100143   assert( iDb<db->nDb );
100144   pDb = &db->aDb[iDb];
100145   zDb = pDb->zName;
100146   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
100147     goto insert_cleanup;
100148   }
100149   withoutRowid = !HasRowid(pTab);
100150 
100151   /* Figure out if we have any triggers and if the table being
100152   ** inserted into is a view
100153   */
100154 #ifndef SQLITE_OMIT_TRIGGER
100155   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
100156   isView = pTab->pSelect!=0;
100157 #else
100158 # define pTrigger 0
100159 # define tmask 0
100160 # define isView 0
100161 #endif
100162 #ifdef SQLITE_OMIT_VIEW
100163 # undef isView
100164 # define isView 0
100165 #endif
100166   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
100167 
100168   /* If pTab is really a view, make sure it has been initialized.
100169   ** ViewGetColumnNames() is a no-op if pTab is not a view.
100170   */
100171   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
100172     goto insert_cleanup;
100173   }
100174 
100175   /* Cannot insert into a read-only table.
100176   */
100177   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
100178     goto insert_cleanup;
100179   }
100180 
100181   /* Allocate a VDBE
100182   */
100183   v = sqlite3GetVdbe(pParse);
100184   if( v==0 ) goto insert_cleanup;
100185   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
100186   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
100187 
100188 #ifndef SQLITE_OMIT_XFER_OPT
100189   /* If the statement is of the form
100190   **
100191   **       INSERT INTO <table1> SELECT * FROM <table2>;
100192   **
100193   ** Then special optimizations can be applied that make the transfer
100194   ** very fast and which reduce fragmentation of indices.
100195   **
100196   ** This is the 2nd template.
100197   */
100198   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
100199     assert( !pTrigger );
100200     assert( pList==0 );
100201     goto insert_end;
100202   }
100203 #endif /* SQLITE_OMIT_XFER_OPT */
100204 
100205   /* If this is an AUTOINCREMENT table, look up the sequence number in the
100206   ** sqlite_sequence table and store it in memory cell regAutoinc.
100207   */
100208   regAutoinc = autoIncBegin(pParse, iDb, pTab);
100209 
100210   /* Allocate registers for holding the rowid of the new row,
100211   ** the content of the new row, and the assembled row record.
100212   */
100213   regRowid = regIns = pParse->nMem+1;
100214   pParse->nMem += pTab->nCol + 1;
100215   if( IsVirtual(pTab) ){
100216     regRowid++;
100217     pParse->nMem++;
100218   }
100219   regData = regRowid+1;
100220 
100221   /* If the INSERT statement included an IDLIST term, then make sure
100222   ** all elements of the IDLIST really are columns of the table and
100223   ** remember the column indices.
100224   **
100225   ** If the table has an INTEGER PRIMARY KEY column and that column
100226   ** is named in the IDLIST, then record in the ipkColumn variable
100227   ** the index into IDLIST of the primary key column.  ipkColumn is
100228   ** the index of the primary key as it appears in IDLIST, not as
100229   ** is appears in the original table.  (The index of the INTEGER
100230   ** PRIMARY KEY in the original table is pTab->iPKey.)
100231   */
100232   bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
100233   if( pColumn ){
100234     for(i=0; i<pColumn->nId; i++){
100235       pColumn->a[i].idx = -1;
100236     }
100237     for(i=0; i<pColumn->nId; i++){
100238       for(j=0; j<pTab->nCol; j++){
100239         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
100240           pColumn->a[i].idx = j;
100241           if( i!=j ) bIdListInOrder = 0;
100242           if( j==pTab->iPKey ){
100243             ipkColumn = i;  assert( !withoutRowid );
100244           }
100245           break;
100246         }
100247       }
100248       if( j>=pTab->nCol ){
100249         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
100250           ipkColumn = i;
100251           bIdListInOrder = 0;
100252         }else{
100253           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
100254               pTabList, 0, pColumn->a[i].zName);
100255           pParse->checkSchema = 1;
100256           goto insert_cleanup;
100257         }
100258       }
100259     }
100260   }
100261 
100262   /* Figure out how many columns of data are supplied.  If the data
100263   ** is coming from a SELECT statement, then generate a co-routine that
100264   ** produces a single row of the SELECT on each invocation.  The
100265   ** co-routine is the common header to the 3rd and 4th templates.
100266   */
100267   if( pSelect ){
100268     /* Data is coming from a SELECT or from a multi-row VALUES clause.
100269     ** Generate a co-routine to run the SELECT. */
100270     int regYield;       /* Register holding co-routine entry-point */
100271     int addrTop;        /* Top of the co-routine */
100272     int rc;             /* Result code */
100273 
100274     regYield = ++pParse->nMem;
100275     addrTop = sqlite3VdbeCurrentAddr(v) + 1;
100276     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
100277     sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
100278     dest.iSdst = bIdListInOrder ? regData : 0;
100279     dest.nSdst = pTab->nCol;
100280     rc = sqlite3Select(pParse, pSelect, &dest);
100281     regFromSelect = dest.iSdst;
100282     if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
100283     sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
100284     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
100285     assert( pSelect->pEList );
100286     nColumn = pSelect->pEList->nExpr;
100287 
100288     /* Set useTempTable to TRUE if the result of the SELECT statement
100289     ** should be written into a temporary table (template 4).  Set to
100290     ** FALSE if each output row of the SELECT can be written directly into
100291     ** the destination table (template 3).
100292     **
100293     ** A temp table must be used if the table being updated is also one
100294     ** of the tables being read by the SELECT statement.  Also use a
100295     ** temp table in the case of row triggers.
100296     */
100297     if( pTrigger || readsTable(pParse, iDb, pTab) ){
100298       useTempTable = 1;
100299     }
100300 
100301     if( useTempTable ){
100302       /* Invoke the coroutine to extract information from the SELECT
100303       ** and add it to a transient table srcTab.  The code generated
100304       ** here is from the 4th template:
100305       **
100306       **      B: open temp table
100307       **      L: yield X, goto M at EOF
100308       **         insert row from R..R+n into temp table
100309       **         goto L
100310       **      M: ...
100311       */
100312       int regRec;          /* Register to hold packed record */
100313       int regTempRowid;    /* Register to hold temp table ROWID */
100314       int addrL;           /* Label "L" */
100315 
100316       srcTab = pParse->nTab++;
100317       regRec = sqlite3GetTempReg(pParse);
100318       regTempRowid = sqlite3GetTempReg(pParse);
100319       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
100320       addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
100321       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
100322       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
100323       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
100324       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
100325       sqlite3VdbeJumpHere(v, addrL);
100326       sqlite3ReleaseTempReg(pParse, regRec);
100327       sqlite3ReleaseTempReg(pParse, regTempRowid);
100328     }
100329   }else{
100330     /* This is the case if the data for the INSERT is coming from a
100331     ** single-row VALUES clause
100332     */
100333     NameContext sNC;
100334     memset(&sNC, 0, sizeof(sNC));
100335     sNC.pParse = pParse;
100336     srcTab = -1;
100337     assert( useTempTable==0 );
100338     nColumn = pList ? pList->nExpr : 0;
100339     for(i=0; i<nColumn; i++){
100340       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
100341         goto insert_cleanup;
100342       }
100343     }
100344   }
100345 
100346   /* If there is no IDLIST term but the table has an integer primary
100347   ** key, the set the ipkColumn variable to the integer primary key
100348   ** column index in the original table definition.
100349   */
100350   if( pColumn==0 && nColumn>0 ){
100351     ipkColumn = pTab->iPKey;
100352   }
100353 
100354   /* Make sure the number of columns in the source data matches the number
100355   ** of columns to be inserted into the table.
100356   */
100357   if( IsVirtual(pTab) ){
100358     for(i=0; i<pTab->nCol; i++){
100359       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
100360     }
100361   }
100362   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
100363     sqlite3ErrorMsg(pParse,
100364        "table %S has %d columns but %d values were supplied",
100365        pTabList, 0, pTab->nCol-nHidden, nColumn);
100366     goto insert_cleanup;
100367   }
100368   if( pColumn!=0 && nColumn!=pColumn->nId ){
100369     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
100370     goto insert_cleanup;
100371   }
100372 
100373   /* Initialize the count of rows to be inserted
100374   */
100375   if( db->flags & SQLITE_CountRows ){
100376     regRowCount = ++pParse->nMem;
100377     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
100378   }
100379 
100380   /* If this is not a view, open the table and and all indices */
100381   if( !isView ){
100382     int nIdx;
100383     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
100384                                       &iDataCur, &iIdxCur);
100385     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
100386     if( aRegIdx==0 ){
100387       goto insert_cleanup;
100388     }
100389     for(i=0; i<nIdx; i++){
100390       aRegIdx[i] = ++pParse->nMem;
100391     }
100392   }
100393 
100394   /* This is the top of the main insertion loop */
100395   if( useTempTable ){
100396     /* This block codes the top of loop only.  The complete loop is the
100397     ** following pseudocode (template 4):
100398     **
100399     **         rewind temp table, if empty goto D
100400     **      C: loop over rows of intermediate table
100401     **           transfer values form intermediate table into <table>
100402     **         end loop
100403     **      D: ...
100404     */
100405     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
100406     addrCont = sqlite3VdbeCurrentAddr(v);
100407   }else if( pSelect ){
100408     /* This block codes the top of loop only.  The complete loop is the
100409     ** following pseudocode (template 3):
100410     **
100411     **      C: yield X, at EOF goto D
100412     **         insert the select result into <table> from R..R+n
100413     **         goto C
100414     **      D: ...
100415     */
100416     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
100417     VdbeCoverage(v);
100418   }
100419 
100420   /* Run the BEFORE and INSTEAD OF triggers, if there are any
100421   */
100422   endOfLoop = sqlite3VdbeMakeLabel(v);
100423   if( tmask & TRIGGER_BEFORE ){
100424     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
100425 
100426     /* build the NEW.* reference row.  Note that if there is an INTEGER
100427     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
100428     ** translated into a unique ID for the row.  But on a BEFORE trigger,
100429     ** we do not know what the unique ID will be (because the insert has
100430     ** not happened yet) so we substitute a rowid of -1
100431     */
100432     if( ipkColumn<0 ){
100433       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
100434     }else{
100435       int j1;
100436       assert( !withoutRowid );
100437       if( useTempTable ){
100438         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
100439       }else{
100440         assert( pSelect==0 );  /* Otherwise useTempTable is true */
100441         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
100442       }
100443       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
100444       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
100445       sqlite3VdbeJumpHere(v, j1);
100446       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
100447     }
100448 
100449     /* Cannot have triggers on a virtual table. If it were possible,
100450     ** this block would have to account for hidden column.
100451     */
100452     assert( !IsVirtual(pTab) );
100453 
100454     /* Create the new column data
100455     */
100456     for(i=0; i<pTab->nCol; i++){
100457       if( pColumn==0 ){
100458         j = i;
100459       }else{
100460         for(j=0; j<pColumn->nId; j++){
100461           if( pColumn->a[j].idx==i ) break;
100462         }
100463       }
100464       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
100465         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
100466       }else if( useTempTable ){
100467         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
100468       }else{
100469         assert( pSelect==0 ); /* Otherwise useTempTable is true */
100470         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
100471       }
100472     }
100473 
100474     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
100475     ** do not attempt any conversions before assembling the record.
100476     ** If this is a real table, attempt conversions as required by the
100477     ** table column affinities.
100478     */
100479     if( !isView ){
100480       sqlite3TableAffinity(v, pTab, regCols+1);
100481     }
100482 
100483     /* Fire BEFORE or INSTEAD OF triggers */
100484     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
100485         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
100486 
100487     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
100488   }
100489 
100490   /* Compute the content of the next row to insert into a range of
100491   ** registers beginning at regIns.
100492   */
100493   if( !isView ){
100494     if( IsVirtual(pTab) ){
100495       /* The row that the VUpdate opcode will delete: none */
100496       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
100497     }
100498     if( ipkColumn>=0 ){
100499       if( useTempTable ){
100500         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
100501       }else if( pSelect ){
100502         sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
100503       }else{
100504         VdbeOp *pOp;
100505         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
100506         pOp = sqlite3VdbeGetOp(v, -1);
100507         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
100508           appendFlag = 1;
100509           pOp->opcode = OP_NewRowid;
100510           pOp->p1 = iDataCur;
100511           pOp->p2 = regRowid;
100512           pOp->p3 = regAutoinc;
100513         }
100514       }
100515       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
100516       ** to generate a unique primary key value.
100517       */
100518       if( !appendFlag ){
100519         int j1;
100520         if( !IsVirtual(pTab) ){
100521           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
100522           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
100523           sqlite3VdbeJumpHere(v, j1);
100524         }else{
100525           j1 = sqlite3VdbeCurrentAddr(v);
100526           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
100527         }
100528         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
100529       }
100530     }else if( IsVirtual(pTab) || withoutRowid ){
100531       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
100532     }else{
100533       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
100534       appendFlag = 1;
100535     }
100536     autoIncStep(pParse, regAutoinc, regRowid);
100537 
100538     /* Compute data for all columns of the new entry, beginning
100539     ** with the first column.
100540     */
100541     nHidden = 0;
100542     for(i=0; i<pTab->nCol; i++){
100543       int iRegStore = regRowid+1+i;
100544       if( i==pTab->iPKey ){
100545         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
100546         ** Whenever this column is read, the rowid will be substituted
100547         ** in its place.  Hence, fill this column with a NULL to avoid
100548         ** taking up data space with information that will never be used.
100549         ** As there may be shallow copies of this value, make it a soft-NULL */
100550         sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
100551         continue;
100552       }
100553       if( pColumn==0 ){
100554         if( IsHiddenColumn(&pTab->aCol[i]) ){
100555           assert( IsVirtual(pTab) );
100556           j = -1;
100557           nHidden++;
100558         }else{
100559           j = i - nHidden;
100560         }
100561       }else{
100562         for(j=0; j<pColumn->nId; j++){
100563           if( pColumn->a[j].idx==i ) break;
100564         }
100565       }
100566       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
100567         sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
100568       }else if( useTempTable ){
100569         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
100570       }else if( pSelect ){
100571         if( regFromSelect!=regData ){
100572           sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
100573         }
100574       }else{
100575         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
100576       }
100577     }
100578 
100579     /* Generate code to check constraints and generate index keys and
100580     ** do the insertion.
100581     */
100582 #ifndef SQLITE_OMIT_VIRTUALTABLE
100583     if( IsVirtual(pTab) ){
100584       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
100585       sqlite3VtabMakeWritable(pParse, pTab);
100586       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
100587       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
100588       sqlite3MayAbort(pParse);
100589     }else
100590 #endif
100591     {
100592       int isReplace;    /* Set to true if constraints may cause a replace */
100593       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
100594           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
100595       );
100596       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
100597       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
100598                                regIns, aRegIdx, 0, appendFlag, isReplace==0);
100599     }
100600   }
100601 
100602   /* Update the count of rows that are inserted
100603   */
100604   if( (db->flags & SQLITE_CountRows)!=0 ){
100605     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
100606   }
100607 
100608   if( pTrigger ){
100609     /* Code AFTER triggers */
100610     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
100611         pTab, regData-2-pTab->nCol, onError, endOfLoop);
100612   }
100613 
100614   /* The bottom of the main insertion loop, if the data source
100615   ** is a SELECT statement.
100616   */
100617   sqlite3VdbeResolveLabel(v, endOfLoop);
100618   if( useTempTable ){
100619     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
100620     sqlite3VdbeJumpHere(v, addrInsTop);
100621     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
100622   }else if( pSelect ){
100623     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
100624     sqlite3VdbeJumpHere(v, addrInsTop);
100625   }
100626 
100627   if( !IsVirtual(pTab) && !isView ){
100628     /* Close all tables opened */
100629     if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
100630     for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
100631       sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
100632     }
100633   }
100634 
100635 insert_end:
100636   /* Update the sqlite_sequence table by storing the content of the
100637   ** maximum rowid counter values recorded while inserting into
100638   ** autoincrement tables.
100639   */
100640   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
100641     sqlite3AutoincrementEnd(pParse);
100642   }
100643 
100644   /*
100645   ** Return the number of rows inserted. If this routine is
100646   ** generating code because of a call to sqlite3NestedParse(), do not
100647   ** invoke the callback function.
100648   */
100649   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
100650     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
100651     sqlite3VdbeSetNumCols(v, 1);
100652     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
100653   }
100654 
100655 insert_cleanup:
100656   sqlite3SrcListDelete(db, pTabList);
100657   sqlite3ExprListDelete(db, pList);
100658   sqlite3SelectDelete(db, pSelect);
100659   sqlite3IdListDelete(db, pColumn);
100660   sqlite3DbFree(db, aRegIdx);
100661 }
100662 
100663 /* Make sure "isView" and other macros defined above are undefined. Otherwise
100664 ** they may interfere with compilation of other functions in this file
100665 ** (or in another file, if this file becomes part of the amalgamation).  */
100666 #ifdef isView
100667  #undef isView
100668 #endif
100669 #ifdef pTrigger
100670  #undef pTrigger
100671 #endif
100672 #ifdef tmask
100673  #undef tmask
100674 #endif
100675 
100676 /*
100677 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
100678 ** on table pTab.
100679 **
100680 ** The regNewData parameter is the first register in a range that contains
100681 ** the data to be inserted or the data after the update.  There will be
100682 ** pTab->nCol+1 registers in this range.  The first register (the one
100683 ** that regNewData points to) will contain the new rowid, or NULL in the
100684 ** case of a WITHOUT ROWID table.  The second register in the range will
100685 ** contain the content of the first table column.  The third register will
100686 ** contain the content of the second table column.  And so forth.
100687 **
100688 ** The regOldData parameter is similar to regNewData except that it contains
100689 ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
100690 ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
100691 ** checking regOldData for zero.
100692 **
100693 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
100694 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
100695 ** might be modified by the UPDATE.  If pkChng is false, then the key of
100696 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
100697 **
100698 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
100699 ** was explicitly specified as part of the INSERT statement.  If pkChng
100700 ** is zero, it means that the either rowid is computed automatically or
100701 ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
100702 ** pkChng will only be true if the INSERT statement provides an integer
100703 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
100704 **
100705 ** The code generated by this routine will store new index entries into
100706 ** registers identified by aRegIdx[].  No index entry is created for
100707 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
100708 ** the same as the order of indices on the linked list of indices
100709 ** at pTab->pIndex.
100710 **
100711 ** The caller must have already opened writeable cursors on the main
100712 ** table and all applicable indices (that is to say, all indices for which
100713 ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
100714 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
100715 ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
100716 ** for the first index in the pTab->pIndex list.  Cursors for other indices
100717 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
100718 **
100719 ** This routine also generates code to check constraints.  NOT NULL,
100720 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
100721 ** then the appropriate action is performed.  There are five possible
100722 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
100723 **
100724 **  Constraint type  Action       What Happens
100725 **  ---------------  ----------   ----------------------------------------
100726 **  any              ROLLBACK     The current transaction is rolled back and
100727 **                                sqlite3_step() returns immediately with a
100728 **                                return code of SQLITE_CONSTRAINT.
100729 **
100730 **  any              ABORT        Back out changes from the current command
100731 **                                only (do not do a complete rollback) then
100732 **                                cause sqlite3_step() to return immediately
100733 **                                with SQLITE_CONSTRAINT.
100734 **
100735 **  any              FAIL         Sqlite3_step() returns immediately with a
100736 **                                return code of SQLITE_CONSTRAINT.  The
100737 **                                transaction is not rolled back and any
100738 **                                changes to prior rows are retained.
100739 **
100740 **  any              IGNORE       The attempt in insert or update the current
100741 **                                row is skipped, without throwing an error.
100742 **                                Processing continues with the next row.
100743 **                                (There is an immediate jump to ignoreDest.)
100744 **
100745 **  NOT NULL         REPLACE      The NULL value is replace by the default
100746 **                                value for that column.  If the default value
100747 **                                is NULL, the action is the same as ABORT.
100748 **
100749 **  UNIQUE           REPLACE      The other row that conflicts with the row
100750 **                                being inserted is removed.
100751 **
100752 **  CHECK            REPLACE      Illegal.  The results in an exception.
100753 **
100754 ** Which action to take is determined by the overrideError parameter.
100755 ** Or if overrideError==OE_Default, then the pParse->onError parameter
100756 ** is used.  Or if pParse->onError==OE_Default then the onError value
100757 ** for the constraint is used.
100758 */
100759 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
100760   Parse *pParse,       /* The parser context */
100761   Table *pTab,         /* The table being inserted or updated */
100762   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
100763   int iDataCur,        /* Canonical data cursor (main table or PK index) */
100764   int iIdxCur,         /* First index cursor */
100765   int regNewData,      /* First register in a range holding values to insert */
100766   int regOldData,      /* Previous content.  0 for INSERTs */
100767   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
100768   u8 overrideError,    /* Override onError to this if not OE_Default */
100769   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
100770   int *pbMayReplace    /* OUT: Set to true if constraint may cause a replace */
100771 ){
100772   Vdbe *v;             /* VDBE under constrution */
100773   Index *pIdx;         /* Pointer to one of the indices */
100774   Index *pPk = 0;      /* The PRIMARY KEY index */
100775   sqlite3 *db;         /* Database connection */
100776   int i;               /* loop counter */
100777   int ix;              /* Index loop counter */
100778   int nCol;            /* Number of columns */
100779   int onError;         /* Conflict resolution strategy */
100780   int j1;              /* Address of jump instruction */
100781   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
100782   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
100783   int ipkTop = 0;      /* Top of the rowid change constraint check */
100784   int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
100785   u8 isUpdate;         /* True if this is an UPDATE operation */
100786   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
100787   int regRowid = -1;   /* Register holding ROWID value */
100788 
100789   isUpdate = regOldData!=0;
100790   db = pParse->db;
100791   v = sqlite3GetVdbe(pParse);
100792   assert( v!=0 );
100793   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
100794   nCol = pTab->nCol;
100795 
100796   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
100797   ** normal rowid tables.  nPkField is the number of key fields in the
100798   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
100799   ** number of fields in the true primary key of the table. */
100800   if( HasRowid(pTab) ){
100801     pPk = 0;
100802     nPkField = 1;
100803   }else{
100804     pPk = sqlite3PrimaryKeyIndex(pTab);
100805     nPkField = pPk->nKeyCol;
100806   }
100807 
100808   /* Record that this module has started */
100809   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
100810                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
100811 
100812   /* Test all NOT NULL constraints.
100813   */
100814   for(i=0; i<nCol; i++){
100815     if( i==pTab->iPKey ){
100816       continue;
100817     }
100818     onError = pTab->aCol[i].notNull;
100819     if( onError==OE_None ) continue;
100820     if( overrideError!=OE_Default ){
100821       onError = overrideError;
100822     }else if( onError==OE_Default ){
100823       onError = OE_Abort;
100824     }
100825     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
100826       onError = OE_Abort;
100827     }
100828     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
100829         || onError==OE_Ignore || onError==OE_Replace );
100830     switch( onError ){
100831       case OE_Abort:
100832         sqlite3MayAbort(pParse);
100833         /* Fall through */
100834       case OE_Rollback:
100835       case OE_Fail: {
100836         char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
100837                                     pTab->aCol[i].zName);
100838         sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
100839                           regNewData+1+i, zMsg, P4_DYNAMIC);
100840         sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
100841         VdbeCoverage(v);
100842         break;
100843       }
100844       case OE_Ignore: {
100845         sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
100846         VdbeCoverage(v);
100847         break;
100848       }
100849       default: {
100850         assert( onError==OE_Replace );
100851         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
100852         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
100853         sqlite3VdbeJumpHere(v, j1);
100854         break;
100855       }
100856     }
100857   }
100858 
100859   /* Test all CHECK constraints
100860   */
100861 #ifndef SQLITE_OMIT_CHECK
100862   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
100863     ExprList *pCheck = pTab->pCheck;
100864     pParse->ckBase = regNewData+1;
100865     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
100866     for(i=0; i<pCheck->nExpr; i++){
100867       int allOk = sqlite3VdbeMakeLabel(v);
100868       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
100869       if( onError==OE_Ignore ){
100870         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
100871       }else{
100872         char *zName = pCheck->a[i].zName;
100873         if( zName==0 ) zName = pTab->zName;
100874         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
100875         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
100876                               onError, zName, P4_TRANSIENT,
100877                               P5_ConstraintCheck);
100878       }
100879       sqlite3VdbeResolveLabel(v, allOk);
100880     }
100881   }
100882 #endif /* !defined(SQLITE_OMIT_CHECK) */
100883 
100884   /* If rowid is changing, make sure the new rowid does not previously
100885   ** exist in the table.
100886   */
100887   if( pkChng && pPk==0 ){
100888     int addrRowidOk = sqlite3VdbeMakeLabel(v);
100889 
100890     /* Figure out what action to take in case of a rowid collision */
100891     onError = pTab->keyConf;
100892     if( overrideError!=OE_Default ){
100893       onError = overrideError;
100894     }else if( onError==OE_Default ){
100895       onError = OE_Abort;
100896     }
100897 
100898     if( isUpdate ){
100899       /* pkChng!=0 does not mean that the rowid has change, only that
100900       ** it might have changed.  Skip the conflict logic below if the rowid
100901       ** is unchanged. */
100902       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
100903       sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
100904       VdbeCoverage(v);
100905     }
100906 
100907     /* If the response to a rowid conflict is REPLACE but the response
100908     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
100909     ** to defer the running of the rowid conflict checking until after
100910     ** the UNIQUE constraints have run.
100911     */
100912     if( onError==OE_Replace && overrideError!=OE_Replace ){
100913       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100914         if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
100915           ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
100916           break;
100917         }
100918       }
100919     }
100920 
100921     /* Check to see if the new rowid already exists in the table.  Skip
100922     ** the following conflict logic if it does not. */
100923     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
100924     VdbeCoverage(v);
100925 
100926     /* Generate code that deals with a rowid collision */
100927     switch( onError ){
100928       default: {
100929         onError = OE_Abort;
100930         /* Fall thru into the next case */
100931       }
100932       case OE_Rollback:
100933       case OE_Abort:
100934       case OE_Fail: {
100935         sqlite3RowidConstraint(pParse, onError, pTab);
100936         break;
100937       }
100938       case OE_Replace: {
100939         /* If there are DELETE triggers on this table and the
100940         ** recursive-triggers flag is set, call GenerateRowDelete() to
100941         ** remove the conflicting row from the table. This will fire
100942         ** the triggers and remove both the table and index b-tree entries.
100943         **
100944         ** Otherwise, if there are no triggers or the recursive-triggers
100945         ** flag is not set, but the table has one or more indexes, call
100946         ** GenerateRowIndexDelete(). This removes the index b-tree entries
100947         ** only. The table b-tree entry will be replaced by the new entry
100948         ** when it is inserted.
100949         **
100950         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
100951         ** also invoke MultiWrite() to indicate that this VDBE may require
100952         ** statement rollback (if the statement is aborted after the delete
100953         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
100954         ** but being more selective here allows statements like:
100955         **
100956         **   REPLACE INTO t(rowid) VALUES($newrowid)
100957         **
100958         ** to run without a statement journal if there are no indexes on the
100959         ** table.
100960         */
100961         Trigger *pTrigger = 0;
100962         if( db->flags&SQLITE_RecTriggers ){
100963           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
100964         }
100965         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
100966           sqlite3MultiWrite(pParse);
100967           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
100968                                    regNewData, 1, 0, OE_Replace, 1);
100969         }else if( pTab->pIndex ){
100970           sqlite3MultiWrite(pParse);
100971           sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
100972         }
100973         seenReplace = 1;
100974         break;
100975       }
100976       case OE_Ignore: {
100977         /*assert( seenReplace==0 );*/
100978         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
100979         break;
100980       }
100981     }
100982     sqlite3VdbeResolveLabel(v, addrRowidOk);
100983     if( ipkTop ){
100984       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
100985       sqlite3VdbeJumpHere(v, ipkTop);
100986     }
100987   }
100988 
100989   /* Test all UNIQUE constraints by creating entries for each UNIQUE
100990   ** index and making sure that duplicate entries do not already exist.
100991   ** Compute the revised record entries for indices as we go.
100992   **
100993   ** This loop also handles the case of the PRIMARY KEY index for a
100994   ** WITHOUT ROWID table.
100995   */
100996   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
100997     int regIdx;          /* Range of registers hold conent for pIdx */
100998     int regR;            /* Range of registers holding conflicting PK */
100999     int iThisCur;        /* Cursor for this UNIQUE index */
101000     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
101001 
101002     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
101003     if( bAffinityDone==0 ){
101004       sqlite3TableAffinity(v, pTab, regNewData+1);
101005       bAffinityDone = 1;
101006     }
101007     iThisCur = iIdxCur+ix;
101008     addrUniqueOk = sqlite3VdbeMakeLabel(v);
101009 
101010     /* Skip partial indices for which the WHERE clause is not true */
101011     if( pIdx->pPartIdxWhere ){
101012       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
101013       pParse->ckBase = regNewData+1;
101014       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
101015                          SQLITE_JUMPIFNULL);
101016       pParse->ckBase = 0;
101017     }
101018 
101019     /* Create a record for this index entry as it should appear after
101020     ** the insert or update.  Store that record in the aRegIdx[ix] register
101021     */
101022     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
101023     for(i=0; i<pIdx->nColumn; i++){
101024       int iField = pIdx->aiColumn[i];
101025       int x;
101026       if( iField<0 || iField==pTab->iPKey ){
101027         if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
101028         x = regNewData;
101029         regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
101030       }else{
101031         x = iField + regNewData + 1;
101032       }
101033       sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
101034       VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
101035     }
101036     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
101037     VdbeComment((v, "for %s", pIdx->zName));
101038     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
101039 
101040     /* In an UPDATE operation, if this index is the PRIMARY KEY index
101041     ** of a WITHOUT ROWID table and there has been no change the
101042     ** primary key, then no collision is possible.  The collision detection
101043     ** logic below can all be skipped. */
101044     if( isUpdate && pPk==pIdx && pkChng==0 ){
101045       sqlite3VdbeResolveLabel(v, addrUniqueOk);
101046       continue;
101047     }
101048 
101049     /* Find out what action to take in case there is a uniqueness conflict */
101050     onError = pIdx->onError;
101051     if( onError==OE_None ){
101052       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
101053       sqlite3VdbeResolveLabel(v, addrUniqueOk);
101054       continue;  /* pIdx is not a UNIQUE index */
101055     }
101056     if( overrideError!=OE_Default ){
101057       onError = overrideError;
101058     }else if( onError==OE_Default ){
101059       onError = OE_Abort;
101060     }
101061 
101062     /* Check to see if the new index entry will be unique */
101063     sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
101064                          regIdx, pIdx->nKeyCol); VdbeCoverage(v);
101065 
101066     /* Generate code to handle collisions */
101067     regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
101068     if( isUpdate || onError==OE_Replace ){
101069       if( HasRowid(pTab) ){
101070         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
101071         /* Conflict only if the rowid of the existing index entry
101072         ** is different from old-rowid */
101073         if( isUpdate ){
101074           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
101075           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
101076           VdbeCoverage(v);
101077         }
101078       }else{
101079         int x;
101080         /* Extract the PRIMARY KEY from the end of the index entry and
101081         ** store it in registers regR..regR+nPk-1 */
101082         if( pIdx!=pPk ){
101083           for(i=0; i<pPk->nKeyCol; i++){
101084             x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
101085             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
101086             VdbeComment((v, "%s.%s", pTab->zName,
101087                          pTab->aCol[pPk->aiColumn[i]].zName));
101088           }
101089         }
101090         if( isUpdate ){
101091           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
101092           ** table, only conflict if the new PRIMARY KEY values are actually
101093           ** different from the old.
101094           **
101095           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
101096           ** of the matched index row are different from the original PRIMARY
101097           ** KEY values of this row before the update.  */
101098           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
101099           int op = OP_Ne;
101100           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
101101 
101102           for(i=0; i<pPk->nKeyCol; i++){
101103             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
101104             x = pPk->aiColumn[i];
101105             if( i==(pPk->nKeyCol-1) ){
101106               addrJump = addrUniqueOk;
101107               op = OP_Eq;
101108             }
101109             sqlite3VdbeAddOp4(v, op,
101110                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
101111             );
101112             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
101113             VdbeCoverageIf(v, op==OP_Eq);
101114             VdbeCoverageIf(v, op==OP_Ne);
101115           }
101116         }
101117       }
101118     }
101119 
101120     /* Generate code that executes if the new index entry is not unique */
101121     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
101122         || onError==OE_Ignore || onError==OE_Replace );
101123     switch( onError ){
101124       case OE_Rollback:
101125       case OE_Abort:
101126       case OE_Fail: {
101127         sqlite3UniqueConstraint(pParse, onError, pIdx);
101128         break;
101129       }
101130       case OE_Ignore: {
101131         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
101132         break;
101133       }
101134       default: {
101135         Trigger *pTrigger = 0;
101136         assert( onError==OE_Replace );
101137         sqlite3MultiWrite(pParse);
101138         if( db->flags&SQLITE_RecTriggers ){
101139           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
101140         }
101141         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
101142                                  regR, nPkField, 0, OE_Replace, pIdx==pPk);
101143         seenReplace = 1;
101144         break;
101145       }
101146     }
101147     sqlite3VdbeResolveLabel(v, addrUniqueOk);
101148     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
101149     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
101150   }
101151   if( ipkTop ){
101152     sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
101153     sqlite3VdbeJumpHere(v, ipkBottom);
101154   }
101155 
101156   *pbMayReplace = seenReplace;
101157   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
101158 }
101159 
101160 /*
101161 ** This routine generates code to finish the INSERT or UPDATE operation
101162 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
101163 ** A consecutive range of registers starting at regNewData contains the
101164 ** rowid and the content to be inserted.
101165 **
101166 ** The arguments to this routine should be the same as the first six
101167 ** arguments to sqlite3GenerateConstraintChecks.
101168 */
101169 SQLITE_PRIVATE void sqlite3CompleteInsertion(
101170   Parse *pParse,      /* The parser context */
101171   Table *pTab,        /* the table into which we are inserting */
101172   int iDataCur,       /* Cursor of the canonical data source */
101173   int iIdxCur,        /* First index cursor */
101174   int regNewData,     /* Range of content */
101175   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
101176   int isUpdate,       /* True for UPDATE, False for INSERT */
101177   int appendBias,     /* True if this is likely to be an append */
101178   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
101179 ){
101180   Vdbe *v;            /* Prepared statements under construction */
101181   Index *pIdx;        /* An index being inserted or updated */
101182   u8 pik_flags;       /* flag values passed to the btree insert */
101183   int regData;        /* Content registers (after the rowid) */
101184   int regRec;         /* Register holding assembled record for the table */
101185   int i;              /* Loop counter */
101186   u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
101187 
101188   v = sqlite3GetVdbe(pParse);
101189   assert( v!=0 );
101190   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
101191   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
101192     if( aRegIdx[i]==0 ) continue;
101193     bAffinityDone = 1;
101194     if( pIdx->pPartIdxWhere ){
101195       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
101196       VdbeCoverage(v);
101197     }
101198     sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
101199     pik_flags = 0;
101200     if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
101201     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
101202       assert( pParse->nested==0 );
101203       pik_flags |= OPFLAG_NCHANGE;
101204     }
101205     if( pik_flags )  sqlite3VdbeChangeP5(v, pik_flags);
101206   }
101207   if( !HasRowid(pTab) ) return;
101208   regData = regNewData + 1;
101209   regRec = sqlite3GetTempReg(pParse);
101210   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
101211   if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
101212   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
101213   if( pParse->nested ){
101214     pik_flags = 0;
101215   }else{
101216     pik_flags = OPFLAG_NCHANGE;
101217     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
101218   }
101219   if( appendBias ){
101220     pik_flags |= OPFLAG_APPEND;
101221   }
101222   if( useSeekResult ){
101223     pik_flags |= OPFLAG_USESEEKRESULT;
101224   }
101225   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
101226   if( !pParse->nested ){
101227     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
101228   }
101229   sqlite3VdbeChangeP5(v, pik_flags);
101230 }
101231 
101232 /*
101233 ** Allocate cursors for the pTab table and all its indices and generate
101234 ** code to open and initialized those cursors.
101235 **
101236 ** The cursor for the object that contains the complete data (normally
101237 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
101238 ** ROWID table) is returned in *piDataCur.  The first index cursor is
101239 ** returned in *piIdxCur.  The number of indices is returned.
101240 **
101241 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
101242 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
101243 ** If iBase is negative, then allocate the next available cursor.
101244 **
101245 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
101246 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
101247 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
101248 ** pTab->pIndex list.
101249 **
101250 ** If pTab is a virtual table, then this routine is a no-op and the
101251 ** *piDataCur and *piIdxCur values are left uninitialized.
101252 */
101253 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
101254   Parse *pParse,   /* Parsing context */
101255   Table *pTab,     /* Table to be opened */
101256   int op,          /* OP_OpenRead or OP_OpenWrite */
101257   int iBase,       /* Use this for the table cursor, if there is one */
101258   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
101259   int *piDataCur,  /* Write the database source cursor number here */
101260   int *piIdxCur    /* Write the first index cursor number here */
101261 ){
101262   int i;
101263   int iDb;
101264   int iDataCur;
101265   Index *pIdx;
101266   Vdbe *v;
101267 
101268   assert( op==OP_OpenRead || op==OP_OpenWrite );
101269   if( IsVirtual(pTab) ){
101270     /* This routine is a no-op for virtual tables. Leave the output
101271     ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
101272     ** can detect if they are used by mistake in the caller. */
101273     return 0;
101274   }
101275   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
101276   v = sqlite3GetVdbe(pParse);
101277   assert( v!=0 );
101278   if( iBase<0 ) iBase = pParse->nTab;
101279   iDataCur = iBase++;
101280   if( piDataCur ) *piDataCur = iDataCur;
101281   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
101282     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
101283   }else{
101284     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
101285   }
101286   if( piIdxCur ) *piIdxCur = iBase;
101287   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
101288     int iIdxCur = iBase++;
101289     assert( pIdx->pSchema==pTab->pSchema );
101290     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
101291       *piDataCur = iIdxCur;
101292     }
101293     if( aToOpen==0 || aToOpen[i+1] ){
101294       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
101295       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
101296       VdbeComment((v, "%s", pIdx->zName));
101297     }
101298   }
101299   if( iBase>pParse->nTab ) pParse->nTab = iBase;
101300   return i;
101301 }
101302 
101303 
101304 #ifdef SQLITE_TEST
101305 /*
101306 ** The following global variable is incremented whenever the
101307 ** transfer optimization is used.  This is used for testing
101308 ** purposes only - to make sure the transfer optimization really
101309 ** is happening when it is supposed to.
101310 */
101311 SQLITE_API int sqlite3_xferopt_count;
101312 #endif /* SQLITE_TEST */
101313 
101314 
101315 #ifndef SQLITE_OMIT_XFER_OPT
101316 /*
101317 ** Check to collation names to see if they are compatible.
101318 */
101319 static int xferCompatibleCollation(const char *z1, const char *z2){
101320   if( z1==0 ){
101321     return z2==0;
101322   }
101323   if( z2==0 ){
101324     return 0;
101325   }
101326   return sqlite3StrICmp(z1, z2)==0;
101327 }
101328 
101329 
101330 /*
101331 ** Check to see if index pSrc is compatible as a source of data
101332 ** for index pDest in an insert transfer optimization.  The rules
101333 ** for a compatible index:
101334 **
101335 **    *   The index is over the same set of columns
101336 **    *   The same DESC and ASC markings occurs on all columns
101337 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
101338 **    *   The same collating sequence on each column
101339 **    *   The index has the exact same WHERE clause
101340 */
101341 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
101342   int i;
101343   assert( pDest && pSrc );
101344   assert( pDest->pTable!=pSrc->pTable );
101345   if( pDest->nKeyCol!=pSrc->nKeyCol ){
101346     return 0;   /* Different number of columns */
101347   }
101348   if( pDest->onError!=pSrc->onError ){
101349     return 0;   /* Different conflict resolution strategies */
101350   }
101351   for(i=0; i<pSrc->nKeyCol; i++){
101352     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
101353       return 0;   /* Different columns indexed */
101354     }
101355     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
101356       return 0;   /* Different sort orders */
101357     }
101358     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
101359       return 0;   /* Different collating sequences */
101360     }
101361   }
101362   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
101363     return 0;     /* Different WHERE clauses */
101364   }
101365 
101366   /* If no test above fails then the indices must be compatible */
101367   return 1;
101368 }
101369 
101370 /*
101371 ** Attempt the transfer optimization on INSERTs of the form
101372 **
101373 **     INSERT INTO tab1 SELECT * FROM tab2;
101374 **
101375 ** The xfer optimization transfers raw records from tab2 over to tab1.
101376 ** Columns are not decoded and reassembled, which greatly improves
101377 ** performance.  Raw index records are transferred in the same way.
101378 **
101379 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
101380 ** There are lots of rules for determining compatibility - see comments
101381 ** embedded in the code for details.
101382 **
101383 ** This routine returns TRUE if the optimization is guaranteed to be used.
101384 ** Sometimes the xfer optimization will only work if the destination table
101385 ** is empty - a factor that can only be determined at run-time.  In that
101386 ** case, this routine generates code for the xfer optimization but also
101387 ** does a test to see if the destination table is empty and jumps over the
101388 ** xfer optimization code if the test fails.  In that case, this routine
101389 ** returns FALSE so that the caller will know to go ahead and generate
101390 ** an unoptimized transfer.  This routine also returns FALSE if there
101391 ** is no chance that the xfer optimization can be applied.
101392 **
101393 ** This optimization is particularly useful at making VACUUM run faster.
101394 */
101395 static int xferOptimization(
101396   Parse *pParse,        /* Parser context */
101397   Table *pDest,         /* The table we are inserting into */
101398   Select *pSelect,      /* A SELECT statement to use as the data source */
101399   int onError,          /* How to handle constraint errors */
101400   int iDbDest           /* The database of pDest */
101401 ){
101402   sqlite3 *db = pParse->db;
101403   ExprList *pEList;                /* The result set of the SELECT */
101404   Table *pSrc;                     /* The table in the FROM clause of SELECT */
101405   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
101406   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
101407   int i;                           /* Loop counter */
101408   int iDbSrc;                      /* The database of pSrc */
101409   int iSrc, iDest;                 /* Cursors from source and destination */
101410   int addr1, addr2;                /* Loop addresses */
101411   int emptyDestTest = 0;           /* Address of test for empty pDest */
101412   int emptySrcTest = 0;            /* Address of test for empty pSrc */
101413   Vdbe *v;                         /* The VDBE we are building */
101414   int regAutoinc;                  /* Memory register used by AUTOINC */
101415   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
101416   int regData, regRowid;           /* Registers holding data and rowid */
101417 
101418   if( pSelect==0 ){
101419     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
101420   }
101421   if( pParse->pWith || pSelect->pWith ){
101422     /* Do not attempt to process this query if there are an WITH clauses
101423     ** attached to it. Proceeding may generate a false "no such table: xxx"
101424     ** error if pSelect reads from a CTE named "xxx".  */
101425     return 0;
101426   }
101427   if( sqlite3TriggerList(pParse, pDest) ){
101428     return 0;   /* tab1 must not have triggers */
101429   }
101430 #ifndef SQLITE_OMIT_VIRTUALTABLE
101431   if( pDest->tabFlags & TF_Virtual ){
101432     return 0;   /* tab1 must not be a virtual table */
101433   }
101434 #endif
101435   if( onError==OE_Default ){
101436     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
101437     if( onError==OE_Default ) onError = OE_Abort;
101438   }
101439   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
101440   if( pSelect->pSrc->nSrc!=1 ){
101441     return 0;   /* FROM clause must have exactly one term */
101442   }
101443   if( pSelect->pSrc->a[0].pSelect ){
101444     return 0;   /* FROM clause cannot contain a subquery */
101445   }
101446   if( pSelect->pWhere ){
101447     return 0;   /* SELECT may not have a WHERE clause */
101448   }
101449   if( pSelect->pOrderBy ){
101450     return 0;   /* SELECT may not have an ORDER BY clause */
101451   }
101452   /* Do not need to test for a HAVING clause.  If HAVING is present but
101453   ** there is no ORDER BY, we will get an error. */
101454   if( pSelect->pGroupBy ){
101455     return 0;   /* SELECT may not have a GROUP BY clause */
101456   }
101457   if( pSelect->pLimit ){
101458     return 0;   /* SELECT may not have a LIMIT clause */
101459   }
101460   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
101461   if( pSelect->pPrior ){
101462     return 0;   /* SELECT may not be a compound query */
101463   }
101464   if( pSelect->selFlags & SF_Distinct ){
101465     return 0;   /* SELECT may not be DISTINCT */
101466   }
101467   pEList = pSelect->pEList;
101468   assert( pEList!=0 );
101469   if( pEList->nExpr!=1 ){
101470     return 0;   /* The result set must have exactly one column */
101471   }
101472   assert( pEList->a[0].pExpr );
101473   if( pEList->a[0].pExpr->op!=TK_ALL ){
101474     return 0;   /* The result set must be the special operator "*" */
101475   }
101476 
101477   /* At this point we have established that the statement is of the
101478   ** correct syntactic form to participate in this optimization.  Now
101479   ** we have to check the semantics.
101480   */
101481   pItem = pSelect->pSrc->a;
101482   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
101483   if( pSrc==0 ){
101484     return 0;   /* FROM clause does not contain a real table */
101485   }
101486   if( pSrc==pDest ){
101487     return 0;   /* tab1 and tab2 may not be the same table */
101488   }
101489   if( HasRowid(pDest)!=HasRowid(pSrc) ){
101490     return 0;   /* source and destination must both be WITHOUT ROWID or not */
101491   }
101492 #ifndef SQLITE_OMIT_VIRTUALTABLE
101493   if( pSrc->tabFlags & TF_Virtual ){
101494     return 0;   /* tab2 must not be a virtual table */
101495   }
101496 #endif
101497   if( pSrc->pSelect ){
101498     return 0;   /* tab2 may not be a view */
101499   }
101500   if( pDest->nCol!=pSrc->nCol ){
101501     return 0;   /* Number of columns must be the same in tab1 and tab2 */
101502   }
101503   if( pDest->iPKey!=pSrc->iPKey ){
101504     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
101505   }
101506   for(i=0; i<pDest->nCol; i++){
101507     Column *pDestCol = &pDest->aCol[i];
101508     Column *pSrcCol = &pSrc->aCol[i];
101509     if( pDestCol->affinity!=pSrcCol->affinity ){
101510       return 0;    /* Affinity must be the same on all columns */
101511     }
101512     if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
101513       return 0;    /* Collating sequence must be the same on all columns */
101514     }
101515     if( pDestCol->notNull && !pSrcCol->notNull ){
101516       return 0;    /* tab2 must be NOT NULL if tab1 is */
101517     }
101518     /* Default values for second and subsequent columns need to match. */
101519     if( i>0
101520      && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
101521          || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
101522     ){
101523       return 0;    /* Default values must be the same for all columns */
101524     }
101525   }
101526   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
101527     if( IsUniqueIndex(pDestIdx) ){
101528       destHasUniqueIdx = 1;
101529     }
101530     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
101531       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
101532     }
101533     if( pSrcIdx==0 ){
101534       return 0;    /* pDestIdx has no corresponding index in pSrc */
101535     }
101536   }
101537 #ifndef SQLITE_OMIT_CHECK
101538   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
101539     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
101540   }
101541 #endif
101542 #ifndef SQLITE_OMIT_FOREIGN_KEY
101543   /* Disallow the transfer optimization if the destination table constains
101544   ** any foreign key constraints.  This is more restrictive than necessary.
101545   ** But the main beneficiary of the transfer optimization is the VACUUM
101546   ** command, and the VACUUM command disables foreign key constraints.  So
101547   ** the extra complication to make this rule less restrictive is probably
101548   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
101549   */
101550   if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
101551     return 0;
101552   }
101553 #endif
101554   if( (db->flags & SQLITE_CountRows)!=0 ){
101555     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
101556   }
101557 
101558   /* If we get this far, it means that the xfer optimization is at
101559   ** least a possibility, though it might only work if the destination
101560   ** table (tab1) is initially empty.
101561   */
101562 #ifdef SQLITE_TEST
101563   sqlite3_xferopt_count++;
101564 #endif
101565   iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
101566   v = sqlite3GetVdbe(pParse);
101567   sqlite3CodeVerifySchema(pParse, iDbSrc);
101568   iSrc = pParse->nTab++;
101569   iDest = pParse->nTab++;
101570   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
101571   regData = sqlite3GetTempReg(pParse);
101572   regRowid = sqlite3GetTempReg(pParse);
101573   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
101574   assert( HasRowid(pDest) || destHasUniqueIdx );
101575   if( (db->flags & SQLITE_Vacuum)==0 && (
101576       (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
101577    || destHasUniqueIdx                              /* (2) */
101578    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
101579   )){
101580     /* In some circumstances, we are able to run the xfer optimization
101581     ** only if the destination table is initially empty. Unless the
101582     ** SQLITE_Vacuum flag is set, this block generates code to make
101583     ** that determination. If SQLITE_Vacuum is set, then the destination
101584     ** table is always empty.
101585     **
101586     ** Conditions under which the destination must be empty:
101587     **
101588     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
101589     **     (If the destination is not initially empty, the rowid fields
101590     **     of index entries might need to change.)
101591     **
101592     ** (2) The destination has a unique index.  (The xfer optimization
101593     **     is unable to test uniqueness.)
101594     **
101595     ** (3) onError is something other than OE_Abort and OE_Rollback.
101596     */
101597     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
101598     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
101599     sqlite3VdbeJumpHere(v, addr1);
101600   }
101601   if( HasRowid(pSrc) ){
101602     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
101603     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
101604     if( pDest->iPKey>=0 ){
101605       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
101606       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
101607       VdbeCoverage(v);
101608       sqlite3RowidConstraint(pParse, onError, pDest);
101609       sqlite3VdbeJumpHere(v, addr2);
101610       autoIncStep(pParse, regAutoinc, regRowid);
101611     }else if( pDest->pIndex==0 ){
101612       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
101613     }else{
101614       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
101615       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
101616     }
101617     sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
101618     sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
101619     sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
101620     sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
101621     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
101622     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
101623     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
101624   }else{
101625     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
101626     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
101627   }
101628   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
101629     u8 useSeekResult = 0;
101630     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
101631       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
101632     }
101633     assert( pSrcIdx );
101634     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
101635     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
101636     VdbeComment((v, "%s", pSrcIdx->zName));
101637     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
101638     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
101639     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
101640     VdbeComment((v, "%s", pDestIdx->zName));
101641     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
101642     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
101643     if( db->flags & SQLITE_Vacuum ){
101644       /* This INSERT command is part of a VACUUM operation, which guarantees
101645       ** that the destination table is empty. If all indexed columns use
101646       ** collation sequence BINARY, then it can also be assumed that the
101647       ** index will be populated by inserting keys in strictly sorted
101648       ** order. In this case, instead of seeking within the b-tree as part
101649       ** of every OP_IdxInsert opcode, an OP_Last is added before the
101650       ** OP_IdxInsert to seek to the point within the b-tree where each key
101651       ** should be inserted. This is faster.
101652       **
101653       ** If any of the indexed columns use a collation sequence other than
101654       ** BINARY, this optimization is disabled. This is because the user
101655       ** might change the definition of a collation sequence and then run
101656       ** a VACUUM command. In that case keys may not be written in strictly
101657       ** sorted order.  */
101658       for(i=0; i<pSrcIdx->nColumn; i++){
101659         char *zColl = pSrcIdx->azColl[i];
101660         assert( zColl!=0 );
101661         if( sqlite3_stricmp("BINARY", zColl) ) break;
101662       }
101663       if( i==pSrcIdx->nColumn ){
101664         useSeekResult = OPFLAG_USESEEKRESULT;
101665         sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
101666       }
101667     }
101668     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
101669     sqlite3VdbeChangeP5(v, useSeekResult);
101670     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
101671     sqlite3VdbeJumpHere(v, addr1);
101672     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
101673     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
101674   }
101675   if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
101676   sqlite3ReleaseTempReg(pParse, regRowid);
101677   sqlite3ReleaseTempReg(pParse, regData);
101678   if( emptyDestTest ){
101679     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
101680     sqlite3VdbeJumpHere(v, emptyDestTest);
101681     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
101682     return 0;
101683   }else{
101684     return 1;
101685   }
101686 }
101687 #endif /* SQLITE_OMIT_XFER_OPT */
101688 
101689 /************** End of insert.c **********************************************/
101690 /************** Begin file legacy.c ******************************************/
101691 /*
101692 ** 2001 September 15
101693 **
101694 ** The author disclaims copyright to this source code.  In place of
101695 ** a legal notice, here is a blessing:
101696 **
101697 **    May you do good and not evil.
101698 **    May you find forgiveness for yourself and forgive others.
101699 **    May you share freely, never taking more than you give.
101700 **
101701 *************************************************************************
101702 ** Main file for the SQLite library.  The routines in this file
101703 ** implement the programmer interface to the library.  Routines in
101704 ** other files are for internal use by SQLite and should not be
101705 ** accessed by users of the library.
101706 */
101707 
101708 
101709 /*
101710 ** Execute SQL code.  Return one of the SQLITE_ success/failure
101711 ** codes.  Also write an error message into memory obtained from
101712 ** malloc() and make *pzErrMsg point to that message.
101713 **
101714 ** If the SQL is a query, then for each row in the query result
101715 ** the xCallback() function is called.  pArg becomes the first
101716 ** argument to xCallback().  If xCallback=NULL then no callback
101717 ** is invoked, even for queries.
101718 */
101719 SQLITE_API int SQLITE_STDCALL sqlite3_exec(
101720   sqlite3 *db,                /* The database on which the SQL executes */
101721   const char *zSql,           /* The SQL to be executed */
101722   sqlite3_callback xCallback, /* Invoke this callback routine */
101723   void *pArg,                 /* First argument to xCallback() */
101724   char **pzErrMsg             /* Write error messages here */
101725 ){
101726   int rc = SQLITE_OK;         /* Return code */
101727   const char *zLeftover;      /* Tail of unprocessed SQL */
101728   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
101729   char **azCols = 0;          /* Names of result columns */
101730   int callbackIsInit;         /* True if callback data is initialized */
101731 
101732   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
101733   if( zSql==0 ) zSql = "";
101734 
101735   sqlite3_mutex_enter(db->mutex);
101736   sqlite3Error(db, SQLITE_OK);
101737   while( rc==SQLITE_OK && zSql[0] ){
101738     int nCol;
101739     char **azVals = 0;
101740 
101741     pStmt = 0;
101742     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
101743     assert( rc==SQLITE_OK || pStmt==0 );
101744     if( rc!=SQLITE_OK ){
101745       continue;
101746     }
101747     if( !pStmt ){
101748       /* this happens for a comment or white-space */
101749       zSql = zLeftover;
101750       continue;
101751     }
101752 
101753     callbackIsInit = 0;
101754     nCol = sqlite3_column_count(pStmt);
101755 
101756     while( 1 ){
101757       int i;
101758       rc = sqlite3_step(pStmt);
101759 
101760       /* Invoke the callback function if required */
101761       if( xCallback && (SQLITE_ROW==rc ||
101762           (SQLITE_DONE==rc && !callbackIsInit
101763                            && db->flags&SQLITE_NullCallback)) ){
101764         if( !callbackIsInit ){
101765           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
101766           if( azCols==0 ){
101767             goto exec_out;
101768           }
101769           for(i=0; i<nCol; i++){
101770             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
101771             /* sqlite3VdbeSetColName() installs column names as UTF8
101772             ** strings so there is no way for sqlite3_column_name() to fail. */
101773             assert( azCols[i]!=0 );
101774           }
101775           callbackIsInit = 1;
101776         }
101777         if( rc==SQLITE_ROW ){
101778           azVals = &azCols[nCol];
101779           for(i=0; i<nCol; i++){
101780             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
101781             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
101782               db->mallocFailed = 1;
101783               goto exec_out;
101784             }
101785           }
101786         }
101787         if( xCallback(pArg, nCol, azVals, azCols) ){
101788           /* EVIDENCE-OF: R-38229-40159 If the callback function to
101789           ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
101790           ** return SQLITE_ABORT. */
101791           rc = SQLITE_ABORT;
101792           sqlite3VdbeFinalize((Vdbe *)pStmt);
101793           pStmt = 0;
101794           sqlite3Error(db, SQLITE_ABORT);
101795           goto exec_out;
101796         }
101797       }
101798 
101799       if( rc!=SQLITE_ROW ){
101800         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
101801         pStmt = 0;
101802         zSql = zLeftover;
101803         while( sqlite3Isspace(zSql[0]) ) zSql++;
101804         break;
101805       }
101806     }
101807 
101808     sqlite3DbFree(db, azCols);
101809     azCols = 0;
101810   }
101811 
101812 exec_out:
101813   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
101814   sqlite3DbFree(db, azCols);
101815 
101816   rc = sqlite3ApiExit(db, rc);
101817   if( rc!=SQLITE_OK && pzErrMsg ){
101818     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
101819     *pzErrMsg = sqlite3Malloc(nErrMsg);
101820     if( *pzErrMsg ){
101821       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
101822     }else{
101823       rc = SQLITE_NOMEM;
101824       sqlite3Error(db, SQLITE_NOMEM);
101825     }
101826   }else if( pzErrMsg ){
101827     *pzErrMsg = 0;
101828   }
101829 
101830   assert( (rc&db->errMask)==rc );
101831   sqlite3_mutex_leave(db->mutex);
101832   return rc;
101833 }
101834 
101835 /************** End of legacy.c **********************************************/
101836 /************** Begin file loadext.c *****************************************/
101837 /*
101838 ** 2006 June 7
101839 **
101840 ** The author disclaims copyright to this source code.  In place of
101841 ** a legal notice, here is a blessing:
101842 **
101843 **    May you do good and not evil.
101844 **    May you find forgiveness for yourself and forgive others.
101845 **    May you share freely, never taking more than you give.
101846 **
101847 *************************************************************************
101848 ** This file contains code used to dynamically load extensions into
101849 ** the SQLite library.
101850 */
101851 
101852 #ifndef SQLITE_CORE
101853   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
101854 #endif
101855 /************** Include sqlite3ext.h in the middle of loadext.c **************/
101856 /************** Begin file sqlite3ext.h **************************************/
101857 /*
101858 ** 2006 June 7
101859 **
101860 ** The author disclaims copyright to this source code.  In place of
101861 ** a legal notice, here is a blessing:
101862 **
101863 **    May you do good and not evil.
101864 **    May you find forgiveness for yourself and forgive others.
101865 **    May you share freely, never taking more than you give.
101866 **
101867 *************************************************************************
101868 ** This header file defines the SQLite interface for use by
101869 ** shared libraries that want to be imported as extensions into
101870 ** an SQLite instance.  Shared libraries that intend to be loaded
101871 ** as extensions by SQLite should #include this file instead of
101872 ** sqlite3.h.
101873 */
101874 #ifndef _SQLITE3EXT_H_
101875 #define _SQLITE3EXT_H_
101876 
101877 typedef struct sqlite3_api_routines sqlite3_api_routines;
101878 
101879 /*
101880 ** The following structure holds pointers to all of the SQLite API
101881 ** routines.
101882 **
101883 ** WARNING:  In order to maintain backwards compatibility, add new
101884 ** interfaces to the end of this structure only.  If you insert new
101885 ** interfaces in the middle of this structure, then older different
101886 ** versions of SQLite will not be able to load each other's shared
101887 ** libraries!
101888 */
101889 struct sqlite3_api_routines {
101890   void * (*aggregate_context)(sqlite3_context*,int nBytes);
101891   int  (*aggregate_count)(sqlite3_context*);
101892   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
101893   int  (*bind_double)(sqlite3_stmt*,int,double);
101894   int  (*bind_int)(sqlite3_stmt*,int,int);
101895   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
101896   int  (*bind_null)(sqlite3_stmt*,int);
101897   int  (*bind_parameter_count)(sqlite3_stmt*);
101898   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
101899   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
101900   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
101901   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
101902   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
101903   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
101904   int  (*busy_timeout)(sqlite3*,int ms);
101905   int  (*changes)(sqlite3*);
101906   int  (*close)(sqlite3*);
101907   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
101908                            int eTextRep,const char*));
101909   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
101910                              int eTextRep,const void*));
101911   const void * (*column_blob)(sqlite3_stmt*,int iCol);
101912   int  (*column_bytes)(sqlite3_stmt*,int iCol);
101913   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
101914   int  (*column_count)(sqlite3_stmt*pStmt);
101915   const char * (*column_database_name)(sqlite3_stmt*,int);
101916   const void * (*column_database_name16)(sqlite3_stmt*,int);
101917   const char * (*column_decltype)(sqlite3_stmt*,int i);
101918   const void * (*column_decltype16)(sqlite3_stmt*,int);
101919   double  (*column_double)(sqlite3_stmt*,int iCol);
101920   int  (*column_int)(sqlite3_stmt*,int iCol);
101921   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
101922   const char * (*column_name)(sqlite3_stmt*,int);
101923   const void * (*column_name16)(sqlite3_stmt*,int);
101924   const char * (*column_origin_name)(sqlite3_stmt*,int);
101925   const void * (*column_origin_name16)(sqlite3_stmt*,int);
101926   const char * (*column_table_name)(sqlite3_stmt*,int);
101927   const void * (*column_table_name16)(sqlite3_stmt*,int);
101928   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
101929   const void * (*column_text16)(sqlite3_stmt*,int iCol);
101930   int  (*column_type)(sqlite3_stmt*,int iCol);
101931   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
101932   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
101933   int  (*complete)(const char*sql);
101934   int  (*complete16)(const void*sql);
101935   int  (*create_collation)(sqlite3*,const char*,int,void*,
101936                            int(*)(void*,int,const void*,int,const void*));
101937   int  (*create_collation16)(sqlite3*,const void*,int,void*,
101938                              int(*)(void*,int,const void*,int,const void*));
101939   int  (*create_function)(sqlite3*,const char*,int,int,void*,
101940                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
101941                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
101942                           void (*xFinal)(sqlite3_context*));
101943   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
101944                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
101945                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
101946                             void (*xFinal)(sqlite3_context*));
101947   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
101948   int  (*data_count)(sqlite3_stmt*pStmt);
101949   sqlite3 * (*db_handle)(sqlite3_stmt*);
101950   int (*declare_vtab)(sqlite3*,const char*);
101951   int  (*enable_shared_cache)(int);
101952   int  (*errcode)(sqlite3*db);
101953   const char * (*errmsg)(sqlite3*);
101954   const void * (*errmsg16)(sqlite3*);
101955   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
101956   int  (*expired)(sqlite3_stmt*);
101957   int  (*finalize)(sqlite3_stmt*pStmt);
101958   void  (*free)(void*);
101959   void  (*free_table)(char**result);
101960   int  (*get_autocommit)(sqlite3*);
101961   void * (*get_auxdata)(sqlite3_context*,int);
101962   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
101963   int  (*global_recover)(void);
101964   void  (*interruptx)(sqlite3*);
101965   sqlite_int64  (*last_insert_rowid)(sqlite3*);
101966   const char * (*libversion)(void);
101967   int  (*libversion_number)(void);
101968   void *(*malloc)(int);
101969   char * (*mprintf)(const char*,...);
101970   int  (*open)(const char*,sqlite3**);
101971   int  (*open16)(const void*,sqlite3**);
101972   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
101973   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
101974   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
101975   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
101976   void *(*realloc)(void*,int);
101977   int  (*reset)(sqlite3_stmt*pStmt);
101978   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
101979   void  (*result_double)(sqlite3_context*,double);
101980   void  (*result_error)(sqlite3_context*,const char*,int);
101981   void  (*result_error16)(sqlite3_context*,const void*,int);
101982   void  (*result_int)(sqlite3_context*,int);
101983   void  (*result_int64)(sqlite3_context*,sqlite_int64);
101984   void  (*result_null)(sqlite3_context*);
101985   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
101986   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
101987   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
101988   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
101989   void  (*result_value)(sqlite3_context*,sqlite3_value*);
101990   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
101991   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
101992                          const char*,const char*),void*);
101993   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
101994   char * (*snprintf)(int,char*,const char*,...);
101995   int  (*step)(sqlite3_stmt*);
101996   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
101997                                 char const**,char const**,int*,int*,int*);
101998   void  (*thread_cleanup)(void);
101999   int  (*total_changes)(sqlite3*);
102000   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
102001   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
102002   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
102003                                          sqlite_int64),void*);
102004   void * (*user_data)(sqlite3_context*);
102005   const void * (*value_blob)(sqlite3_value*);
102006   int  (*value_bytes)(sqlite3_value*);
102007   int  (*value_bytes16)(sqlite3_value*);
102008   double  (*value_double)(sqlite3_value*);
102009   int  (*value_int)(sqlite3_value*);
102010   sqlite_int64  (*value_int64)(sqlite3_value*);
102011   int  (*value_numeric_type)(sqlite3_value*);
102012   const unsigned char * (*value_text)(sqlite3_value*);
102013   const void * (*value_text16)(sqlite3_value*);
102014   const void * (*value_text16be)(sqlite3_value*);
102015   const void * (*value_text16le)(sqlite3_value*);
102016   int  (*value_type)(sqlite3_value*);
102017   char *(*vmprintf)(const char*,va_list);
102018   /* Added ??? */
102019   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
102020   /* Added by 3.3.13 */
102021   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
102022   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
102023   int (*clear_bindings)(sqlite3_stmt*);
102024   /* Added by 3.4.1 */
102025   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
102026                           void (*xDestroy)(void *));
102027   /* Added by 3.5.0 */
102028   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
102029   int (*blob_bytes)(sqlite3_blob*);
102030   int (*blob_close)(sqlite3_blob*);
102031   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
102032                    int,sqlite3_blob**);
102033   int (*blob_read)(sqlite3_blob*,void*,int,int);
102034   int (*blob_write)(sqlite3_blob*,const void*,int,int);
102035   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
102036                              int(*)(void*,int,const void*,int,const void*),
102037                              void(*)(void*));
102038   int (*file_control)(sqlite3*,const char*,int,void*);
102039   sqlite3_int64 (*memory_highwater)(int);
102040   sqlite3_int64 (*memory_used)(void);
102041   sqlite3_mutex *(*mutex_alloc)(int);
102042   void (*mutex_enter)(sqlite3_mutex*);
102043   void (*mutex_free)(sqlite3_mutex*);
102044   void (*mutex_leave)(sqlite3_mutex*);
102045   int (*mutex_try)(sqlite3_mutex*);
102046   int (*open_v2)(const char*,sqlite3**,int,const char*);
102047   int (*release_memory)(int);
102048   void (*result_error_nomem)(sqlite3_context*);
102049   void (*result_error_toobig)(sqlite3_context*);
102050   int (*sleep)(int);
102051   void (*soft_heap_limit)(int);
102052   sqlite3_vfs *(*vfs_find)(const char*);
102053   int (*vfs_register)(sqlite3_vfs*,int);
102054   int (*vfs_unregister)(sqlite3_vfs*);
102055   int (*xthreadsafe)(void);
102056   void (*result_zeroblob)(sqlite3_context*,int);
102057   void (*result_error_code)(sqlite3_context*,int);
102058   int (*test_control)(int, ...);
102059   void (*randomness)(int,void*);
102060   sqlite3 *(*context_db_handle)(sqlite3_context*);
102061   int (*extended_result_codes)(sqlite3*,int);
102062   int (*limit)(sqlite3*,int,int);
102063   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
102064   const char *(*sql)(sqlite3_stmt*);
102065   int (*status)(int,int*,int*,int);
102066   int (*backup_finish)(sqlite3_backup*);
102067   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
102068   int (*backup_pagecount)(sqlite3_backup*);
102069   int (*backup_remaining)(sqlite3_backup*);
102070   int (*backup_step)(sqlite3_backup*,int);
102071   const char *(*compileoption_get)(int);
102072   int (*compileoption_used)(const char*);
102073   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
102074                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
102075                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
102076                             void (*xFinal)(sqlite3_context*),
102077                             void(*xDestroy)(void*));
102078   int (*db_config)(sqlite3*,int,...);
102079   sqlite3_mutex *(*db_mutex)(sqlite3*);
102080   int (*db_status)(sqlite3*,int,int*,int*,int);
102081   int (*extended_errcode)(sqlite3*);
102082   void (*log)(int,const char*,...);
102083   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
102084   const char *(*sourceid)(void);
102085   int (*stmt_status)(sqlite3_stmt*,int,int);
102086   int (*strnicmp)(const char*,const char*,int);
102087   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
102088   int (*wal_autocheckpoint)(sqlite3*,int);
102089   int (*wal_checkpoint)(sqlite3*,const char*);
102090   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
102091   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
102092   int (*vtab_config)(sqlite3*,int op,...);
102093   int (*vtab_on_conflict)(sqlite3*);
102094   /* Version 3.7.16 and later */
102095   int (*close_v2)(sqlite3*);
102096   const char *(*db_filename)(sqlite3*,const char*);
102097   int (*db_readonly)(sqlite3*,const char*);
102098   int (*db_release_memory)(sqlite3*);
102099   const char *(*errstr)(int);
102100   int (*stmt_busy)(sqlite3_stmt*);
102101   int (*stmt_readonly)(sqlite3_stmt*);
102102   int (*stricmp)(const char*,const char*);
102103   int (*uri_boolean)(const char*,const char*,int);
102104   sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
102105   const char *(*uri_parameter)(const char*,const char*);
102106   char *(*vsnprintf)(int,char*,const char*,va_list);
102107   int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
102108   /* Version 3.8.7 and later */
102109   int (*auto_extension)(void(*)(void));
102110   int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
102111                      void(*)(void*));
102112   int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
102113                       void(*)(void*),unsigned char);
102114   int (*cancel_auto_extension)(void(*)(void));
102115   int (*load_extension)(sqlite3*,const char*,const char*,char**);
102116   void *(*malloc64)(sqlite3_uint64);
102117   sqlite3_uint64 (*msize)(void*);
102118   void *(*realloc64)(void*,sqlite3_uint64);
102119   void (*reset_auto_extension)(void);
102120   void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
102121                         void(*)(void*));
102122   void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
102123                          void(*)(void*), unsigned char);
102124   int (*strglob)(const char*,const char*);
102125 };
102126 
102127 /*
102128 ** The following macros redefine the API routines so that they are
102129 ** redirected through the global sqlite3_api structure.
102130 **
102131 ** This header file is also used by the loadext.c source file
102132 ** (part of the main SQLite library - not an extension) so that
102133 ** it can get access to the sqlite3_api_routines structure
102134 ** definition.  But the main library does not want to redefine
102135 ** the API.  So the redefinition macros are only valid if the
102136 ** SQLITE_CORE macros is undefined.
102137 */
102138 #ifndef SQLITE_CORE
102139 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
102140 #ifndef SQLITE_OMIT_DEPRECATED
102141 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
102142 #endif
102143 #define sqlite3_bind_blob              sqlite3_api->bind_blob
102144 #define sqlite3_bind_double            sqlite3_api->bind_double
102145 #define sqlite3_bind_int               sqlite3_api->bind_int
102146 #define sqlite3_bind_int64             sqlite3_api->bind_int64
102147 #define sqlite3_bind_null              sqlite3_api->bind_null
102148 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
102149 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
102150 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
102151 #define sqlite3_bind_text              sqlite3_api->bind_text
102152 #define sqlite3_bind_text16            sqlite3_api->bind_text16
102153 #define sqlite3_bind_value             sqlite3_api->bind_value
102154 #define sqlite3_busy_handler           sqlite3_api->busy_handler
102155 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
102156 #define sqlite3_changes                sqlite3_api->changes
102157 #define sqlite3_close                  sqlite3_api->close
102158 #define sqlite3_collation_needed       sqlite3_api->collation_needed
102159 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
102160 #define sqlite3_column_blob            sqlite3_api->column_blob
102161 #define sqlite3_column_bytes           sqlite3_api->column_bytes
102162 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
102163 #define sqlite3_column_count           sqlite3_api->column_count
102164 #define sqlite3_column_database_name   sqlite3_api->column_database_name
102165 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
102166 #define sqlite3_column_decltype        sqlite3_api->column_decltype
102167 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
102168 #define sqlite3_column_double          sqlite3_api->column_double
102169 #define sqlite3_column_int             sqlite3_api->column_int
102170 #define sqlite3_column_int64           sqlite3_api->column_int64
102171 #define sqlite3_column_name            sqlite3_api->column_name
102172 #define sqlite3_column_name16          sqlite3_api->column_name16
102173 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
102174 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
102175 #define sqlite3_column_table_name      sqlite3_api->column_table_name
102176 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
102177 #define sqlite3_column_text            sqlite3_api->column_text
102178 #define sqlite3_column_text16          sqlite3_api->column_text16
102179 #define sqlite3_column_type            sqlite3_api->column_type
102180 #define sqlite3_column_value           sqlite3_api->column_value
102181 #define sqlite3_commit_hook            sqlite3_api->commit_hook
102182 #define sqlite3_complete               sqlite3_api->complete
102183 #define sqlite3_complete16             sqlite3_api->complete16
102184 #define sqlite3_create_collation       sqlite3_api->create_collation
102185 #define sqlite3_create_collation16     sqlite3_api->create_collation16
102186 #define sqlite3_create_function        sqlite3_api->create_function
102187 #define sqlite3_create_function16      sqlite3_api->create_function16
102188 #define sqlite3_create_module          sqlite3_api->create_module
102189 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
102190 #define sqlite3_data_count             sqlite3_api->data_count
102191 #define sqlite3_db_handle              sqlite3_api->db_handle
102192 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
102193 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
102194 #define sqlite3_errcode                sqlite3_api->errcode
102195 #define sqlite3_errmsg                 sqlite3_api->errmsg
102196 #define sqlite3_errmsg16               sqlite3_api->errmsg16
102197 #define sqlite3_exec                   sqlite3_api->exec
102198 #ifndef SQLITE_OMIT_DEPRECATED
102199 #define sqlite3_expired                sqlite3_api->expired
102200 #endif
102201 #define sqlite3_finalize               sqlite3_api->finalize
102202 #define sqlite3_free                   sqlite3_api->free
102203 #define sqlite3_free_table             sqlite3_api->free_table
102204 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
102205 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
102206 #define sqlite3_get_table              sqlite3_api->get_table
102207 #ifndef SQLITE_OMIT_DEPRECATED
102208 #define sqlite3_global_recover         sqlite3_api->global_recover
102209 #endif
102210 #define sqlite3_interrupt              sqlite3_api->interruptx
102211 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
102212 #define sqlite3_libversion             sqlite3_api->libversion
102213 #define sqlite3_libversion_number      sqlite3_api->libversion_number
102214 #define sqlite3_malloc                 sqlite3_api->malloc
102215 #define sqlite3_mprintf                sqlite3_api->mprintf
102216 #define sqlite3_open                   sqlite3_api->open
102217 #define sqlite3_open16                 sqlite3_api->open16
102218 #define sqlite3_prepare                sqlite3_api->prepare
102219 #define sqlite3_prepare16              sqlite3_api->prepare16
102220 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
102221 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
102222 #define sqlite3_profile                sqlite3_api->profile
102223 #define sqlite3_progress_handler       sqlite3_api->progress_handler
102224 #define sqlite3_realloc                sqlite3_api->realloc
102225 #define sqlite3_reset                  sqlite3_api->reset
102226 #define sqlite3_result_blob            sqlite3_api->result_blob
102227 #define sqlite3_result_double          sqlite3_api->result_double
102228 #define sqlite3_result_error           sqlite3_api->result_error
102229 #define sqlite3_result_error16         sqlite3_api->result_error16
102230 #define sqlite3_result_int             sqlite3_api->result_int
102231 #define sqlite3_result_int64           sqlite3_api->result_int64
102232 #define sqlite3_result_null            sqlite3_api->result_null
102233 #define sqlite3_result_text            sqlite3_api->result_text
102234 #define sqlite3_result_text16          sqlite3_api->result_text16
102235 #define sqlite3_result_text16be        sqlite3_api->result_text16be
102236 #define sqlite3_result_text16le        sqlite3_api->result_text16le
102237 #define sqlite3_result_value           sqlite3_api->result_value
102238 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
102239 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
102240 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
102241 #define sqlite3_snprintf               sqlite3_api->snprintf
102242 #define sqlite3_step                   sqlite3_api->step
102243 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
102244 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
102245 #define sqlite3_total_changes          sqlite3_api->total_changes
102246 #define sqlite3_trace                  sqlite3_api->trace
102247 #ifndef SQLITE_OMIT_DEPRECATED
102248 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
102249 #endif
102250 #define sqlite3_update_hook            sqlite3_api->update_hook
102251 #define sqlite3_user_data              sqlite3_api->user_data
102252 #define sqlite3_value_blob             sqlite3_api->value_blob
102253 #define sqlite3_value_bytes            sqlite3_api->value_bytes
102254 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
102255 #define sqlite3_value_double           sqlite3_api->value_double
102256 #define sqlite3_value_int              sqlite3_api->value_int
102257 #define sqlite3_value_int64            sqlite3_api->value_int64
102258 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
102259 #define sqlite3_value_text             sqlite3_api->value_text
102260 #define sqlite3_value_text16           sqlite3_api->value_text16
102261 #define sqlite3_value_text16be         sqlite3_api->value_text16be
102262 #define sqlite3_value_text16le         sqlite3_api->value_text16le
102263 #define sqlite3_value_type             sqlite3_api->value_type
102264 #define sqlite3_vmprintf               sqlite3_api->vmprintf
102265 #define sqlite3_overload_function      sqlite3_api->overload_function
102266 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
102267 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
102268 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
102269 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
102270 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
102271 #define sqlite3_blob_close             sqlite3_api->blob_close
102272 #define sqlite3_blob_open              sqlite3_api->blob_open
102273 #define sqlite3_blob_read              sqlite3_api->blob_read
102274 #define sqlite3_blob_write             sqlite3_api->blob_write
102275 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
102276 #define sqlite3_file_control           sqlite3_api->file_control
102277 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
102278 #define sqlite3_memory_used            sqlite3_api->memory_used
102279 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
102280 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
102281 #define sqlite3_mutex_free             sqlite3_api->mutex_free
102282 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
102283 #define sqlite3_mutex_try              sqlite3_api->mutex_try
102284 #define sqlite3_open_v2                sqlite3_api->open_v2
102285 #define sqlite3_release_memory         sqlite3_api->release_memory
102286 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
102287 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
102288 #define sqlite3_sleep                  sqlite3_api->sleep
102289 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
102290 #define sqlite3_vfs_find               sqlite3_api->vfs_find
102291 #define sqlite3_vfs_register           sqlite3_api->vfs_register
102292 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
102293 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
102294 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
102295 #define sqlite3_result_error_code      sqlite3_api->result_error_code
102296 #define sqlite3_test_control           sqlite3_api->test_control
102297 #define sqlite3_randomness             sqlite3_api->randomness
102298 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
102299 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
102300 #define sqlite3_limit                  sqlite3_api->limit
102301 #define sqlite3_next_stmt              sqlite3_api->next_stmt
102302 #define sqlite3_sql                    sqlite3_api->sql
102303 #define sqlite3_status                 sqlite3_api->status
102304 #define sqlite3_backup_finish          sqlite3_api->backup_finish
102305 #define sqlite3_backup_init            sqlite3_api->backup_init
102306 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
102307 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
102308 #define sqlite3_backup_step            sqlite3_api->backup_step
102309 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
102310 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
102311 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
102312 #define sqlite3_db_config              sqlite3_api->db_config
102313 #define sqlite3_db_mutex               sqlite3_api->db_mutex
102314 #define sqlite3_db_status              sqlite3_api->db_status
102315 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
102316 #define sqlite3_log                    sqlite3_api->log
102317 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
102318 #define sqlite3_sourceid               sqlite3_api->sourceid
102319 #define sqlite3_stmt_status            sqlite3_api->stmt_status
102320 #define sqlite3_strnicmp               sqlite3_api->strnicmp
102321 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
102322 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
102323 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
102324 #define sqlite3_wal_hook               sqlite3_api->wal_hook
102325 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
102326 #define sqlite3_vtab_config            sqlite3_api->vtab_config
102327 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
102328 /* Version 3.7.16 and later */
102329 #define sqlite3_close_v2               sqlite3_api->close_v2
102330 #define sqlite3_db_filename            sqlite3_api->db_filename
102331 #define sqlite3_db_readonly            sqlite3_api->db_readonly
102332 #define sqlite3_db_release_memory      sqlite3_api->db_release_memory
102333 #define sqlite3_errstr                 sqlite3_api->errstr
102334 #define sqlite3_stmt_busy              sqlite3_api->stmt_busy
102335 #define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
102336 #define sqlite3_stricmp                sqlite3_api->stricmp
102337 #define sqlite3_uri_boolean            sqlite3_api->uri_boolean
102338 #define sqlite3_uri_int64              sqlite3_api->uri_int64
102339 #define sqlite3_uri_parameter          sqlite3_api->uri_parameter
102340 #define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
102341 #define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
102342 /* Version 3.8.7 and later */
102343 #define sqlite3_auto_extension         sqlite3_api->auto_extension
102344 #define sqlite3_bind_blob64            sqlite3_api->bind_blob64
102345 #define sqlite3_bind_text64            sqlite3_api->bind_text64
102346 #define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
102347 #define sqlite3_load_extension         sqlite3_api->load_extension
102348 #define sqlite3_malloc64               sqlite3_api->malloc64
102349 #define sqlite3_msize                  sqlite3_api->msize
102350 #define sqlite3_realloc64              sqlite3_api->realloc64
102351 #define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
102352 #define sqlite3_result_blob64          sqlite3_api->result_blob64
102353 #define sqlite3_result_text64          sqlite3_api->result_text64
102354 #define sqlite3_strglob                sqlite3_api->strglob
102355 #endif /* SQLITE_CORE */
102356 
102357 #ifndef SQLITE_CORE
102358   /* This case when the file really is being compiled as a loadable
102359   ** extension */
102360 # define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
102361 # define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
102362 # define SQLITE_EXTENSION_INIT3     \
102363     extern const sqlite3_api_routines *sqlite3_api;
102364 #else
102365   /* This case when the file is being statically linked into the
102366   ** application */
102367 # define SQLITE_EXTENSION_INIT1     /*no-op*/
102368 # define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
102369 # define SQLITE_EXTENSION_INIT3     /*no-op*/
102370 #endif
102371 
102372 #endif /* _SQLITE3EXT_H_ */
102373 
102374 /************** End of sqlite3ext.h ******************************************/
102375 /************** Continuing where we left off in loadext.c ********************/
102376 /* #include <string.h> */
102377 
102378 #ifndef SQLITE_OMIT_LOAD_EXTENSION
102379 
102380 /*
102381 ** Some API routines are omitted when various features are
102382 ** excluded from a build of SQLite.  Substitute a NULL pointer
102383 ** for any missing APIs.
102384 */
102385 #ifndef SQLITE_ENABLE_COLUMN_METADATA
102386 # define sqlite3_column_database_name   0
102387 # define sqlite3_column_database_name16 0
102388 # define sqlite3_column_table_name      0
102389 # define sqlite3_column_table_name16    0
102390 # define sqlite3_column_origin_name     0
102391 # define sqlite3_column_origin_name16   0
102392 #endif
102393 
102394 #ifdef SQLITE_OMIT_AUTHORIZATION
102395 # define sqlite3_set_authorizer         0
102396 #endif
102397 
102398 #ifdef SQLITE_OMIT_UTF16
102399 # define sqlite3_bind_text16            0
102400 # define sqlite3_collation_needed16     0
102401 # define sqlite3_column_decltype16      0
102402 # define sqlite3_column_name16          0
102403 # define sqlite3_column_text16          0
102404 # define sqlite3_complete16             0
102405 # define sqlite3_create_collation16     0
102406 # define sqlite3_create_function16      0
102407 # define sqlite3_errmsg16               0
102408 # define sqlite3_open16                 0
102409 # define sqlite3_prepare16              0
102410 # define sqlite3_prepare16_v2           0
102411 # define sqlite3_result_error16         0
102412 # define sqlite3_result_text16          0
102413 # define sqlite3_result_text16be        0
102414 # define sqlite3_result_text16le        0
102415 # define sqlite3_value_text16           0
102416 # define sqlite3_value_text16be         0
102417 # define sqlite3_value_text16le         0
102418 # define sqlite3_column_database_name16 0
102419 # define sqlite3_column_table_name16    0
102420 # define sqlite3_column_origin_name16   0
102421 #endif
102422 
102423 #ifdef SQLITE_OMIT_COMPLETE
102424 # define sqlite3_complete 0
102425 # define sqlite3_complete16 0
102426 #endif
102427 
102428 #ifdef SQLITE_OMIT_DECLTYPE
102429 # define sqlite3_column_decltype16      0
102430 # define sqlite3_column_decltype        0
102431 #endif
102432 
102433 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
102434 # define sqlite3_progress_handler 0
102435 #endif
102436 
102437 #ifdef SQLITE_OMIT_VIRTUALTABLE
102438 # define sqlite3_create_module 0
102439 # define sqlite3_create_module_v2 0
102440 # define sqlite3_declare_vtab 0
102441 # define sqlite3_vtab_config 0
102442 # define sqlite3_vtab_on_conflict 0
102443 #endif
102444 
102445 #ifdef SQLITE_OMIT_SHARED_CACHE
102446 # define sqlite3_enable_shared_cache 0
102447 #endif
102448 
102449 #ifdef SQLITE_OMIT_TRACE
102450 # define sqlite3_profile       0
102451 # define sqlite3_trace         0
102452 #endif
102453 
102454 #ifdef SQLITE_OMIT_GET_TABLE
102455 # define sqlite3_free_table    0
102456 # define sqlite3_get_table     0
102457 #endif
102458 
102459 #ifdef SQLITE_OMIT_INCRBLOB
102460 #define sqlite3_bind_zeroblob  0
102461 #define sqlite3_blob_bytes     0
102462 #define sqlite3_blob_close     0
102463 #define sqlite3_blob_open      0
102464 #define sqlite3_blob_read      0
102465 #define sqlite3_blob_write     0
102466 #define sqlite3_blob_reopen    0
102467 #endif
102468 
102469 /*
102470 ** The following structure contains pointers to all SQLite API routines.
102471 ** A pointer to this structure is passed into extensions when they are
102472 ** loaded so that the extension can make calls back into the SQLite
102473 ** library.
102474 **
102475 ** When adding new APIs, add them to the bottom of this structure
102476 ** in order to preserve backwards compatibility.
102477 **
102478 ** Extensions that use newer APIs should first call the
102479 ** sqlite3_libversion_number() to make sure that the API they
102480 ** intend to use is supported by the library.  Extensions should
102481 ** also check to make sure that the pointer to the function is
102482 ** not NULL before calling it.
102483 */
102484 static const sqlite3_api_routines sqlite3Apis = {
102485   sqlite3_aggregate_context,
102486 #ifndef SQLITE_OMIT_DEPRECATED
102487   sqlite3_aggregate_count,
102488 #else
102489   0,
102490 #endif
102491   sqlite3_bind_blob,
102492   sqlite3_bind_double,
102493   sqlite3_bind_int,
102494   sqlite3_bind_int64,
102495   sqlite3_bind_null,
102496   sqlite3_bind_parameter_count,
102497   sqlite3_bind_parameter_index,
102498   sqlite3_bind_parameter_name,
102499   sqlite3_bind_text,
102500   sqlite3_bind_text16,
102501   sqlite3_bind_value,
102502   sqlite3_busy_handler,
102503   sqlite3_busy_timeout,
102504   sqlite3_changes,
102505   sqlite3_close,
102506   sqlite3_collation_needed,
102507   sqlite3_collation_needed16,
102508   sqlite3_column_blob,
102509   sqlite3_column_bytes,
102510   sqlite3_column_bytes16,
102511   sqlite3_column_count,
102512   sqlite3_column_database_name,
102513   sqlite3_column_database_name16,
102514   sqlite3_column_decltype,
102515   sqlite3_column_decltype16,
102516   sqlite3_column_double,
102517   sqlite3_column_int,
102518   sqlite3_column_int64,
102519   sqlite3_column_name,
102520   sqlite3_column_name16,
102521   sqlite3_column_origin_name,
102522   sqlite3_column_origin_name16,
102523   sqlite3_column_table_name,
102524   sqlite3_column_table_name16,
102525   sqlite3_column_text,
102526   sqlite3_column_text16,
102527   sqlite3_column_type,
102528   sqlite3_column_value,
102529   sqlite3_commit_hook,
102530   sqlite3_complete,
102531   sqlite3_complete16,
102532   sqlite3_create_collation,
102533   sqlite3_create_collation16,
102534   sqlite3_create_function,
102535   sqlite3_create_function16,
102536   sqlite3_create_module,
102537   sqlite3_data_count,
102538   sqlite3_db_handle,
102539   sqlite3_declare_vtab,
102540   sqlite3_enable_shared_cache,
102541   sqlite3_errcode,
102542   sqlite3_errmsg,
102543   sqlite3_errmsg16,
102544   sqlite3_exec,
102545 #ifndef SQLITE_OMIT_DEPRECATED
102546   sqlite3_expired,
102547 #else
102548   0,
102549 #endif
102550   sqlite3_finalize,
102551   sqlite3_free,
102552   sqlite3_free_table,
102553   sqlite3_get_autocommit,
102554   sqlite3_get_auxdata,
102555   sqlite3_get_table,
102556   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
102557   sqlite3_interrupt,
102558   sqlite3_last_insert_rowid,
102559   sqlite3_libversion,
102560   sqlite3_libversion_number,
102561   sqlite3_malloc,
102562   sqlite3_mprintf,
102563   sqlite3_open,
102564   sqlite3_open16,
102565   sqlite3_prepare,
102566   sqlite3_prepare16,
102567   sqlite3_profile,
102568   sqlite3_progress_handler,
102569   sqlite3_realloc,
102570   sqlite3_reset,
102571   sqlite3_result_blob,
102572   sqlite3_result_double,
102573   sqlite3_result_error,
102574   sqlite3_result_error16,
102575   sqlite3_result_int,
102576   sqlite3_result_int64,
102577   sqlite3_result_null,
102578   sqlite3_result_text,
102579   sqlite3_result_text16,
102580   sqlite3_result_text16be,
102581   sqlite3_result_text16le,
102582   sqlite3_result_value,
102583   sqlite3_rollback_hook,
102584   sqlite3_set_authorizer,
102585   sqlite3_set_auxdata,
102586   sqlite3_snprintf,
102587   sqlite3_step,
102588   sqlite3_table_column_metadata,
102589 #ifndef SQLITE_OMIT_DEPRECATED
102590   sqlite3_thread_cleanup,
102591 #else
102592   0,
102593 #endif
102594   sqlite3_total_changes,
102595   sqlite3_trace,
102596 #ifndef SQLITE_OMIT_DEPRECATED
102597   sqlite3_transfer_bindings,
102598 #else
102599   0,
102600 #endif
102601   sqlite3_update_hook,
102602   sqlite3_user_data,
102603   sqlite3_value_blob,
102604   sqlite3_value_bytes,
102605   sqlite3_value_bytes16,
102606   sqlite3_value_double,
102607   sqlite3_value_int,
102608   sqlite3_value_int64,
102609   sqlite3_value_numeric_type,
102610   sqlite3_value_text,
102611   sqlite3_value_text16,
102612   sqlite3_value_text16be,
102613   sqlite3_value_text16le,
102614   sqlite3_value_type,
102615   sqlite3_vmprintf,
102616   /*
102617   ** The original API set ends here.  All extensions can call any
102618   ** of the APIs above provided that the pointer is not NULL.  But
102619   ** before calling APIs that follow, extension should check the
102620   ** sqlite3_libversion_number() to make sure they are dealing with
102621   ** a library that is new enough to support that API.
102622   *************************************************************************
102623   */
102624   sqlite3_overload_function,
102625 
102626   /*
102627   ** Added after 3.3.13
102628   */
102629   sqlite3_prepare_v2,
102630   sqlite3_prepare16_v2,
102631   sqlite3_clear_bindings,
102632 
102633   /*
102634   ** Added for 3.4.1
102635   */
102636   sqlite3_create_module_v2,
102637 
102638   /*
102639   ** Added for 3.5.0
102640   */
102641   sqlite3_bind_zeroblob,
102642   sqlite3_blob_bytes,
102643   sqlite3_blob_close,
102644   sqlite3_blob_open,
102645   sqlite3_blob_read,
102646   sqlite3_blob_write,
102647   sqlite3_create_collation_v2,
102648   sqlite3_file_control,
102649   sqlite3_memory_highwater,
102650   sqlite3_memory_used,
102651 #ifdef SQLITE_MUTEX_OMIT
102652   0,
102653   0,
102654   0,
102655   0,
102656   0,
102657 #else
102658   sqlite3_mutex_alloc,
102659   sqlite3_mutex_enter,
102660   sqlite3_mutex_free,
102661   sqlite3_mutex_leave,
102662   sqlite3_mutex_try,
102663 #endif
102664   sqlite3_open_v2,
102665   sqlite3_release_memory,
102666   sqlite3_result_error_nomem,
102667   sqlite3_result_error_toobig,
102668   sqlite3_sleep,
102669   sqlite3_soft_heap_limit,
102670   sqlite3_vfs_find,
102671   sqlite3_vfs_register,
102672   sqlite3_vfs_unregister,
102673 
102674   /*
102675   ** Added for 3.5.8
102676   */
102677   sqlite3_threadsafe,
102678   sqlite3_result_zeroblob,
102679   sqlite3_result_error_code,
102680   sqlite3_test_control,
102681   sqlite3_randomness,
102682   sqlite3_context_db_handle,
102683 
102684   /*
102685   ** Added for 3.6.0
102686   */
102687   sqlite3_extended_result_codes,
102688   sqlite3_limit,
102689   sqlite3_next_stmt,
102690   sqlite3_sql,
102691   sqlite3_status,
102692 
102693   /*
102694   ** Added for 3.7.4
102695   */
102696   sqlite3_backup_finish,
102697   sqlite3_backup_init,
102698   sqlite3_backup_pagecount,
102699   sqlite3_backup_remaining,
102700   sqlite3_backup_step,
102701 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
102702   sqlite3_compileoption_get,
102703   sqlite3_compileoption_used,
102704 #else
102705   0,
102706   0,
102707 #endif
102708   sqlite3_create_function_v2,
102709   sqlite3_db_config,
102710   sqlite3_db_mutex,
102711   sqlite3_db_status,
102712   sqlite3_extended_errcode,
102713   sqlite3_log,
102714   sqlite3_soft_heap_limit64,
102715   sqlite3_sourceid,
102716   sqlite3_stmt_status,
102717   sqlite3_strnicmp,
102718 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
102719   sqlite3_unlock_notify,
102720 #else
102721   0,
102722 #endif
102723 #ifndef SQLITE_OMIT_WAL
102724   sqlite3_wal_autocheckpoint,
102725   sqlite3_wal_checkpoint,
102726   sqlite3_wal_hook,
102727 #else
102728   0,
102729   0,
102730   0,
102731 #endif
102732   sqlite3_blob_reopen,
102733   sqlite3_vtab_config,
102734   sqlite3_vtab_on_conflict,
102735   sqlite3_close_v2,
102736   sqlite3_db_filename,
102737   sqlite3_db_readonly,
102738   sqlite3_db_release_memory,
102739   sqlite3_errstr,
102740   sqlite3_stmt_busy,
102741   sqlite3_stmt_readonly,
102742   sqlite3_stricmp,
102743   sqlite3_uri_boolean,
102744   sqlite3_uri_int64,
102745   sqlite3_uri_parameter,
102746   sqlite3_vsnprintf,
102747   sqlite3_wal_checkpoint_v2,
102748   /* Version 3.8.7 and later */
102749   sqlite3_auto_extension,
102750   sqlite3_bind_blob64,
102751   sqlite3_bind_text64,
102752   sqlite3_cancel_auto_extension,
102753   sqlite3_load_extension,
102754   sqlite3_malloc64,
102755   sqlite3_msize,
102756   sqlite3_realloc64,
102757   sqlite3_reset_auto_extension,
102758   sqlite3_result_blob64,
102759   sqlite3_result_text64,
102760   sqlite3_strglob
102761 };
102762 
102763 /*
102764 ** Attempt to load an SQLite extension library contained in the file
102765 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
102766 ** default entry point name (sqlite3_extension_init) is used.  Use
102767 ** of the default name is recommended.
102768 **
102769 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
102770 **
102771 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
102772 ** error message text.  The calling function should free this memory
102773 ** by calling sqlite3DbFree(db, ).
102774 */
102775 static int sqlite3LoadExtension(
102776   sqlite3 *db,          /* Load the extension into this database connection */
102777   const char *zFile,    /* Name of the shared library containing extension */
102778   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
102779   char **pzErrMsg       /* Put error message here if not 0 */
102780 ){
102781   sqlite3_vfs *pVfs = db->pVfs;
102782   void *handle;
102783   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
102784   char *zErrmsg = 0;
102785   const char *zEntry;
102786   char *zAltEntry = 0;
102787   void **aHandle;
102788   u64 nMsg = 300 + sqlite3Strlen30(zFile);
102789   int ii;
102790 
102791   /* Shared library endings to try if zFile cannot be loaded as written */
102792   static const char *azEndings[] = {
102793 #if SQLITE_OS_WIN
102794      "dll"
102795 #elif defined(__APPLE__)
102796      "dylib"
102797 #else
102798      "so"
102799 #endif
102800   };
102801 
102802 
102803   if( pzErrMsg ) *pzErrMsg = 0;
102804 
102805   /* Ticket #1863.  To avoid a creating security problems for older
102806   ** applications that relink against newer versions of SQLite, the
102807   ** ability to run load_extension is turned off by default.  One
102808   ** must call sqlite3_enable_load_extension() to turn on extension
102809   ** loading.  Otherwise you get the following error.
102810   */
102811   if( (db->flags & SQLITE_LoadExtension)==0 ){
102812     if( pzErrMsg ){
102813       *pzErrMsg = sqlite3_mprintf("not authorized");
102814     }
102815     return SQLITE_ERROR;
102816   }
102817 
102818   zEntry = zProc ? zProc : "sqlite3_extension_init";
102819 
102820   handle = sqlite3OsDlOpen(pVfs, zFile);
102821 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
102822   for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
102823     char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
102824     if( zAltFile==0 ) return SQLITE_NOMEM;
102825     handle = sqlite3OsDlOpen(pVfs, zAltFile);
102826     sqlite3_free(zAltFile);
102827   }
102828 #endif
102829   if( handle==0 ){
102830     if( pzErrMsg ){
102831       *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
102832       if( zErrmsg ){
102833         sqlite3_snprintf(nMsg, zErrmsg,
102834             "unable to open shared library [%s]", zFile);
102835         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
102836       }
102837     }
102838     return SQLITE_ERROR;
102839   }
102840   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
102841                    sqlite3OsDlSym(pVfs, handle, zEntry);
102842 
102843   /* If no entry point was specified and the default legacy
102844   ** entry point name "sqlite3_extension_init" was not found, then
102845   ** construct an entry point name "sqlite3_X_init" where the X is
102846   ** replaced by the lowercase value of every ASCII alphabetic
102847   ** character in the filename after the last "/" upto the first ".",
102848   ** and eliding the first three characters if they are "lib".
102849   ** Examples:
102850   **
102851   **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
102852   **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
102853   */
102854   if( xInit==0 && zProc==0 ){
102855     int iFile, iEntry, c;
102856     int ncFile = sqlite3Strlen30(zFile);
102857     zAltEntry = sqlite3_malloc64(ncFile+30);
102858     if( zAltEntry==0 ){
102859       sqlite3OsDlClose(pVfs, handle);
102860       return SQLITE_NOMEM;
102861     }
102862     memcpy(zAltEntry, "sqlite3_", 8);
102863     for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
102864     iFile++;
102865     if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
102866     for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
102867       if( sqlite3Isalpha(c) ){
102868         zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
102869       }
102870     }
102871     memcpy(zAltEntry+iEntry, "_init", 6);
102872     zEntry = zAltEntry;
102873     xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
102874                      sqlite3OsDlSym(pVfs, handle, zEntry);
102875   }
102876   if( xInit==0 ){
102877     if( pzErrMsg ){
102878       nMsg += sqlite3Strlen30(zEntry);
102879       *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
102880       if( zErrmsg ){
102881         sqlite3_snprintf(nMsg, zErrmsg,
102882             "no entry point [%s] in shared library [%s]", zEntry, zFile);
102883         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
102884       }
102885     }
102886     sqlite3OsDlClose(pVfs, handle);
102887     sqlite3_free(zAltEntry);
102888     return SQLITE_ERROR;
102889   }
102890   sqlite3_free(zAltEntry);
102891   if( xInit(db, &zErrmsg, &sqlite3Apis) ){
102892     if( pzErrMsg ){
102893       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
102894     }
102895     sqlite3_free(zErrmsg);
102896     sqlite3OsDlClose(pVfs, handle);
102897     return SQLITE_ERROR;
102898   }
102899 
102900   /* Append the new shared library handle to the db->aExtension array. */
102901   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
102902   if( aHandle==0 ){
102903     return SQLITE_NOMEM;
102904   }
102905   if( db->nExtension>0 ){
102906     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
102907   }
102908   sqlite3DbFree(db, db->aExtension);
102909   db->aExtension = aHandle;
102910 
102911   db->aExtension[db->nExtension++] = handle;
102912   return SQLITE_OK;
102913 }
102914 SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
102915   sqlite3 *db,          /* Load the extension into this database connection */
102916   const char *zFile,    /* Name of the shared library containing extension */
102917   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
102918   char **pzErrMsg       /* Put error message here if not 0 */
102919 ){
102920   int rc;
102921   sqlite3_mutex_enter(db->mutex);
102922   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
102923   rc = sqlite3ApiExit(db, rc);
102924   sqlite3_mutex_leave(db->mutex);
102925   return rc;
102926 }
102927 
102928 /*
102929 ** Call this routine when the database connection is closing in order
102930 ** to clean up loaded extensions
102931 */
102932 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
102933   int i;
102934   assert( sqlite3_mutex_held(db->mutex) );
102935   for(i=0; i<db->nExtension; i++){
102936     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
102937   }
102938   sqlite3DbFree(db, db->aExtension);
102939 }
102940 
102941 /*
102942 ** Enable or disable extension loading.  Extension loading is disabled by
102943 ** default so as not to open security holes in older applications.
102944 */
102945 SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff){
102946   sqlite3_mutex_enter(db->mutex);
102947   if( onoff ){
102948     db->flags |= SQLITE_LoadExtension;
102949   }else{
102950     db->flags &= ~SQLITE_LoadExtension;
102951   }
102952   sqlite3_mutex_leave(db->mutex);
102953   return SQLITE_OK;
102954 }
102955 
102956 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
102957 
102958 /*
102959 ** The auto-extension code added regardless of whether or not extension
102960 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
102961 ** code if regular extension loading is not available.  This is that
102962 ** dummy pointer.
102963 */
102964 #ifdef SQLITE_OMIT_LOAD_EXTENSION
102965 static const sqlite3_api_routines sqlite3Apis = { 0 };
102966 #endif
102967 
102968 
102969 /*
102970 ** The following object holds the list of automatically loaded
102971 ** extensions.
102972 **
102973 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
102974 ** mutex must be held while accessing this list.
102975 */
102976 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
102977 static SQLITE_WSD struct sqlite3AutoExtList {
102978   u32 nExt;              /* Number of entries in aExt[] */
102979   void (**aExt)(void);   /* Pointers to the extension init functions */
102980 } sqlite3Autoext = { 0, 0 };
102981 
102982 /* The "wsdAutoext" macro will resolve to the autoextension
102983 ** state vector.  If writable static data is unsupported on the target,
102984 ** we have to locate the state vector at run-time.  In the more common
102985 ** case where writable static data is supported, wsdStat can refer directly
102986 ** to the "sqlite3Autoext" state vector declared above.
102987 */
102988 #ifdef SQLITE_OMIT_WSD
102989 # define wsdAutoextInit \
102990   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
102991 # define wsdAutoext x[0]
102992 #else
102993 # define wsdAutoextInit
102994 # define wsdAutoext sqlite3Autoext
102995 #endif
102996 
102997 
102998 /*
102999 ** Register a statically linked extension that is automatically
103000 ** loaded by every new database connection.
103001 */
103002 SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xInit)(void)){
103003   int rc = SQLITE_OK;
103004 #ifndef SQLITE_OMIT_AUTOINIT
103005   rc = sqlite3_initialize();
103006   if( rc ){
103007     return rc;
103008   }else
103009 #endif
103010   {
103011     u32 i;
103012 #if SQLITE_THREADSAFE
103013     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
103014 #endif
103015     wsdAutoextInit;
103016     sqlite3_mutex_enter(mutex);
103017     for(i=0; i<wsdAutoext.nExt; i++){
103018       if( wsdAutoext.aExt[i]==xInit ) break;
103019     }
103020     if( i==wsdAutoext.nExt ){
103021       u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
103022       void (**aNew)(void);
103023       aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
103024       if( aNew==0 ){
103025         rc = SQLITE_NOMEM;
103026       }else{
103027         wsdAutoext.aExt = aNew;
103028         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
103029         wsdAutoext.nExt++;
103030       }
103031     }
103032     sqlite3_mutex_leave(mutex);
103033     assert( (rc&0xff)==rc );
103034     return rc;
103035   }
103036 }
103037 
103038 /*
103039 ** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
103040 ** set of routines that is invoked for each new database connection, if it
103041 ** is currently on the list.  If xInit is not on the list, then this
103042 ** routine is a no-op.
103043 **
103044 ** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
103045 ** was not on the list.
103046 */
103047 SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xInit)(void)){
103048 #if SQLITE_THREADSAFE
103049   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
103050 #endif
103051   int i;
103052   int n = 0;
103053   wsdAutoextInit;
103054   sqlite3_mutex_enter(mutex);
103055   for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
103056     if( wsdAutoext.aExt[i]==xInit ){
103057       wsdAutoext.nExt--;
103058       wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
103059       n++;
103060       break;
103061     }
103062   }
103063   sqlite3_mutex_leave(mutex);
103064   return n;
103065 }
103066 
103067 /*
103068 ** Reset the automatic extension loading mechanism.
103069 */
103070 SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void){
103071 #ifndef SQLITE_OMIT_AUTOINIT
103072   if( sqlite3_initialize()==SQLITE_OK )
103073 #endif
103074   {
103075 #if SQLITE_THREADSAFE
103076     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
103077 #endif
103078     wsdAutoextInit;
103079     sqlite3_mutex_enter(mutex);
103080     sqlite3_free(wsdAutoext.aExt);
103081     wsdAutoext.aExt = 0;
103082     wsdAutoext.nExt = 0;
103083     sqlite3_mutex_leave(mutex);
103084   }
103085 }
103086 
103087 /*
103088 ** Load all automatic extensions.
103089 **
103090 ** If anything goes wrong, set an error in the database connection.
103091 */
103092 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
103093   u32 i;
103094   int go = 1;
103095   int rc;
103096   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
103097 
103098   wsdAutoextInit;
103099   if( wsdAutoext.nExt==0 ){
103100     /* Common case: early out without every having to acquire a mutex */
103101     return;
103102   }
103103   for(i=0; go; i++){
103104     char *zErrmsg;
103105 #if SQLITE_THREADSAFE
103106     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
103107 #endif
103108     sqlite3_mutex_enter(mutex);
103109     if( i>=wsdAutoext.nExt ){
103110       xInit = 0;
103111       go = 0;
103112     }else{
103113       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
103114               wsdAutoext.aExt[i];
103115     }
103116     sqlite3_mutex_leave(mutex);
103117     zErrmsg = 0;
103118     if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
103119       sqlite3ErrorWithMsg(db, rc,
103120             "automatic extension loading failed: %s", zErrmsg);
103121       go = 0;
103122     }
103123     sqlite3_free(zErrmsg);
103124   }
103125 }
103126 
103127 /************** End of loadext.c *********************************************/
103128 /************** Begin file pragma.c ******************************************/
103129 /*
103130 ** 2003 April 6
103131 **
103132 ** The author disclaims copyright to this source code.  In place of
103133 ** a legal notice, here is a blessing:
103134 **
103135 **    May you do good and not evil.
103136 **    May you find forgiveness for yourself and forgive others.
103137 **    May you share freely, never taking more than you give.
103138 **
103139 *************************************************************************
103140 ** This file contains code used to implement the PRAGMA command.
103141 */
103142 
103143 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
103144 #  if defined(__APPLE__)
103145 #    define SQLITE_ENABLE_LOCKING_STYLE 1
103146 #  else
103147 #    define SQLITE_ENABLE_LOCKING_STYLE 0
103148 #  endif
103149 #endif
103150 
103151 /***************************************************************************
103152 ** The "pragma.h" include file is an automatically generated file that
103153 ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
103154 ** object.  This ensures that the aPragmaName[] table is arranged in
103155 ** lexicographical order to facility a binary search of the pragma name.
103156 ** Do not edit pragma.h directly.  Edit and rerun the script in at
103157 ** ../tool/mkpragmatab.tcl. */
103158 /************** Include pragma.h in the middle of pragma.c *******************/
103159 /************** Begin file pragma.h ******************************************/
103160 /* DO NOT EDIT!
103161 ** This file is automatically generated by the script at
103162 ** ../tool/mkpragmatab.tcl.  To update the set of pragmas, edit
103163 ** that script and rerun it.
103164 */
103165 #define PragTyp_HEADER_VALUE                   0
103166 #define PragTyp_AUTO_VACUUM                    1
103167 #define PragTyp_FLAG                           2
103168 #define PragTyp_BUSY_TIMEOUT                   3
103169 #define PragTyp_CACHE_SIZE                     4
103170 #define PragTyp_CASE_SENSITIVE_LIKE            5
103171 #define PragTyp_COLLATION_LIST                 6
103172 #define PragTyp_COMPILE_OPTIONS                7
103173 #define PragTyp_DATA_STORE_DIRECTORY           8
103174 #define PragTyp_DATABASE_LIST                  9
103175 #define PragTyp_DEFAULT_CACHE_SIZE            10
103176 #define PragTyp_ENCODING                      11
103177 #define PragTyp_FOREIGN_KEY_CHECK             12
103178 #define PragTyp_FOREIGN_KEY_LIST              13
103179 #define PragTyp_INCREMENTAL_VACUUM            14
103180 #define PragTyp_INDEX_INFO                    15
103181 #define PragTyp_INDEX_LIST                    16
103182 #define PragTyp_INTEGRITY_CHECK               17
103183 #define PragTyp_JOURNAL_MODE                  18
103184 #define PragTyp_JOURNAL_SIZE_LIMIT            19
103185 #define PragTyp_LOCK_PROXY_FILE               20
103186 #define PragTyp_LOCKING_MODE                  21
103187 #define PragTyp_PAGE_COUNT                    22
103188 #define PragTyp_MMAP_SIZE                     23
103189 #define PragTyp_PAGE_SIZE                     24
103190 #define PragTyp_SECURE_DELETE                 25
103191 #define PragTyp_SHRINK_MEMORY                 26
103192 #define PragTyp_SOFT_HEAP_LIMIT               27
103193 #define PragTyp_STATS                         28
103194 #define PragTyp_SYNCHRONOUS                   29
103195 #define PragTyp_TABLE_INFO                    30
103196 #define PragTyp_TEMP_STORE                    31
103197 #define PragTyp_TEMP_STORE_DIRECTORY          32
103198 #define PragTyp_THREADS                       33
103199 #define PragTyp_WAL_AUTOCHECKPOINT            34
103200 #define PragTyp_WAL_CHECKPOINT                35
103201 #define PragTyp_ACTIVATE_EXTENSIONS           36
103202 #define PragTyp_HEXKEY                        37
103203 #define PragTyp_KEY                           38
103204 #define PragTyp_REKEY                         39
103205 #define PragTyp_LOCK_STATUS                   40
103206 #define PragTyp_PARSER_TRACE                  41
103207 #define PragFlag_NeedSchema           0x01
103208 #define PragFlag_ReadOnly             0x02
103209 static const struct sPragmaNames {
103210   const char *const zName;  /* Name of pragma */
103211   u8 ePragTyp;              /* PragTyp_XXX value */
103212   u8 mPragFlag;             /* Zero or more PragFlag_XXX values */
103213   u32 iArg;                 /* Extra argument */
103214 } aPragmaNames[] = {
103215 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
103216   { /* zName:     */ "activate_extensions",
103217     /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
103218     /* ePragFlag: */ 0,
103219     /* iArg:      */ 0 },
103220 #endif
103221 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
103222   { /* zName:     */ "application_id",
103223     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
103224     /* ePragFlag: */ 0,
103225     /* iArg:      */ BTREE_APPLICATION_ID },
103226 #endif
103227 #if !defined(SQLITE_OMIT_AUTOVACUUM)
103228   { /* zName:     */ "auto_vacuum",
103229     /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
103230     /* ePragFlag: */ PragFlag_NeedSchema,
103231     /* iArg:      */ 0 },
103232 #endif
103233 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103234 #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
103235   { /* zName:     */ "automatic_index",
103236     /* ePragTyp:  */ PragTyp_FLAG,
103237     /* ePragFlag: */ 0,
103238     /* iArg:      */ SQLITE_AutoIndex },
103239 #endif
103240 #endif
103241   { /* zName:     */ "busy_timeout",
103242     /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
103243     /* ePragFlag: */ 0,
103244     /* iArg:      */ 0 },
103245 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
103246   { /* zName:     */ "cache_size",
103247     /* ePragTyp:  */ PragTyp_CACHE_SIZE,
103248     /* ePragFlag: */ PragFlag_NeedSchema,
103249     /* iArg:      */ 0 },
103250 #endif
103251 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103252   { /* zName:     */ "cache_spill",
103253     /* ePragTyp:  */ PragTyp_FLAG,
103254     /* ePragFlag: */ 0,
103255     /* iArg:      */ SQLITE_CacheSpill },
103256 #endif
103257   { /* zName:     */ "case_sensitive_like",
103258     /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
103259     /* ePragFlag: */ 0,
103260     /* iArg:      */ 0 },
103261 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103262   { /* zName:     */ "checkpoint_fullfsync",
103263     /* ePragTyp:  */ PragTyp_FLAG,
103264     /* ePragFlag: */ 0,
103265     /* iArg:      */ SQLITE_CkptFullFSync },
103266 #endif
103267 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
103268   { /* zName:     */ "collation_list",
103269     /* ePragTyp:  */ PragTyp_COLLATION_LIST,
103270     /* ePragFlag: */ 0,
103271     /* iArg:      */ 0 },
103272 #endif
103273 #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
103274   { /* zName:     */ "compile_options",
103275     /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
103276     /* ePragFlag: */ 0,
103277     /* iArg:      */ 0 },
103278 #endif
103279 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103280   { /* zName:     */ "count_changes",
103281     /* ePragTyp:  */ PragTyp_FLAG,
103282     /* ePragFlag: */ 0,
103283     /* iArg:      */ SQLITE_CountRows },
103284 #endif
103285 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
103286   { /* zName:     */ "data_store_directory",
103287     /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
103288     /* ePragFlag: */ 0,
103289     /* iArg:      */ 0 },
103290 #endif
103291 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
103292   { /* zName:     */ "data_version",
103293     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
103294     /* ePragFlag: */ PragFlag_ReadOnly,
103295     /* iArg:      */ BTREE_DATA_VERSION },
103296 #endif
103297 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
103298   { /* zName:     */ "database_list",
103299     /* ePragTyp:  */ PragTyp_DATABASE_LIST,
103300     /* ePragFlag: */ PragFlag_NeedSchema,
103301     /* iArg:      */ 0 },
103302 #endif
103303 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
103304   { /* zName:     */ "default_cache_size",
103305     /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
103306     /* ePragFlag: */ PragFlag_NeedSchema,
103307     /* iArg:      */ 0 },
103308 #endif
103309 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103310 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
103311   { /* zName:     */ "defer_foreign_keys",
103312     /* ePragTyp:  */ PragTyp_FLAG,
103313     /* ePragFlag: */ 0,
103314     /* iArg:      */ SQLITE_DeferFKs },
103315 #endif
103316 #endif
103317 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103318   { /* zName:     */ "empty_result_callbacks",
103319     /* ePragTyp:  */ PragTyp_FLAG,
103320     /* ePragFlag: */ 0,
103321     /* iArg:      */ SQLITE_NullCallback },
103322 #endif
103323 #if !defined(SQLITE_OMIT_UTF16)
103324   { /* zName:     */ "encoding",
103325     /* ePragTyp:  */ PragTyp_ENCODING,
103326     /* ePragFlag: */ 0,
103327     /* iArg:      */ 0 },
103328 #endif
103329 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
103330   { /* zName:     */ "foreign_key_check",
103331     /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
103332     /* ePragFlag: */ PragFlag_NeedSchema,
103333     /* iArg:      */ 0 },
103334 #endif
103335 #if !defined(SQLITE_OMIT_FOREIGN_KEY)
103336   { /* zName:     */ "foreign_key_list",
103337     /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
103338     /* ePragFlag: */ PragFlag_NeedSchema,
103339     /* iArg:      */ 0 },
103340 #endif
103341 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103342 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
103343   { /* zName:     */ "foreign_keys",
103344     /* ePragTyp:  */ PragTyp_FLAG,
103345     /* ePragFlag: */ 0,
103346     /* iArg:      */ SQLITE_ForeignKeys },
103347 #endif
103348 #endif
103349 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
103350   { /* zName:     */ "freelist_count",
103351     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
103352     /* ePragFlag: */ PragFlag_ReadOnly,
103353     /* iArg:      */ BTREE_FREE_PAGE_COUNT },
103354 #endif
103355 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103356   { /* zName:     */ "full_column_names",
103357     /* ePragTyp:  */ PragTyp_FLAG,
103358     /* ePragFlag: */ 0,
103359     /* iArg:      */ SQLITE_FullColNames },
103360   { /* zName:     */ "fullfsync",
103361     /* ePragTyp:  */ PragTyp_FLAG,
103362     /* ePragFlag: */ 0,
103363     /* iArg:      */ SQLITE_FullFSync },
103364 #endif
103365 #if defined(SQLITE_HAS_CODEC)
103366   { /* zName:     */ "hexkey",
103367     /* ePragTyp:  */ PragTyp_HEXKEY,
103368     /* ePragFlag: */ 0,
103369     /* iArg:      */ 0 },
103370   { /* zName:     */ "hexrekey",
103371     /* ePragTyp:  */ PragTyp_HEXKEY,
103372     /* ePragFlag: */ 0,
103373     /* iArg:      */ 0 },
103374 #endif
103375 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103376 #if !defined(SQLITE_OMIT_CHECK)
103377   { /* zName:     */ "ignore_check_constraints",
103378     /* ePragTyp:  */ PragTyp_FLAG,
103379     /* ePragFlag: */ 0,
103380     /* iArg:      */ SQLITE_IgnoreChecks },
103381 #endif
103382 #endif
103383 #if !defined(SQLITE_OMIT_AUTOVACUUM)
103384   { /* zName:     */ "incremental_vacuum",
103385     /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
103386     /* ePragFlag: */ PragFlag_NeedSchema,
103387     /* iArg:      */ 0 },
103388 #endif
103389 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
103390   { /* zName:     */ "index_info",
103391     /* ePragTyp:  */ PragTyp_INDEX_INFO,
103392     /* ePragFlag: */ PragFlag_NeedSchema,
103393     /* iArg:      */ 0 },
103394   { /* zName:     */ "index_list",
103395     /* ePragTyp:  */ PragTyp_INDEX_LIST,
103396     /* ePragFlag: */ PragFlag_NeedSchema,
103397     /* iArg:      */ 0 },
103398   { /* zName:     */ "index_xinfo",
103399     /* ePragTyp:  */ PragTyp_INDEX_INFO,
103400     /* ePragFlag: */ PragFlag_NeedSchema,
103401     /* iArg:      */ 1 },
103402 #endif
103403 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
103404   { /* zName:     */ "integrity_check",
103405     /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
103406     /* ePragFlag: */ PragFlag_NeedSchema,
103407     /* iArg:      */ 0 },
103408 #endif
103409 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
103410   { /* zName:     */ "journal_mode",
103411     /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
103412     /* ePragFlag: */ PragFlag_NeedSchema,
103413     /* iArg:      */ 0 },
103414   { /* zName:     */ "journal_size_limit",
103415     /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
103416     /* ePragFlag: */ 0,
103417     /* iArg:      */ 0 },
103418 #endif
103419 #if defined(SQLITE_HAS_CODEC)
103420   { /* zName:     */ "key",
103421     /* ePragTyp:  */ PragTyp_KEY,
103422     /* ePragFlag: */ 0,
103423     /* iArg:      */ 0 },
103424 #endif
103425 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103426   { /* zName:     */ "legacy_file_format",
103427     /* ePragTyp:  */ PragTyp_FLAG,
103428     /* ePragFlag: */ 0,
103429     /* iArg:      */ SQLITE_LegacyFileFmt },
103430 #endif
103431 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
103432   { /* zName:     */ "lock_proxy_file",
103433     /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
103434     /* ePragFlag: */ 0,
103435     /* iArg:      */ 0 },
103436 #endif
103437 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
103438   { /* zName:     */ "lock_status",
103439     /* ePragTyp:  */ PragTyp_LOCK_STATUS,
103440     /* ePragFlag: */ 0,
103441     /* iArg:      */ 0 },
103442 #endif
103443 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
103444   { /* zName:     */ "locking_mode",
103445     /* ePragTyp:  */ PragTyp_LOCKING_MODE,
103446     /* ePragFlag: */ 0,
103447     /* iArg:      */ 0 },
103448   { /* zName:     */ "max_page_count",
103449     /* ePragTyp:  */ PragTyp_PAGE_COUNT,
103450     /* ePragFlag: */ PragFlag_NeedSchema,
103451     /* iArg:      */ 0 },
103452   { /* zName:     */ "mmap_size",
103453     /* ePragTyp:  */ PragTyp_MMAP_SIZE,
103454     /* ePragFlag: */ 0,
103455     /* iArg:      */ 0 },
103456   { /* zName:     */ "page_count",
103457     /* ePragTyp:  */ PragTyp_PAGE_COUNT,
103458     /* ePragFlag: */ PragFlag_NeedSchema,
103459     /* iArg:      */ 0 },
103460   { /* zName:     */ "page_size",
103461     /* ePragTyp:  */ PragTyp_PAGE_SIZE,
103462     /* ePragFlag: */ 0,
103463     /* iArg:      */ 0 },
103464 #endif
103465 #if defined(SQLITE_DEBUG)
103466   { /* zName:     */ "parser_trace",
103467     /* ePragTyp:  */ PragTyp_PARSER_TRACE,
103468     /* ePragFlag: */ 0,
103469     /* iArg:      */ 0 },
103470 #endif
103471 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103472   { /* zName:     */ "query_only",
103473     /* ePragTyp:  */ PragTyp_FLAG,
103474     /* ePragFlag: */ 0,
103475     /* iArg:      */ SQLITE_QueryOnly },
103476 #endif
103477 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
103478   { /* zName:     */ "quick_check",
103479     /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
103480     /* ePragFlag: */ PragFlag_NeedSchema,
103481     /* iArg:      */ 0 },
103482 #endif
103483 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103484   { /* zName:     */ "read_uncommitted",
103485     /* ePragTyp:  */ PragTyp_FLAG,
103486     /* ePragFlag: */ 0,
103487     /* iArg:      */ SQLITE_ReadUncommitted },
103488   { /* zName:     */ "recursive_triggers",
103489     /* ePragTyp:  */ PragTyp_FLAG,
103490     /* ePragFlag: */ 0,
103491     /* iArg:      */ SQLITE_RecTriggers },
103492 #endif
103493 #if defined(SQLITE_HAS_CODEC)
103494   { /* zName:     */ "rekey",
103495     /* ePragTyp:  */ PragTyp_REKEY,
103496     /* ePragFlag: */ 0,
103497     /* iArg:      */ 0 },
103498 #endif
103499 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103500   { /* zName:     */ "reverse_unordered_selects",
103501     /* ePragTyp:  */ PragTyp_FLAG,
103502     /* ePragFlag: */ 0,
103503     /* iArg:      */ SQLITE_ReverseOrder },
103504 #endif
103505 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
103506   { /* zName:     */ "schema_version",
103507     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
103508     /* ePragFlag: */ 0,
103509     /* iArg:      */ BTREE_SCHEMA_VERSION },
103510 #endif
103511 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
103512   { /* zName:     */ "secure_delete",
103513     /* ePragTyp:  */ PragTyp_SECURE_DELETE,
103514     /* ePragFlag: */ 0,
103515     /* iArg:      */ 0 },
103516 #endif
103517 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103518   { /* zName:     */ "short_column_names",
103519     /* ePragTyp:  */ PragTyp_FLAG,
103520     /* ePragFlag: */ 0,
103521     /* iArg:      */ SQLITE_ShortColNames },
103522 #endif
103523   { /* zName:     */ "shrink_memory",
103524     /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
103525     /* ePragFlag: */ 0,
103526     /* iArg:      */ 0 },
103527   { /* zName:     */ "soft_heap_limit",
103528     /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
103529     /* ePragFlag: */ 0,
103530     /* iArg:      */ 0 },
103531 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103532 #if defined(SQLITE_DEBUG)
103533   { /* zName:     */ "sql_trace",
103534     /* ePragTyp:  */ PragTyp_FLAG,
103535     /* ePragFlag: */ 0,
103536     /* iArg:      */ SQLITE_SqlTrace },
103537 #endif
103538 #endif
103539 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
103540   { /* zName:     */ "stats",
103541     /* ePragTyp:  */ PragTyp_STATS,
103542     /* ePragFlag: */ PragFlag_NeedSchema,
103543     /* iArg:      */ 0 },
103544 #endif
103545 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
103546   { /* zName:     */ "synchronous",
103547     /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
103548     /* ePragFlag: */ PragFlag_NeedSchema,
103549     /* iArg:      */ 0 },
103550 #endif
103551 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
103552   { /* zName:     */ "table_info",
103553     /* ePragTyp:  */ PragTyp_TABLE_INFO,
103554     /* ePragFlag: */ PragFlag_NeedSchema,
103555     /* iArg:      */ 0 },
103556 #endif
103557 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
103558   { /* zName:     */ "temp_store",
103559     /* ePragTyp:  */ PragTyp_TEMP_STORE,
103560     /* ePragFlag: */ 0,
103561     /* iArg:      */ 0 },
103562   { /* zName:     */ "temp_store_directory",
103563     /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
103564     /* ePragFlag: */ 0,
103565     /* iArg:      */ 0 },
103566 #endif
103567   { /* zName:     */ "threads",
103568     /* ePragTyp:  */ PragTyp_THREADS,
103569     /* ePragFlag: */ 0,
103570     /* iArg:      */ 0 },
103571 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
103572   { /* zName:     */ "user_version",
103573     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
103574     /* ePragFlag: */ 0,
103575     /* iArg:      */ BTREE_USER_VERSION },
103576 #endif
103577 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103578 #if defined(SQLITE_DEBUG)
103579   { /* zName:     */ "vdbe_addoptrace",
103580     /* ePragTyp:  */ PragTyp_FLAG,
103581     /* ePragFlag: */ 0,
103582     /* iArg:      */ SQLITE_VdbeAddopTrace },
103583   { /* zName:     */ "vdbe_debug",
103584     /* ePragTyp:  */ PragTyp_FLAG,
103585     /* ePragFlag: */ 0,
103586     /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
103587   { /* zName:     */ "vdbe_eqp",
103588     /* ePragTyp:  */ PragTyp_FLAG,
103589     /* ePragFlag: */ 0,
103590     /* iArg:      */ SQLITE_VdbeEQP },
103591   { /* zName:     */ "vdbe_listing",
103592     /* ePragTyp:  */ PragTyp_FLAG,
103593     /* ePragFlag: */ 0,
103594     /* iArg:      */ SQLITE_VdbeListing },
103595   { /* zName:     */ "vdbe_trace",
103596     /* ePragTyp:  */ PragTyp_FLAG,
103597     /* ePragFlag: */ 0,
103598     /* iArg:      */ SQLITE_VdbeTrace },
103599 #endif
103600 #endif
103601 #if !defined(SQLITE_OMIT_WAL)
103602   { /* zName:     */ "wal_autocheckpoint",
103603     /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
103604     /* ePragFlag: */ 0,
103605     /* iArg:      */ 0 },
103606   { /* zName:     */ "wal_checkpoint",
103607     /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
103608     /* ePragFlag: */ PragFlag_NeedSchema,
103609     /* iArg:      */ 0 },
103610 #endif
103611 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103612   { /* zName:     */ "writable_schema",
103613     /* ePragTyp:  */ PragTyp_FLAG,
103614     /* ePragFlag: */ 0,
103615     /* iArg:      */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
103616 #endif
103617 };
103618 /* Number of pragmas: 59 on by default, 72 total. */
103619 
103620 /************** End of pragma.h **********************************************/
103621 /************** Continuing where we left off in pragma.c *********************/
103622 
103623 /*
103624 ** Interpret the given string as a safety level.  Return 0 for OFF,
103625 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
103626 ** unrecognized string argument.  The FULL option is disallowed
103627 ** if the omitFull parameter it 1.
103628 **
103629 ** Note that the values returned are one less that the values that
103630 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
103631 ** to support legacy SQL code.  The safety level used to be boolean
103632 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
103633 */
103634 static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
103635                              /* 123456789 123456789 */
103636   static const char zText[] = "onoffalseyestruefull";
103637   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
103638   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
103639   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
103640   int i, n;
103641   if( sqlite3Isdigit(*z) ){
103642     return (u8)sqlite3Atoi(z);
103643   }
103644   n = sqlite3Strlen30(z);
103645   for(i=0; i<ArraySize(iLength)-omitFull; i++){
103646     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
103647       return iValue[i];
103648     }
103649   }
103650   return dflt;
103651 }
103652 
103653 /*
103654 ** Interpret the given string as a boolean value.
103655 */
103656 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
103657   return getSafetyLevel(z,1,dflt)!=0;
103658 }
103659 
103660 /* The sqlite3GetBoolean() function is used by other modules but the
103661 ** remainder of this file is specific to PRAGMA processing.  So omit
103662 ** the rest of the file if PRAGMAs are omitted from the build.
103663 */
103664 #if !defined(SQLITE_OMIT_PRAGMA)
103665 
103666 /*
103667 ** Interpret the given string as a locking mode value.
103668 */
103669 static int getLockingMode(const char *z){
103670   if( z ){
103671     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
103672     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
103673   }
103674   return PAGER_LOCKINGMODE_QUERY;
103675 }
103676 
103677 #ifndef SQLITE_OMIT_AUTOVACUUM
103678 /*
103679 ** Interpret the given string as an auto-vacuum mode value.
103680 **
103681 ** The following strings, "none", "full" and "incremental" are
103682 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
103683 */
103684 static int getAutoVacuum(const char *z){
103685   int i;
103686   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
103687   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
103688   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
103689   i = sqlite3Atoi(z);
103690   return (u8)((i>=0&&i<=2)?i:0);
103691 }
103692 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
103693 
103694 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
103695 /*
103696 ** Interpret the given string as a temp db location. Return 1 for file
103697 ** backed temporary databases, 2 for the Red-Black tree in memory database
103698 ** and 0 to use the compile-time default.
103699 */
103700 static int getTempStore(const char *z){
103701   if( z[0]>='0' && z[0]<='2' ){
103702     return z[0] - '0';
103703   }else if( sqlite3StrICmp(z, "file")==0 ){
103704     return 1;
103705   }else if( sqlite3StrICmp(z, "memory")==0 ){
103706     return 2;
103707   }else{
103708     return 0;
103709   }
103710 }
103711 #endif /* SQLITE_PAGER_PRAGMAS */
103712 
103713 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
103714 /*
103715 ** Invalidate temp storage, either when the temp storage is changed
103716 ** from default, or when 'file' and the temp_store_directory has changed
103717 */
103718 static int invalidateTempStorage(Parse *pParse){
103719   sqlite3 *db = pParse->db;
103720   if( db->aDb[1].pBt!=0 ){
103721     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
103722       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
103723         "from within a transaction");
103724       return SQLITE_ERROR;
103725     }
103726     sqlite3BtreeClose(db->aDb[1].pBt);
103727     db->aDb[1].pBt = 0;
103728     sqlite3ResetAllSchemasOfConnection(db);
103729   }
103730   return SQLITE_OK;
103731 }
103732 #endif /* SQLITE_PAGER_PRAGMAS */
103733 
103734 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
103735 /*
103736 ** If the TEMP database is open, close it and mark the database schema
103737 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
103738 ** or DEFAULT_TEMP_STORE pragmas.
103739 */
103740 static int changeTempStorage(Parse *pParse, const char *zStorageType){
103741   int ts = getTempStore(zStorageType);
103742   sqlite3 *db = pParse->db;
103743   if( db->temp_store==ts ) return SQLITE_OK;
103744   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
103745     return SQLITE_ERROR;
103746   }
103747   db->temp_store = (u8)ts;
103748   return SQLITE_OK;
103749 }
103750 #endif /* SQLITE_PAGER_PRAGMAS */
103751 
103752 /*
103753 ** Generate code to return a single integer value.
103754 */
103755 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
103756   Vdbe *v = sqlite3GetVdbe(pParse);
103757   int nMem = ++pParse->nMem;
103758   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
103759   if( pI64 ){
103760     memcpy(pI64, &value, sizeof(value));
103761   }
103762   sqlite3VdbeAddOp4(v, OP_Int64, 0, nMem, 0, (char*)pI64, P4_INT64);
103763   sqlite3VdbeSetNumCols(v, 1);
103764   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
103765   sqlite3VdbeAddOp2(v, OP_ResultRow, nMem, 1);
103766 }
103767 
103768 
103769 /*
103770 ** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
103771 ** set these values for all pagers.
103772 */
103773 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
103774 static void setAllPagerFlags(sqlite3 *db){
103775   if( db->autoCommit ){
103776     Db *pDb = db->aDb;
103777     int n = db->nDb;
103778     assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
103779     assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
103780     assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
103781     assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
103782              ==  PAGER_FLAGS_MASK );
103783     assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
103784     while( (n--) > 0 ){
103785       if( pDb->pBt ){
103786         sqlite3BtreeSetPagerFlags(pDb->pBt,
103787                  pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
103788       }
103789       pDb++;
103790     }
103791   }
103792 }
103793 #else
103794 # define setAllPagerFlags(X)  /* no-op */
103795 #endif
103796 
103797 
103798 /*
103799 ** Return a human-readable name for a constraint resolution action.
103800 */
103801 #ifndef SQLITE_OMIT_FOREIGN_KEY
103802 static const char *actionName(u8 action){
103803   const char *zName;
103804   switch( action ){
103805     case OE_SetNull:  zName = "SET NULL";        break;
103806     case OE_SetDflt:  zName = "SET DEFAULT";     break;
103807     case OE_Cascade:  zName = "CASCADE";         break;
103808     case OE_Restrict: zName = "RESTRICT";        break;
103809     default:          zName = "NO ACTION";
103810                       assert( action==OE_None ); break;
103811   }
103812   return zName;
103813 }
103814 #endif
103815 
103816 
103817 /*
103818 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
103819 ** defined in pager.h. This function returns the associated lowercase
103820 ** journal-mode name.
103821 */
103822 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
103823   static char * const azModeName[] = {
103824     "delete", "persist", "off", "truncate", "memory"
103825 #ifndef SQLITE_OMIT_WAL
103826      , "wal"
103827 #endif
103828   };
103829   assert( PAGER_JOURNALMODE_DELETE==0 );
103830   assert( PAGER_JOURNALMODE_PERSIST==1 );
103831   assert( PAGER_JOURNALMODE_OFF==2 );
103832   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
103833   assert( PAGER_JOURNALMODE_MEMORY==4 );
103834   assert( PAGER_JOURNALMODE_WAL==5 );
103835   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
103836 
103837   if( eMode==ArraySize(azModeName) ) return 0;
103838   return azModeName[eMode];
103839 }
103840 
103841 /*
103842 ** Process a pragma statement.
103843 **
103844 ** Pragmas are of this form:
103845 **
103846 **      PRAGMA [database.]id [= value]
103847 **
103848 ** The identifier might also be a string.  The value is a string, and
103849 ** identifier, or a number.  If minusFlag is true, then the value is
103850 ** a number that was preceded by a minus sign.
103851 **
103852 ** If the left side is "database.id" then pId1 is the database name
103853 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
103854 ** id and pId2 is any empty string.
103855 */
103856 SQLITE_PRIVATE void sqlite3Pragma(
103857   Parse *pParse,
103858   Token *pId1,        /* First part of [database.]id field */
103859   Token *pId2,        /* Second part of [database.]id field, or NULL */
103860   Token *pValue,      /* Token for <value>, or NULL */
103861   int minusFlag       /* True if a '-' sign preceded <value> */
103862 ){
103863   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
103864   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
103865   const char *zDb = 0;   /* The database name */
103866   Token *pId;            /* Pointer to <id> token */
103867   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
103868   int iDb;               /* Database index for <database> */
103869   int lwr, upr, mid = 0;       /* Binary search bounds */
103870   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
103871   sqlite3 *db = pParse->db;    /* The database connection */
103872   Db *pDb;                     /* The specific database being pragmaed */
103873   Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
103874   const struct sPragmaNames *pPragma;
103875 
103876   if( v==0 ) return;
103877   sqlite3VdbeRunOnlyOnce(v);
103878   pParse->nMem = 2;
103879 
103880   /* Interpret the [database.] part of the pragma statement. iDb is the
103881   ** index of the database this pragma is being applied to in db.aDb[]. */
103882   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
103883   if( iDb<0 ) return;
103884   pDb = &db->aDb[iDb];
103885 
103886   /* If the temp database has been explicitly named as part of the
103887   ** pragma, make sure it is open.
103888   */
103889   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
103890     return;
103891   }
103892 
103893   zLeft = sqlite3NameFromToken(db, pId);
103894   if( !zLeft ) return;
103895   if( minusFlag ){
103896     zRight = sqlite3MPrintf(db, "-%T", pValue);
103897   }else{
103898     zRight = sqlite3NameFromToken(db, pValue);
103899   }
103900 
103901   assert( pId2 );
103902   zDb = pId2->n>0 ? pDb->zName : 0;
103903   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
103904     goto pragma_out;
103905   }
103906 
103907   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
103908   ** connection.  If it returns SQLITE_OK, then assume that the VFS
103909   ** handled the pragma and generate a no-op prepared statement.
103910   **
103911   ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
103912   ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
103913   ** object corresponding to the database file to which the pragma
103914   ** statement refers.
103915   **
103916   ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
103917   ** file control is an array of pointers to strings (char**) in which the
103918   ** second element of the array is the name of the pragma and the third
103919   ** element is the argument to the pragma or NULL if the pragma has no
103920   ** argument.
103921   */
103922   aFcntl[0] = 0;
103923   aFcntl[1] = zLeft;
103924   aFcntl[2] = zRight;
103925   aFcntl[3] = 0;
103926   db->busyHandler.nBusy = 0;
103927   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
103928   if( rc==SQLITE_OK ){
103929     if( aFcntl[0] ){
103930       int nMem = ++pParse->nMem;
103931       sqlite3VdbeAddOp4(v, OP_String8, 0, nMem, 0, aFcntl[0], 0);
103932       sqlite3VdbeSetNumCols(v, 1);
103933       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
103934       sqlite3VdbeAddOp2(v, OP_ResultRow, nMem, 1);
103935       sqlite3_free(aFcntl[0]);
103936     }
103937     goto pragma_out;
103938   }
103939   if( rc!=SQLITE_NOTFOUND ){
103940     if( aFcntl[0] ){
103941       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
103942       sqlite3_free(aFcntl[0]);
103943     }
103944     pParse->nErr++;
103945     pParse->rc = rc;
103946     goto pragma_out;
103947   }
103948 
103949   /* Locate the pragma in the lookup table */
103950   lwr = 0;
103951   upr = ArraySize(aPragmaNames)-1;
103952   while( lwr<=upr ){
103953     mid = (lwr+upr)/2;
103954     rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
103955     if( rc==0 ) break;
103956     if( rc<0 ){
103957       upr = mid - 1;
103958     }else{
103959       lwr = mid + 1;
103960     }
103961   }
103962   if( lwr>upr ) goto pragma_out;
103963   pPragma = &aPragmaNames[mid];
103964 
103965   /* Make sure the database schema is loaded if the pragma requires that */
103966   if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
103967     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
103968   }
103969 
103970   /* Jump to the appropriate pragma handler */
103971   switch( pPragma->ePragTyp ){
103972 
103973 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
103974   /*
103975   **  PRAGMA [database.]default_cache_size
103976   **  PRAGMA [database.]default_cache_size=N
103977   **
103978   ** The first form reports the current persistent setting for the
103979   ** page cache size.  The value returned is the maximum number of
103980   ** pages in the page cache.  The second form sets both the current
103981   ** page cache size value and the persistent page cache size value
103982   ** stored in the database file.
103983   **
103984   ** Older versions of SQLite would set the default cache size to a
103985   ** negative number to indicate synchronous=OFF.  These days, synchronous
103986   ** is always on by default regardless of the sign of the default cache
103987   ** size.  But continue to take the absolute value of the default cache
103988   ** size of historical compatibility.
103989   */
103990   case PragTyp_DEFAULT_CACHE_SIZE: {
103991     static const int iLn = VDBE_OFFSET_LINENO(2);
103992     static const VdbeOpList getCacheSize[] = {
103993       { OP_Transaction, 0, 0,        0},                         /* 0 */
103994       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
103995       { OP_IfPos,       1, 8,        0},
103996       { OP_Integer,     0, 2,        0},
103997       { OP_Subtract,    1, 2,        1},
103998       { OP_IfPos,       1, 8,        0},
103999       { OP_Integer,     0, 1,        0},                         /* 6 */
104000       { OP_Noop,        0, 0,        0},
104001       { OP_ResultRow,   1, 1,        0},
104002     };
104003     int addr;
104004     sqlite3VdbeUsesBtree(v, iDb);
104005     if( !zRight ){
104006       sqlite3VdbeSetNumCols(v, 1);
104007       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
104008       pParse->nMem += 2;
104009       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
104010       sqlite3VdbeChangeP1(v, addr, iDb);
104011       sqlite3VdbeChangeP1(v, addr+1, iDb);
104012       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
104013     }else{
104014       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
104015       sqlite3BeginWriteOperation(pParse, 0, iDb);
104016       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
104017       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
104018       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
104019       pDb->pSchema->cache_size = size;
104020       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
104021     }
104022     break;
104023   }
104024 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
104025 
104026 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
104027   /*
104028   **  PRAGMA [database.]page_size
104029   **  PRAGMA [database.]page_size=N
104030   **
104031   ** The first form reports the current setting for the
104032   ** database page size in bytes.  The second form sets the
104033   ** database page size value.  The value can only be set if
104034   ** the database has not yet been created.
104035   */
104036   case PragTyp_PAGE_SIZE: {
104037     Btree *pBt = pDb->pBt;
104038     assert( pBt!=0 );
104039     if( !zRight ){
104040       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
104041       returnSingleInt(pParse, "page_size", size);
104042     }else{
104043       /* Malloc may fail when setting the page-size, as there is an internal
104044       ** buffer that the pager module resizes using sqlite3_realloc().
104045       */
104046       db->nextPagesize = sqlite3Atoi(zRight);
104047       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
104048         db->mallocFailed = 1;
104049       }
104050     }
104051     break;
104052   }
104053 
104054   /*
104055   **  PRAGMA [database.]secure_delete
104056   **  PRAGMA [database.]secure_delete=ON/OFF
104057   **
104058   ** The first form reports the current setting for the
104059   ** secure_delete flag.  The second form changes the secure_delete
104060   ** flag setting and reports thenew value.
104061   */
104062   case PragTyp_SECURE_DELETE: {
104063     Btree *pBt = pDb->pBt;
104064     int b = -1;
104065     assert( pBt!=0 );
104066     if( zRight ){
104067       b = sqlite3GetBoolean(zRight, 0);
104068     }
104069     if( pId2->n==0 && b>=0 ){
104070       int ii;
104071       for(ii=0; ii<db->nDb; ii++){
104072         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
104073       }
104074     }
104075     b = sqlite3BtreeSecureDelete(pBt, b);
104076     returnSingleInt(pParse, "secure_delete", b);
104077     break;
104078   }
104079 
104080   /*
104081   **  PRAGMA [database.]max_page_count
104082   **  PRAGMA [database.]max_page_count=N
104083   **
104084   ** The first form reports the current setting for the
104085   ** maximum number of pages in the database file.  The
104086   ** second form attempts to change this setting.  Both
104087   ** forms return the current setting.
104088   **
104089   ** The absolute value of N is used.  This is undocumented and might
104090   ** change.  The only purpose is to provide an easy way to test
104091   ** the sqlite3AbsInt32() function.
104092   **
104093   **  PRAGMA [database.]page_count
104094   **
104095   ** Return the number of pages in the specified database.
104096   */
104097   case PragTyp_PAGE_COUNT: {
104098     int iReg;
104099     sqlite3CodeVerifySchema(pParse, iDb);
104100     iReg = ++pParse->nMem;
104101     if( sqlite3Tolower(zLeft[0])=='p' ){
104102       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
104103     }else{
104104       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
104105                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
104106     }
104107     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
104108     sqlite3VdbeSetNumCols(v, 1);
104109     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
104110     break;
104111   }
104112 
104113   /*
104114   **  PRAGMA [database.]locking_mode
104115   **  PRAGMA [database.]locking_mode = (normal|exclusive)
104116   */
104117   case PragTyp_LOCKING_MODE: {
104118     const char *zRet = "normal";
104119     int eMode = getLockingMode(zRight);
104120 
104121     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
104122       /* Simple "PRAGMA locking_mode;" statement. This is a query for
104123       ** the current default locking mode (which may be different to
104124       ** the locking-mode of the main database).
104125       */
104126       eMode = db->dfltLockMode;
104127     }else{
104128       Pager *pPager;
104129       if( pId2->n==0 ){
104130         /* This indicates that no database name was specified as part
104131         ** of the PRAGMA command. In this case the locking-mode must be
104132         ** set on all attached databases, as well as the main db file.
104133         **
104134         ** Also, the sqlite3.dfltLockMode variable is set so that
104135         ** any subsequently attached databases also use the specified
104136         ** locking mode.
104137         */
104138         int ii;
104139         assert(pDb==&db->aDb[0]);
104140         for(ii=2; ii<db->nDb; ii++){
104141           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
104142           sqlite3PagerLockingMode(pPager, eMode);
104143         }
104144         db->dfltLockMode = (u8)eMode;
104145       }
104146       pPager = sqlite3BtreePager(pDb->pBt);
104147       eMode = sqlite3PagerLockingMode(pPager, eMode);
104148     }
104149 
104150     assert( eMode==PAGER_LOCKINGMODE_NORMAL
104151             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
104152     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
104153       zRet = "exclusive";
104154     }
104155     sqlite3VdbeSetNumCols(v, 1);
104156     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
104157     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
104158     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
104159     break;
104160   }
104161 
104162   /*
104163   **  PRAGMA [database.]journal_mode
104164   **  PRAGMA [database.]journal_mode =
104165   **                      (delete|persist|off|truncate|memory|wal|off)
104166   */
104167   case PragTyp_JOURNAL_MODE: {
104168     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
104169     int ii;           /* Loop counter */
104170 
104171     sqlite3VdbeSetNumCols(v, 1);
104172     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
104173 
104174     if( zRight==0 ){
104175       /* If there is no "=MODE" part of the pragma, do a query for the
104176       ** current mode */
104177       eMode = PAGER_JOURNALMODE_QUERY;
104178     }else{
104179       const char *zMode;
104180       int n = sqlite3Strlen30(zRight);
104181       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
104182         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
104183       }
104184       if( !zMode ){
104185         /* If the "=MODE" part does not match any known journal mode,
104186         ** then do a query */
104187         eMode = PAGER_JOURNALMODE_QUERY;
104188       }
104189     }
104190     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
104191       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
104192       iDb = 0;
104193       pId2->n = 1;
104194     }
104195     for(ii=db->nDb-1; ii>=0; ii--){
104196       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
104197         sqlite3VdbeUsesBtree(v, ii);
104198         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
104199       }
104200     }
104201     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
104202     break;
104203   }
104204 
104205   /*
104206   **  PRAGMA [database.]journal_size_limit
104207   **  PRAGMA [database.]journal_size_limit=N
104208   **
104209   ** Get or set the size limit on rollback journal files.
104210   */
104211   case PragTyp_JOURNAL_SIZE_LIMIT: {
104212     Pager *pPager = sqlite3BtreePager(pDb->pBt);
104213     i64 iLimit = -2;
104214     if( zRight ){
104215       sqlite3DecOrHexToI64(zRight, &iLimit);
104216       if( iLimit<-1 ) iLimit = -1;
104217     }
104218     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
104219     returnSingleInt(pParse, "journal_size_limit", iLimit);
104220     break;
104221   }
104222 
104223 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
104224 
104225   /*
104226   **  PRAGMA [database.]auto_vacuum
104227   **  PRAGMA [database.]auto_vacuum=N
104228   **
104229   ** Get or set the value of the database 'auto-vacuum' parameter.
104230   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
104231   */
104232 #ifndef SQLITE_OMIT_AUTOVACUUM
104233   case PragTyp_AUTO_VACUUM: {
104234     Btree *pBt = pDb->pBt;
104235     assert( pBt!=0 );
104236     if( !zRight ){
104237       returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
104238     }else{
104239       int eAuto = getAutoVacuum(zRight);
104240       assert( eAuto>=0 && eAuto<=2 );
104241       db->nextAutovac = (u8)eAuto;
104242       /* Call SetAutoVacuum() to set initialize the internal auto and
104243       ** incr-vacuum flags. This is required in case this connection
104244       ** creates the database file. It is important that it is created
104245       ** as an auto-vacuum capable db.
104246       */
104247       rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
104248       if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
104249         /* When setting the auto_vacuum mode to either "full" or
104250         ** "incremental", write the value of meta[6] in the database
104251         ** file. Before writing to meta[6], check that meta[3] indicates
104252         ** that this really is an auto-vacuum capable database.
104253         */
104254         static const int iLn = VDBE_OFFSET_LINENO(2);
104255         static const VdbeOpList setMeta6[] = {
104256           { OP_Transaction,    0,         1,                 0},    /* 0 */
104257           { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
104258           { OP_If,             1,         0,                 0},    /* 2 */
104259           { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
104260           { OP_Integer,        0,         1,                 0},    /* 4 */
104261           { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
104262         };
104263         int iAddr;
104264         iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
104265         sqlite3VdbeChangeP1(v, iAddr, iDb);
104266         sqlite3VdbeChangeP1(v, iAddr+1, iDb);
104267         sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
104268         sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
104269         sqlite3VdbeChangeP1(v, iAddr+5, iDb);
104270         sqlite3VdbeUsesBtree(v, iDb);
104271       }
104272     }
104273     break;
104274   }
104275 #endif
104276 
104277   /*
104278   **  PRAGMA [database.]incremental_vacuum(N)
104279   **
104280   ** Do N steps of incremental vacuuming on a database.
104281   */
104282 #ifndef SQLITE_OMIT_AUTOVACUUM
104283   case PragTyp_INCREMENTAL_VACUUM: {
104284     int iLimit, addr;
104285     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
104286       iLimit = 0x7fffffff;
104287     }
104288     sqlite3BeginWriteOperation(pParse, 0, iDb);
104289     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
104290     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
104291     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
104292     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
104293     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
104294     sqlite3VdbeJumpHere(v, addr);
104295     break;
104296   }
104297 #endif
104298 
104299 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
104300   /*
104301   **  PRAGMA [database.]cache_size
104302   **  PRAGMA [database.]cache_size=N
104303   **
104304   ** The first form reports the current local setting for the
104305   ** page cache size. The second form sets the local
104306   ** page cache size value.  If N is positive then that is the
104307   ** number of pages in the cache.  If N is negative, then the
104308   ** number of pages is adjusted so that the cache uses -N kibibytes
104309   ** of memory.
104310   */
104311   case PragTyp_CACHE_SIZE: {
104312     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
104313     if( !zRight ){
104314       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
104315     }else{
104316       int size = sqlite3Atoi(zRight);
104317       pDb->pSchema->cache_size = size;
104318       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
104319     }
104320     break;
104321   }
104322 
104323   /*
104324   **  PRAGMA [database.]mmap_size(N)
104325   **
104326   ** Used to set mapping size limit. The mapping size limit is
104327   ** used to limit the aggregate size of all memory mapped regions of the
104328   ** database file. If this parameter is set to zero, then memory mapping
104329   ** is not used at all.  If N is negative, then the default memory map
104330   ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
104331   ** The parameter N is measured in bytes.
104332   **
104333   ** This value is advisory.  The underlying VFS is free to memory map
104334   ** as little or as much as it wants.  Except, if N is set to 0 then the
104335   ** upper layers will never invoke the xFetch interfaces to the VFS.
104336   */
104337   case PragTyp_MMAP_SIZE: {
104338     sqlite3_int64 sz;
104339 #if SQLITE_MAX_MMAP_SIZE>0
104340     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
104341     if( zRight ){
104342       int ii;
104343       sqlite3DecOrHexToI64(zRight, &sz);
104344       if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
104345       if( pId2->n==0 ) db->szMmap = sz;
104346       for(ii=db->nDb-1; ii>=0; ii--){
104347         if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
104348           sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
104349         }
104350       }
104351     }
104352     sz = -1;
104353     rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
104354 #else
104355     sz = 0;
104356     rc = SQLITE_OK;
104357 #endif
104358     if( rc==SQLITE_OK ){
104359       returnSingleInt(pParse, "mmap_size", sz);
104360     }else if( rc!=SQLITE_NOTFOUND ){
104361       pParse->nErr++;
104362       pParse->rc = rc;
104363     }
104364     break;
104365   }
104366 
104367   /*
104368   **   PRAGMA temp_store
104369   **   PRAGMA temp_store = "default"|"memory"|"file"
104370   **
104371   ** Return or set the local value of the temp_store flag.  Changing
104372   ** the local value does not make changes to the disk file and the default
104373   ** value will be restored the next time the database is opened.
104374   **
104375   ** Note that it is possible for the library compile-time options to
104376   ** override this setting
104377   */
104378   case PragTyp_TEMP_STORE: {
104379     if( !zRight ){
104380       returnSingleInt(pParse, "temp_store", db->temp_store);
104381     }else{
104382       changeTempStorage(pParse, zRight);
104383     }
104384     break;
104385   }
104386 
104387   /*
104388   **   PRAGMA temp_store_directory
104389   **   PRAGMA temp_store_directory = ""|"directory_name"
104390   **
104391   ** Return or set the local value of the temp_store_directory flag.  Changing
104392   ** the value sets a specific directory to be used for temporary files.
104393   ** Setting to a null string reverts to the default temporary directory search.
104394   ** If temporary directory is changed, then invalidateTempStorage.
104395   **
104396   */
104397   case PragTyp_TEMP_STORE_DIRECTORY: {
104398     if( !zRight ){
104399       if( sqlite3_temp_directory ){
104400         sqlite3VdbeSetNumCols(v, 1);
104401         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
104402             "temp_store_directory", SQLITE_STATIC);
104403         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
104404         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
104405       }
104406     }else{
104407 #ifndef SQLITE_OMIT_WSD
104408       if( zRight[0] ){
104409         int res;
104410         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
104411         if( rc!=SQLITE_OK || res==0 ){
104412           sqlite3ErrorMsg(pParse, "not a writable directory");
104413           goto pragma_out;
104414         }
104415       }
104416       if( SQLITE_TEMP_STORE==0
104417        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
104418        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
104419       ){
104420         invalidateTempStorage(pParse);
104421       }
104422       sqlite3_free(sqlite3_temp_directory);
104423       if( zRight[0] ){
104424         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
104425       }else{
104426         sqlite3_temp_directory = 0;
104427       }
104428 #endif /* SQLITE_OMIT_WSD */
104429     }
104430     break;
104431   }
104432 
104433 #if SQLITE_OS_WIN
104434   /*
104435   **   PRAGMA data_store_directory
104436   **   PRAGMA data_store_directory = ""|"directory_name"
104437   **
104438   ** Return or set the local value of the data_store_directory flag.  Changing
104439   ** the value sets a specific directory to be used for database files that
104440   ** were specified with a relative pathname.  Setting to a null string reverts
104441   ** to the default database directory, which for database files specified with
104442   ** a relative path will probably be based on the current directory for the
104443   ** process.  Database file specified with an absolute path are not impacted
104444   ** by this setting, regardless of its value.
104445   **
104446   */
104447   case PragTyp_DATA_STORE_DIRECTORY: {
104448     if( !zRight ){
104449       if( sqlite3_data_directory ){
104450         sqlite3VdbeSetNumCols(v, 1);
104451         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
104452             "data_store_directory", SQLITE_STATIC);
104453         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
104454         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
104455       }
104456     }else{
104457 #ifndef SQLITE_OMIT_WSD
104458       if( zRight[0] ){
104459         int res;
104460         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
104461         if( rc!=SQLITE_OK || res==0 ){
104462           sqlite3ErrorMsg(pParse, "not a writable directory");
104463           goto pragma_out;
104464         }
104465       }
104466       sqlite3_free(sqlite3_data_directory);
104467       if( zRight[0] ){
104468         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
104469       }else{
104470         sqlite3_data_directory = 0;
104471       }
104472 #endif /* SQLITE_OMIT_WSD */
104473     }
104474     break;
104475   }
104476 #endif
104477 
104478 #if SQLITE_ENABLE_LOCKING_STYLE
104479   /*
104480   **   PRAGMA [database.]lock_proxy_file
104481   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
104482   **
104483   ** Return or set the value of the lock_proxy_file flag.  Changing
104484   ** the value sets a specific file to be used for database access locks.
104485   **
104486   */
104487   case PragTyp_LOCK_PROXY_FILE: {
104488     if( !zRight ){
104489       Pager *pPager = sqlite3BtreePager(pDb->pBt);
104490       char *proxy_file_path = NULL;
104491       sqlite3_file *pFile = sqlite3PagerFile(pPager);
104492       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
104493                            &proxy_file_path);
104494 
104495       if( proxy_file_path ){
104496         sqlite3VdbeSetNumCols(v, 1);
104497         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
104498                               "lock_proxy_file", SQLITE_STATIC);
104499         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
104500         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
104501       }
104502     }else{
104503       Pager *pPager = sqlite3BtreePager(pDb->pBt);
104504       sqlite3_file *pFile = sqlite3PagerFile(pPager);
104505       int res;
104506       if( zRight[0] ){
104507         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
104508                                      zRight);
104509       } else {
104510         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
104511                                      NULL);
104512       }
104513       if( res!=SQLITE_OK ){
104514         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
104515         goto pragma_out;
104516       }
104517     }
104518     break;
104519   }
104520 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
104521 
104522   /*
104523   **   PRAGMA [database.]synchronous
104524   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
104525   **
104526   ** Return or set the local value of the synchronous flag.  Changing
104527   ** the local value does not make changes to the disk file and the
104528   ** default value will be restored the next time the database is
104529   ** opened.
104530   */
104531   case PragTyp_SYNCHRONOUS: {
104532     if( !zRight ){
104533       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
104534     }else{
104535       if( !db->autoCommit ){
104536         sqlite3ErrorMsg(pParse,
104537             "Safety level may not be changed inside a transaction");
104538       }else{
104539         int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
104540         if( iLevel==0 ) iLevel = 1;
104541         pDb->safety_level = iLevel;
104542         setAllPagerFlags(db);
104543       }
104544     }
104545     break;
104546   }
104547 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
104548 
104549 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
104550   case PragTyp_FLAG: {
104551     if( zRight==0 ){
104552       returnSingleInt(pParse, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
104553     }else{
104554       int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
104555       if( db->autoCommit==0 ){
104556         /* Foreign key support may not be enabled or disabled while not
104557         ** in auto-commit mode.  */
104558         mask &= ~(SQLITE_ForeignKeys);
104559       }
104560 #if SQLITE_USER_AUTHENTICATION
104561       if( db->auth.authLevel==UAUTH_User ){
104562         /* Do not allow non-admin users to modify the schema arbitrarily */
104563         mask &= ~(SQLITE_WriteSchema);
104564       }
104565 #endif
104566 
104567       if( sqlite3GetBoolean(zRight, 0) ){
104568         db->flags |= mask;
104569       }else{
104570         db->flags &= ~mask;
104571         if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
104572       }
104573 
104574       /* Many of the flag-pragmas modify the code generated by the SQL
104575       ** compiler (eg. count_changes). So add an opcode to expire all
104576       ** compiled SQL statements after modifying a pragma value.
104577       */
104578       sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
104579       setAllPagerFlags(db);
104580     }
104581     break;
104582   }
104583 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
104584 
104585 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
104586   /*
104587   **   PRAGMA table_info(<table>)
104588   **
104589   ** Return a single row for each column of the named table. The columns of
104590   ** the returned data set are:
104591   **
104592   ** cid:        Column id (numbered from left to right, starting at 0)
104593   ** name:       Column name
104594   ** type:       Column declaration type.
104595   ** notnull:    True if 'NOT NULL' is part of column declaration
104596   ** dflt_value: The default value for the column, if any.
104597   */
104598   case PragTyp_TABLE_INFO: if( zRight ){
104599     Table *pTab;
104600     pTab = sqlite3FindTable(db, zRight, zDb);
104601     if( pTab ){
104602       int i, k;
104603       int nHidden = 0;
104604       Column *pCol;
104605       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
104606       sqlite3VdbeSetNumCols(v, 6);
104607       pParse->nMem = 6;
104608       sqlite3CodeVerifySchema(pParse, iDb);
104609       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
104610       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
104611       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
104612       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
104613       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
104614       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
104615       sqlite3ViewGetColumnNames(pParse, pTab);
104616       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
104617         if( IsHiddenColumn(pCol) ){
104618           nHidden++;
104619           continue;
104620         }
104621         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
104622         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
104623         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
104624            pCol->zType ? pCol->zType : "", 0);
104625         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
104626         if( pCol->zDflt ){
104627           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
104628         }else{
104629           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
104630         }
104631         if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
104632           k = 0;
104633         }else if( pPk==0 ){
104634           k = 1;
104635         }else{
104636           for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
104637         }
104638         sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
104639         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
104640       }
104641     }
104642   }
104643   break;
104644 
104645   case PragTyp_STATS: {
104646     Index *pIdx;
104647     HashElem *i;
104648     v = sqlite3GetVdbe(pParse);
104649     sqlite3VdbeSetNumCols(v, 4);
104650     pParse->nMem = 4;
104651     sqlite3CodeVerifySchema(pParse, iDb);
104652     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
104653     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
104654     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
104655     sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
104656     for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
104657       Table *pTab = sqliteHashData(i);
104658       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
104659       sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
104660       sqlite3VdbeAddOp2(v, OP_Integer,
104661                            (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
104662       sqlite3VdbeAddOp2(v, OP_Integer,
104663           (int)sqlite3LogEstToInt(pTab->nRowLogEst), 4);
104664       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
104665       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
104666         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
104667         sqlite3VdbeAddOp2(v, OP_Integer,
104668                              (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
104669         sqlite3VdbeAddOp2(v, OP_Integer,
104670             (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]), 4);
104671         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
104672       }
104673     }
104674   }
104675   break;
104676 
104677   case PragTyp_INDEX_INFO: if( zRight ){
104678     Index *pIdx;
104679     Table *pTab;
104680     pIdx = sqlite3FindIndex(db, zRight, zDb);
104681     if( pIdx ){
104682       int i;
104683       int mx;
104684       if( pPragma->iArg ){
104685         /* PRAGMA index_xinfo (newer version with more rows and columns) */
104686         mx = pIdx->nColumn;
104687         pParse->nMem = 6;
104688       }else{
104689         /* PRAGMA index_info (legacy version) */
104690         mx = pIdx->nKeyCol;
104691         pParse->nMem = 3;
104692       }
104693       pTab = pIdx->pTable;
104694       sqlite3VdbeSetNumCols(v, pParse->nMem);
104695       sqlite3CodeVerifySchema(pParse, iDb);
104696       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
104697       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
104698       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
104699       if( pPragma->iArg ){
104700         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "desc", SQLITE_STATIC);
104701         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "coll", SQLITE_STATIC);
104702         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "key", SQLITE_STATIC);
104703       }
104704       for(i=0; i<mx; i++){
104705         i16 cnum = pIdx->aiColumn[i];
104706         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
104707         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
104708         if( cnum<0 ){
104709           sqlite3VdbeAddOp2(v, OP_Null, 0, 3);
104710         }else{
104711           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
104712         }
104713         if( pPragma->iArg ){
104714           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->aSortOrder[i], 4);
104715           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, pIdx->azColl[i], 0);
104716           sqlite3VdbeAddOp2(v, OP_Integer, i<pIdx->nKeyCol, 6);
104717         }
104718         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
104719       }
104720     }
104721   }
104722   break;
104723 
104724   case PragTyp_INDEX_LIST: if( zRight ){
104725     Index *pIdx;
104726     Table *pTab;
104727     int i;
104728     pTab = sqlite3FindTable(db, zRight, zDb);
104729     if( pTab ){
104730       v = sqlite3GetVdbe(pParse);
104731       sqlite3VdbeSetNumCols(v, 5);
104732       pParse->nMem = 5;
104733       sqlite3CodeVerifySchema(pParse, iDb);
104734       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
104735       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
104736       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
104737       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "origin", SQLITE_STATIC);
104738       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "partial", SQLITE_STATIC);
104739       for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
104740         const char *azOrigin[] = { "c", "u", "pk" };
104741         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
104742         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
104743         sqlite3VdbeAddOp2(v, OP_Integer, IsUniqueIndex(pIdx), 3);
104744         sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, azOrigin[pIdx->idxType], 0);
104745         sqlite3VdbeAddOp2(v, OP_Integer, pIdx->pPartIdxWhere!=0, 5);
104746         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
104747       }
104748     }
104749   }
104750   break;
104751 
104752   case PragTyp_DATABASE_LIST: {
104753     int i;
104754     sqlite3VdbeSetNumCols(v, 3);
104755     pParse->nMem = 3;
104756     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
104757     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
104758     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
104759     for(i=0; i<db->nDb; i++){
104760       if( db->aDb[i].pBt==0 ) continue;
104761       assert( db->aDb[i].zName!=0 );
104762       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
104763       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
104764       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
104765            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
104766       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
104767     }
104768   }
104769   break;
104770 
104771   case PragTyp_COLLATION_LIST: {
104772     int i = 0;
104773     HashElem *p;
104774     sqlite3VdbeSetNumCols(v, 2);
104775     pParse->nMem = 2;
104776     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
104777     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
104778     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
104779       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
104780       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
104781       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
104782       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
104783     }
104784   }
104785   break;
104786 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
104787 
104788 #ifndef SQLITE_OMIT_FOREIGN_KEY
104789   case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
104790     FKey *pFK;
104791     Table *pTab;
104792     pTab = sqlite3FindTable(db, zRight, zDb);
104793     if( pTab ){
104794       v = sqlite3GetVdbe(pParse);
104795       pFK = pTab->pFKey;
104796       if( pFK ){
104797         int i = 0;
104798         sqlite3VdbeSetNumCols(v, 8);
104799         pParse->nMem = 8;
104800         sqlite3CodeVerifySchema(pParse, iDb);
104801         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
104802         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
104803         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
104804         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
104805         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
104806         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
104807         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
104808         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
104809         while(pFK){
104810           int j;
104811           for(j=0; j<pFK->nCol; j++){
104812             char *zCol = pFK->aCol[j].zCol;
104813             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
104814             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
104815             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
104816             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
104817             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
104818             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
104819                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
104820             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
104821             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
104822             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
104823             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
104824             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
104825           }
104826           ++i;
104827           pFK = pFK->pNextFrom;
104828         }
104829       }
104830     }
104831   }
104832   break;
104833 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
104834 
104835 #ifndef SQLITE_OMIT_FOREIGN_KEY
104836 #ifndef SQLITE_OMIT_TRIGGER
104837   case PragTyp_FOREIGN_KEY_CHECK: {
104838     FKey *pFK;             /* A foreign key constraint */
104839     Table *pTab;           /* Child table contain "REFERENCES" keyword */
104840     Table *pParent;        /* Parent table that child points to */
104841     Index *pIdx;           /* Index in the parent table */
104842     int i;                 /* Loop counter:  Foreign key number for pTab */
104843     int j;                 /* Loop counter:  Field of the foreign key */
104844     HashElem *k;           /* Loop counter:  Next table in schema */
104845     int x;                 /* result variable */
104846     int regResult;         /* 3 registers to hold a result row */
104847     int regKey;            /* Register to hold key for checking the FK */
104848     int regRow;            /* Registers to hold a row from pTab */
104849     int addrTop;           /* Top of a loop checking foreign keys */
104850     int addrOk;            /* Jump here if the key is OK */
104851     int *aiCols;           /* child to parent column mapping */
104852 
104853     regResult = pParse->nMem+1;
104854     pParse->nMem += 4;
104855     regKey = ++pParse->nMem;
104856     regRow = ++pParse->nMem;
104857     v = sqlite3GetVdbe(pParse);
104858     sqlite3VdbeSetNumCols(v, 4);
104859     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
104860     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
104861     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
104862     sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
104863     sqlite3CodeVerifySchema(pParse, iDb);
104864     k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
104865     while( k ){
104866       if( zRight ){
104867         pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
104868         k = 0;
104869       }else{
104870         pTab = (Table*)sqliteHashData(k);
104871         k = sqliteHashNext(k);
104872       }
104873       if( pTab==0 || pTab->pFKey==0 ) continue;
104874       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
104875       if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
104876       sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
104877       sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
104878                         P4_TRANSIENT);
104879       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
104880         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
104881         if( pParent==0 ) continue;
104882         pIdx = 0;
104883         sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
104884         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
104885         if( x==0 ){
104886           if( pIdx==0 ){
104887             sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
104888           }else{
104889             sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
104890             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
104891           }
104892         }else{
104893           k = 0;
104894           break;
104895         }
104896       }
104897       assert( pParse->nErr>0 || pFK==0 );
104898       if( pFK ) break;
104899       if( pParse->nTab<i ) pParse->nTab = i;
104900       addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
104901       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
104902         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
104903         pIdx = 0;
104904         aiCols = 0;
104905         if( pParent ){
104906           x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
104907           assert( x==0 );
104908         }
104909         addrOk = sqlite3VdbeMakeLabel(v);
104910         if( pParent && pIdx==0 ){
104911           int iKey = pFK->aCol[0].iFrom;
104912           assert( iKey>=0 && iKey<pTab->nCol );
104913           if( iKey!=pTab->iPKey ){
104914             sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
104915             sqlite3ColumnDefault(v, pTab, iKey, regRow);
104916             sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
104917             sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
104918                sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
104919           }else{
104920             sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
104921           }
104922           sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
104923           sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
104924           sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
104925         }else{
104926           for(j=0; j<pFK->nCol; j++){
104927             sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
104928                             aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
104929             sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
104930           }
104931           if( pParent ){
104932             sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
104933                               sqlite3IndexAffinityStr(v,pIdx), pFK->nCol);
104934             sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
104935             VdbeCoverage(v);
104936           }
104937         }
104938         sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
104939         sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
104940                           pFK->zTo, P4_TRANSIENT);
104941         sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
104942         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
104943         sqlite3VdbeResolveLabel(v, addrOk);
104944         sqlite3DbFree(db, aiCols);
104945       }
104946       sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
104947       sqlite3VdbeJumpHere(v, addrTop);
104948     }
104949   }
104950   break;
104951 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
104952 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
104953 
104954 #ifndef NDEBUG
104955   case PragTyp_PARSER_TRACE: {
104956     if( zRight ){
104957       if( sqlite3GetBoolean(zRight, 0) ){
104958         sqlite3ParserTrace(stderr, "parser: ");
104959       }else{
104960         sqlite3ParserTrace(0, 0);
104961       }
104962     }
104963   }
104964   break;
104965 #endif
104966 
104967   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
104968   ** used will be case sensitive or not depending on the RHS.
104969   */
104970   case PragTyp_CASE_SENSITIVE_LIKE: {
104971     if( zRight ){
104972       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
104973     }
104974   }
104975   break;
104976 
104977 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
104978 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
104979 #endif
104980 
104981 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
104982   /* Pragma "quick_check" is reduced version of
104983   ** integrity_check designed to detect most database corruption
104984   ** without most of the overhead of a full integrity-check.
104985   */
104986   case PragTyp_INTEGRITY_CHECK: {
104987     int i, j, addr, mxErr;
104988 
104989     /* Code that appears at the end of the integrity check.  If no error
104990     ** messages have been generated, output OK.  Otherwise output the
104991     ** error message
104992     */
104993     static const int iLn = VDBE_OFFSET_LINENO(2);
104994     static const VdbeOpList endCode[] = {
104995       { OP_IfNeg,       1, 0,        0},    /* 0 */
104996       { OP_String8,     0, 3,        0},    /* 1 */
104997       { OP_ResultRow,   3, 1,        0},
104998     };
104999 
105000     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
105001 
105002     /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
105003     ** then iDb is set to the index of the database identified by <db>.
105004     ** In this case, the integrity of database iDb only is verified by
105005     ** the VDBE created below.
105006     **
105007     ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
105008     ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
105009     ** to -1 here, to indicate that the VDBE should verify the integrity
105010     ** of all attached databases.  */
105011     assert( iDb>=0 );
105012     assert( iDb==0 || pId2->z );
105013     if( pId2->z==0 ) iDb = -1;
105014 
105015     /* Initialize the VDBE program */
105016     pParse->nMem = 6;
105017     sqlite3VdbeSetNumCols(v, 1);
105018     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
105019 
105020     /* Set the maximum error count */
105021     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
105022     if( zRight ){
105023       sqlite3GetInt32(zRight, &mxErr);
105024       if( mxErr<=0 ){
105025         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
105026       }
105027     }
105028     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
105029 
105030     /* Do an integrity check on each database file */
105031     for(i=0; i<db->nDb; i++){
105032       HashElem *x;
105033       Hash *pTbls;
105034       int cnt = 0;
105035 
105036       if( OMIT_TEMPDB && i==1 ) continue;
105037       if( iDb>=0 && i!=iDb ) continue;
105038 
105039       sqlite3CodeVerifySchema(pParse, i);
105040       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
105041       VdbeCoverage(v);
105042       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
105043       sqlite3VdbeJumpHere(v, addr);
105044 
105045       /* Do an integrity check of the B-Tree
105046       **
105047       ** Begin by filling registers 2, 3, ... with the root pages numbers
105048       ** for all tables and indices in the database.
105049       */
105050       assert( sqlite3SchemaMutexHeld(db, i, 0) );
105051       pTbls = &db->aDb[i].pSchema->tblHash;
105052       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
105053         Table *pTab = sqliteHashData(x);
105054         Index *pIdx;
105055         if( HasRowid(pTab) ){
105056           sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
105057           VdbeComment((v, "%s", pTab->zName));
105058           cnt++;
105059         }
105060         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
105061           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
105062           VdbeComment((v, "%s", pIdx->zName));
105063           cnt++;
105064         }
105065       }
105066 
105067       /* Make sure sufficient number of registers have been allocated */
105068       pParse->nMem = MAX( pParse->nMem, cnt+8 );
105069 
105070       /* Do the b-tree integrity checks */
105071       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
105072       sqlite3VdbeChangeP5(v, (u8)i);
105073       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
105074       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
105075          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
105076          P4_DYNAMIC);
105077       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
105078       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
105079       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
105080       sqlite3VdbeJumpHere(v, addr);
105081 
105082       /* Make sure all the indices are constructed correctly.
105083       */
105084       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
105085         Table *pTab = sqliteHashData(x);
105086         Index *pIdx, *pPk;
105087         Index *pPrior = 0;
105088         int loopTop;
105089         int iDataCur, iIdxCur;
105090         int r1 = -1;
105091 
105092         if( pTab->pIndex==0 ) continue;
105093         pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
105094         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
105095         VdbeCoverage(v);
105096         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
105097         sqlite3VdbeJumpHere(v, addr);
105098         sqlite3ExprCacheClear(pParse);
105099         sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
105100                                    1, 0, &iDataCur, &iIdxCur);
105101         sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
105102         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
105103           sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
105104         }
105105         pParse->nMem = MAX(pParse->nMem, 8+j);
105106         sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
105107         loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
105108         /* Verify that all NOT NULL columns really are NOT NULL */
105109         for(j=0; j<pTab->nCol; j++){
105110           char *zErr;
105111           int jmp2, jmp3;
105112           if( j==pTab->iPKey ) continue;
105113           if( pTab->aCol[j].notNull==0 ) continue;
105114           sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
105115           sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
105116           jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
105117           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
105118           zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
105119                               pTab->aCol[j].zName);
105120           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
105121           sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
105122           jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
105123           sqlite3VdbeAddOp0(v, OP_Halt);
105124           sqlite3VdbeJumpHere(v, jmp2);
105125           sqlite3VdbeJumpHere(v, jmp3);
105126         }
105127         /* Validate index entries for the current row */
105128         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
105129           int jmp2, jmp3, jmp4, jmp5;
105130           int ckUniq = sqlite3VdbeMakeLabel(v);
105131           if( pPk==pIdx ) continue;
105132           r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
105133                                        pPrior, r1);
105134           pPrior = pIdx;
105135           sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
105136           /* Verify that an index entry exists for the current table row */
105137           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
105138                                       pIdx->nColumn); VdbeCoverage(v);
105139           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
105140           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC);
105141           sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
105142           sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
105143                             " missing from index ", P4_STATIC);
105144           sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
105145           jmp5 = sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
105146                                    pIdx->zName, P4_TRANSIENT);
105147           sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
105148           sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
105149           jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
105150           sqlite3VdbeAddOp0(v, OP_Halt);
105151           sqlite3VdbeJumpHere(v, jmp2);
105152           /* For UNIQUE indexes, verify that only one entry exists with the
105153           ** current key.  The entry is unique if (1) any column is NULL
105154           ** or (2) the next entry has a different key */
105155           if( IsUniqueIndex(pIdx) ){
105156             int uniqOk = sqlite3VdbeMakeLabel(v);
105157             int jmp6;
105158             int kk;
105159             for(kk=0; kk<pIdx->nKeyCol; kk++){
105160               int iCol = pIdx->aiColumn[kk];
105161               assert( iCol>=0 && iCol<pTab->nCol );
105162               if( pTab->aCol[iCol].notNull ) continue;
105163               sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
105164               VdbeCoverage(v);
105165             }
105166             jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
105167             sqlite3VdbeAddOp2(v, OP_Goto, 0, uniqOk);
105168             sqlite3VdbeJumpHere(v, jmp6);
105169             sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
105170                                  pIdx->nKeyCol); VdbeCoverage(v);
105171             sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
105172             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
105173                               "non-unique entry in index ", P4_STATIC);
105174             sqlite3VdbeAddOp2(v, OP_Goto, 0, jmp5);
105175             sqlite3VdbeResolveLabel(v, uniqOk);
105176           }
105177           sqlite3VdbeJumpHere(v, jmp4);
105178           sqlite3ResolvePartIdxLabel(pParse, jmp3);
105179         }
105180         sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
105181         sqlite3VdbeJumpHere(v, loopTop-1);
105182 #ifndef SQLITE_OMIT_BTREECOUNT
105183         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
105184                      "wrong # of entries in index ", P4_STATIC);
105185         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
105186           if( pPk==pIdx ) continue;
105187           addr = sqlite3VdbeCurrentAddr(v);
105188           sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
105189           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
105190           sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
105191           sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
105192           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
105193           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
105194           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
105195           sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
105196           sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
105197         }
105198 #endif /* SQLITE_OMIT_BTREECOUNT */
105199       }
105200     }
105201     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
105202     sqlite3VdbeChangeP3(v, addr, -mxErr);
105203     sqlite3VdbeJumpHere(v, addr);
105204     sqlite3VdbeChangeP4(v, addr+1, "ok", P4_STATIC);
105205   }
105206   break;
105207 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
105208 
105209 #ifndef SQLITE_OMIT_UTF16
105210   /*
105211   **   PRAGMA encoding
105212   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
105213   **
105214   ** In its first form, this pragma returns the encoding of the main
105215   ** database. If the database is not initialized, it is initialized now.
105216   **
105217   ** The second form of this pragma is a no-op if the main database file
105218   ** has not already been initialized. In this case it sets the default
105219   ** encoding that will be used for the main database file if a new file
105220   ** is created. If an existing main database file is opened, then the
105221   ** default text encoding for the existing database is used.
105222   **
105223   ** In all cases new databases created using the ATTACH command are
105224   ** created to use the same default text encoding as the main database. If
105225   ** the main database has not been initialized and/or created when ATTACH
105226   ** is executed, this is done before the ATTACH operation.
105227   **
105228   ** In the second form this pragma sets the text encoding to be used in
105229   ** new database files created using this database handle. It is only
105230   ** useful if invoked immediately after the main database i
105231   */
105232   case PragTyp_ENCODING: {
105233     static const struct EncName {
105234       char *zName;
105235       u8 enc;
105236     } encnames[] = {
105237       { "UTF8",     SQLITE_UTF8        },
105238       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
105239       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
105240       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
105241       { "UTF16le",  SQLITE_UTF16LE     },
105242       { "UTF16be",  SQLITE_UTF16BE     },
105243       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
105244       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
105245       { 0, 0 }
105246     };
105247     const struct EncName *pEnc;
105248     if( !zRight ){    /* "PRAGMA encoding" */
105249       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
105250       sqlite3VdbeSetNumCols(v, 1);
105251       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
105252       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
105253       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
105254       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
105255       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
105256       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
105257       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
105258     }else{                        /* "PRAGMA encoding = XXX" */
105259       /* Only change the value of sqlite.enc if the database handle is not
105260       ** initialized. If the main database exists, the new sqlite.enc value
105261       ** will be overwritten when the schema is next loaded. If it does not
105262       ** already exists, it will be created to use the new encoding value.
105263       */
105264       if(
105265         !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
105266         DbHasProperty(db, 0, DB_Empty)
105267       ){
105268         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
105269           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
105270             SCHEMA_ENC(db) = ENC(db) =
105271                 pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
105272             break;
105273           }
105274         }
105275         if( !pEnc->zName ){
105276           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
105277         }
105278       }
105279     }
105280   }
105281   break;
105282 #endif /* SQLITE_OMIT_UTF16 */
105283 
105284 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
105285   /*
105286   **   PRAGMA [database.]schema_version
105287   **   PRAGMA [database.]schema_version = <integer>
105288   **
105289   **   PRAGMA [database.]user_version
105290   **   PRAGMA [database.]user_version = <integer>
105291   **
105292   **   PRAGMA [database.]freelist_count = <integer>
105293   **
105294   **   PRAGMA [database.]application_id
105295   **   PRAGMA [database.]application_id = <integer>
105296   **
105297   ** The pragma's schema_version and user_version are used to set or get
105298   ** the value of the schema-version and user-version, respectively. Both
105299   ** the schema-version and the user-version are 32-bit signed integers
105300   ** stored in the database header.
105301   **
105302   ** The schema-cookie is usually only manipulated internally by SQLite. It
105303   ** is incremented by SQLite whenever the database schema is modified (by
105304   ** creating or dropping a table or index). The schema version is used by
105305   ** SQLite each time a query is executed to ensure that the internal cache
105306   ** of the schema used when compiling the SQL query matches the schema of
105307   ** the database against which the compiled query is actually executed.
105308   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
105309   ** the schema-version is potentially dangerous and may lead to program
105310   ** crashes or database corruption. Use with caution!
105311   **
105312   ** The user-version is not used internally by SQLite. It may be used by
105313   ** applications for any purpose.
105314   */
105315   case PragTyp_HEADER_VALUE: {
105316     int iCookie = pPragma->iArg;  /* Which cookie to read or write */
105317     sqlite3VdbeUsesBtree(v, iDb);
105318     if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
105319       /* Write the specified cookie value */
105320       static const VdbeOpList setCookie[] = {
105321         { OP_Transaction,    0,  1,  0},    /* 0 */
105322         { OP_Integer,        0,  1,  0},    /* 1 */
105323         { OP_SetCookie,      0,  0,  1},    /* 2 */
105324       };
105325       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
105326       sqlite3VdbeChangeP1(v, addr, iDb);
105327       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
105328       sqlite3VdbeChangeP1(v, addr+2, iDb);
105329       sqlite3VdbeChangeP2(v, addr+2, iCookie);
105330     }else{
105331       /* Read the specified cookie value */
105332       static const VdbeOpList readCookie[] = {
105333         { OP_Transaction,     0,  0,  0},    /* 0 */
105334         { OP_ReadCookie,      0,  1,  0},    /* 1 */
105335         { OP_ResultRow,       1,  1,  0}
105336       };
105337       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
105338       sqlite3VdbeChangeP1(v, addr, iDb);
105339       sqlite3VdbeChangeP1(v, addr+1, iDb);
105340       sqlite3VdbeChangeP3(v, addr+1, iCookie);
105341       sqlite3VdbeSetNumCols(v, 1);
105342       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
105343     }
105344   }
105345   break;
105346 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
105347 
105348 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
105349   /*
105350   **   PRAGMA compile_options
105351   **
105352   ** Return the names of all compile-time options used in this build,
105353   ** one option per row.
105354   */
105355   case PragTyp_COMPILE_OPTIONS: {
105356     int i = 0;
105357     const char *zOpt;
105358     sqlite3VdbeSetNumCols(v, 1);
105359     pParse->nMem = 1;
105360     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
105361     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
105362       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
105363       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
105364     }
105365   }
105366   break;
105367 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
105368 
105369 #ifndef SQLITE_OMIT_WAL
105370   /*
105371   **   PRAGMA [database.]wal_checkpoint = passive|full|restart|truncate
105372   **
105373   ** Checkpoint the database.
105374   */
105375   case PragTyp_WAL_CHECKPOINT: {
105376     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
105377     int eMode = SQLITE_CHECKPOINT_PASSIVE;
105378     if( zRight ){
105379       if( sqlite3StrICmp(zRight, "full")==0 ){
105380         eMode = SQLITE_CHECKPOINT_FULL;
105381       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
105382         eMode = SQLITE_CHECKPOINT_RESTART;
105383       }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
105384         eMode = SQLITE_CHECKPOINT_TRUNCATE;
105385       }
105386     }
105387     sqlite3VdbeSetNumCols(v, 3);
105388     pParse->nMem = 3;
105389     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
105390     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
105391     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
105392 
105393     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
105394     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
105395   }
105396   break;
105397 
105398   /*
105399   **   PRAGMA wal_autocheckpoint
105400   **   PRAGMA wal_autocheckpoint = N
105401   **
105402   ** Configure a database connection to automatically checkpoint a database
105403   ** after accumulating N frames in the log. Or query for the current value
105404   ** of N.
105405   */
105406   case PragTyp_WAL_AUTOCHECKPOINT: {
105407     if( zRight ){
105408       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
105409     }
105410     returnSingleInt(pParse, "wal_autocheckpoint",
105411        db->xWalCallback==sqlite3WalDefaultHook ?
105412            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
105413   }
105414   break;
105415 #endif
105416 
105417   /*
105418   **  PRAGMA shrink_memory
105419   **
105420   ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
105421   ** connection on which it is invoked to free up as much memory as it
105422   ** can, by calling sqlite3_db_release_memory().
105423   */
105424   case PragTyp_SHRINK_MEMORY: {
105425     sqlite3_db_release_memory(db);
105426     break;
105427   }
105428 
105429   /*
105430   **   PRAGMA busy_timeout
105431   **   PRAGMA busy_timeout = N
105432   **
105433   ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
105434   ** if one is set.  If no busy handler or a different busy handler is set
105435   ** then 0 is returned.  Setting the busy_timeout to 0 or negative
105436   ** disables the timeout.
105437   */
105438   /*case PragTyp_BUSY_TIMEOUT*/ default: {
105439     assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
105440     if( zRight ){
105441       sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
105442     }
105443     returnSingleInt(pParse, "timeout",  db->busyTimeout);
105444     break;
105445   }
105446 
105447   /*
105448   **   PRAGMA soft_heap_limit
105449   **   PRAGMA soft_heap_limit = N
105450   **
105451   ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
105452   ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
105453   ** specified and is a non-negative integer.
105454   ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
105455   ** returns the same integer that would be returned by the
105456   ** sqlite3_soft_heap_limit64(-1) C-language function.
105457   */
105458   case PragTyp_SOFT_HEAP_LIMIT: {
105459     sqlite3_int64 N;
105460     if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
105461       sqlite3_soft_heap_limit64(N);
105462     }
105463     returnSingleInt(pParse, "soft_heap_limit",  sqlite3_soft_heap_limit64(-1));
105464     break;
105465   }
105466 
105467   /*
105468   **   PRAGMA threads
105469   **   PRAGMA threads = N
105470   **
105471   ** Configure the maximum number of worker threads.  Return the new
105472   ** maximum, which might be less than requested.
105473   */
105474   case PragTyp_THREADS: {
105475     sqlite3_int64 N;
105476     if( zRight
105477      && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
105478      && N>=0
105479     ){
105480       sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
105481     }
105482     returnSingleInt(pParse, "threads",
105483                     sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
105484     break;
105485   }
105486 
105487 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
105488   /*
105489   ** Report the current state of file logs for all databases
105490   */
105491   case PragTyp_LOCK_STATUS: {
105492     static const char *const azLockName[] = {
105493       "unlocked", "shared", "reserved", "pending", "exclusive"
105494     };
105495     int i;
105496     sqlite3VdbeSetNumCols(v, 2);
105497     pParse->nMem = 2;
105498     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
105499     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
105500     for(i=0; i<db->nDb; i++){
105501       Btree *pBt;
105502       const char *zState = "unknown";
105503       int j;
105504       if( db->aDb[i].zName==0 ) continue;
105505       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
105506       pBt = db->aDb[i].pBt;
105507       if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
105508         zState = "closed";
105509       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
105510                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
105511          zState = azLockName[j];
105512       }
105513       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
105514       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
105515     }
105516     break;
105517   }
105518 #endif
105519 
105520 #ifdef SQLITE_HAS_CODEC
105521   case PragTyp_KEY: {
105522     if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
105523     break;
105524   }
105525   case PragTyp_REKEY: {
105526     if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
105527     break;
105528   }
105529   case PragTyp_HEXKEY: {
105530     if( zRight ){
105531       u8 iByte;
105532       int i;
105533       char zKey[40];
105534       for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
105535         iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
105536         if( (i&1)!=0 ) zKey[i/2] = iByte;
105537       }
105538       if( (zLeft[3] & 0xf)==0xb ){
105539         sqlite3_key_v2(db, zDb, zKey, i/2);
105540       }else{
105541         sqlite3_rekey_v2(db, zDb, zKey, i/2);
105542       }
105543     }
105544     break;
105545   }
105546 #endif
105547 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
105548   case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
105549 #ifdef SQLITE_HAS_CODEC
105550     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
105551       sqlite3_activate_see(&zRight[4]);
105552     }
105553 #endif
105554 #ifdef SQLITE_ENABLE_CEROD
105555     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
105556       sqlite3_activate_cerod(&zRight[6]);
105557     }
105558 #endif
105559   }
105560   break;
105561 #endif
105562 
105563   } /* End of the PRAGMA switch */
105564 
105565 pragma_out:
105566   sqlite3DbFree(db, zLeft);
105567   sqlite3DbFree(db, zRight);
105568 }
105569 
105570 #endif /* SQLITE_OMIT_PRAGMA */
105571 
105572 /************** End of pragma.c **********************************************/
105573 /************** Begin file prepare.c *****************************************/
105574 /*
105575 ** 2005 May 25
105576 **
105577 ** The author disclaims copyright to this source code.  In place of
105578 ** a legal notice, here is a blessing:
105579 **
105580 **    May you do good and not evil.
105581 **    May you find forgiveness for yourself and forgive others.
105582 **    May you share freely, never taking more than you give.
105583 **
105584 *************************************************************************
105585 ** This file contains the implementation of the sqlite3_prepare()
105586 ** interface, and routines that contribute to loading the database schema
105587 ** from disk.
105588 */
105589 
105590 /*
105591 ** Fill the InitData structure with an error message that indicates
105592 ** that the database is corrupt.
105593 */
105594 static void corruptSchema(
105595   InitData *pData,     /* Initialization context */
105596   const char *zObj,    /* Object being parsed at the point of error */
105597   const char *zExtra   /* Error information */
105598 ){
105599   sqlite3 *db = pData->db;
105600   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
105601     if( zObj==0 ) zObj = "?";
105602     sqlite3SetString(pData->pzErrMsg, db,
105603       "malformed database schema (%s)", zObj);
105604     if( zExtra ){
105605       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
105606                                  "%s - %s", *pData->pzErrMsg, zExtra);
105607     }
105608   }
105609   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
105610 }
105611 
105612 /*
105613 ** This is the callback routine for the code that initializes the
105614 ** database.  See sqlite3Init() below for additional information.
105615 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
105616 **
105617 ** Each callback contains the following information:
105618 **
105619 **     argv[0] = name of thing being created
105620 **     argv[1] = root page number for table or index. 0 for trigger or view.
105621 **     argv[2] = SQL text for the CREATE statement.
105622 **
105623 */
105624 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
105625   InitData *pData = (InitData*)pInit;
105626   sqlite3 *db = pData->db;
105627   int iDb = pData->iDb;
105628 
105629   assert( argc==3 );
105630   UNUSED_PARAMETER2(NotUsed, argc);
105631   assert( sqlite3_mutex_held(db->mutex) );
105632   DbClearProperty(db, iDb, DB_Empty);
105633   if( db->mallocFailed ){
105634     corruptSchema(pData, argv[0], 0);
105635     return 1;
105636   }
105637 
105638   assert( iDb>=0 && iDb<db->nDb );
105639   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
105640   if( argv[1]==0 ){
105641     corruptSchema(pData, argv[0], 0);
105642   }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
105643     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
105644     ** But because db->init.busy is set to 1, no VDBE code is generated
105645     ** or executed.  All the parser does is build the internal data
105646     ** structures that describe the table, index, or view.
105647     */
105648     int rc;
105649     sqlite3_stmt *pStmt;
105650     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
105651 
105652     assert( db->init.busy );
105653     db->init.iDb = iDb;
105654     db->init.newTnum = sqlite3Atoi(argv[1]);
105655     db->init.orphanTrigger = 0;
105656     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
105657     rc = db->errCode;
105658     assert( (rc&0xFF)==(rcp&0xFF) );
105659     db->init.iDb = 0;
105660     if( SQLITE_OK!=rc ){
105661       if( db->init.orphanTrigger ){
105662         assert( iDb==1 );
105663       }else{
105664         pData->rc = rc;
105665         if( rc==SQLITE_NOMEM ){
105666           db->mallocFailed = 1;
105667         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
105668           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
105669         }
105670       }
105671     }
105672     sqlite3_finalize(pStmt);
105673   }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
105674     corruptSchema(pData, argv[0], 0);
105675   }else{
105676     /* If the SQL column is blank it means this is an index that
105677     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
105678     ** constraint for a CREATE TABLE.  The index should have already
105679     ** been created when we processed the CREATE TABLE.  All we have
105680     ** to do here is record the root page number for that index.
105681     */
105682     Index *pIndex;
105683     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
105684     if( pIndex==0 ){
105685       /* This can occur if there exists an index on a TEMP table which
105686       ** has the same name as another index on a permanent index.  Since
105687       ** the permanent table is hidden by the TEMP table, we can also
105688       ** safely ignore the index on the permanent table.
105689       */
105690       /* Do Nothing */;
105691     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
105692       corruptSchema(pData, argv[0], "invalid rootpage");
105693     }
105694   }
105695   return 0;
105696 }
105697 
105698 /*
105699 ** Attempt to read the database schema and initialize internal
105700 ** data structures for a single database file.  The index of the
105701 ** database file is given by iDb.  iDb==0 is used for the main
105702 ** database.  iDb==1 should never be used.  iDb>=2 is used for
105703 ** auxiliary databases.  Return one of the SQLITE_ error codes to
105704 ** indicate success or failure.
105705 */
105706 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
105707   int rc;
105708   int i;
105709 #ifndef SQLITE_OMIT_DEPRECATED
105710   int size;
105711 #endif
105712   Table *pTab;
105713   Db *pDb;
105714   char const *azArg[4];
105715   int meta[5];
105716   InitData initData;
105717   char const *zMasterSchema;
105718   char const *zMasterName;
105719   int openedTransaction = 0;
105720 
105721   /*
105722   ** The master database table has a structure like this
105723   */
105724   static const char master_schema[] =
105725      "CREATE TABLE sqlite_master(\n"
105726      "  type text,\n"
105727      "  name text,\n"
105728      "  tbl_name text,\n"
105729      "  rootpage integer,\n"
105730      "  sql text\n"
105731      ")"
105732   ;
105733 #ifndef SQLITE_OMIT_TEMPDB
105734   static const char temp_master_schema[] =
105735      "CREATE TEMP TABLE sqlite_temp_master(\n"
105736      "  type text,\n"
105737      "  name text,\n"
105738      "  tbl_name text,\n"
105739      "  rootpage integer,\n"
105740      "  sql text\n"
105741      ")"
105742   ;
105743 #else
105744   #define temp_master_schema 0
105745 #endif
105746 
105747   assert( iDb>=0 && iDb<db->nDb );
105748   assert( db->aDb[iDb].pSchema );
105749   assert( sqlite3_mutex_held(db->mutex) );
105750   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
105751 
105752   /* zMasterSchema and zInitScript are set to point at the master schema
105753   ** and initialisation script appropriate for the database being
105754   ** initialized. zMasterName is the name of the master table.
105755   */
105756   if( !OMIT_TEMPDB && iDb==1 ){
105757     zMasterSchema = temp_master_schema;
105758   }else{
105759     zMasterSchema = master_schema;
105760   }
105761   zMasterName = SCHEMA_TABLE(iDb);
105762 
105763   /* Construct the schema tables.  */
105764   azArg[0] = zMasterName;
105765   azArg[1] = "1";
105766   azArg[2] = zMasterSchema;
105767   azArg[3] = 0;
105768   initData.db = db;
105769   initData.iDb = iDb;
105770   initData.rc = SQLITE_OK;
105771   initData.pzErrMsg = pzErrMsg;
105772   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
105773   if( initData.rc ){
105774     rc = initData.rc;
105775     goto error_out;
105776   }
105777   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
105778   if( ALWAYS(pTab) ){
105779     pTab->tabFlags |= TF_Readonly;
105780   }
105781 
105782   /* Create a cursor to hold the database open
105783   */
105784   pDb = &db->aDb[iDb];
105785   if( pDb->pBt==0 ){
105786     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
105787       DbSetProperty(db, 1, DB_SchemaLoaded);
105788     }
105789     return SQLITE_OK;
105790   }
105791 
105792   /* If there is not already a read-only (or read-write) transaction opened
105793   ** on the b-tree database, open one now. If a transaction is opened, it
105794   ** will be closed before this function returns.  */
105795   sqlite3BtreeEnter(pDb->pBt);
105796   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
105797     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
105798     if( rc!=SQLITE_OK ){
105799       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
105800       goto initone_error_out;
105801     }
105802     openedTransaction = 1;
105803   }
105804 
105805   /* Get the database meta information.
105806   **
105807   ** Meta values are as follows:
105808   **    meta[0]   Schema cookie.  Changes with each schema change.
105809   **    meta[1]   File format of schema layer.
105810   **    meta[2]   Size of the page cache.
105811   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
105812   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
105813   **    meta[5]   User version
105814   **    meta[6]   Incremental vacuum mode
105815   **    meta[7]   unused
105816   **    meta[8]   unused
105817   **    meta[9]   unused
105818   **
105819   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
105820   ** the possible values of meta[4].
105821   */
105822   for(i=0; i<ArraySize(meta); i++){
105823     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
105824   }
105825   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
105826 
105827   /* If opening a non-empty database, check the text encoding. For the
105828   ** main database, set sqlite3.enc to the encoding of the main database.
105829   ** For an attached db, it is an error if the encoding is not the same
105830   ** as sqlite3.enc.
105831   */
105832   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
105833     if( iDb==0 ){
105834 #ifndef SQLITE_OMIT_UTF16
105835       u8 encoding;
105836       /* If opening the main database, set ENC(db). */
105837       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
105838       if( encoding==0 ) encoding = SQLITE_UTF8;
105839       ENC(db) = encoding;
105840 #else
105841       ENC(db) = SQLITE_UTF8;
105842 #endif
105843     }else{
105844       /* If opening an attached database, the encoding much match ENC(db) */
105845       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
105846         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
105847             " text encoding as main database");
105848         rc = SQLITE_ERROR;
105849         goto initone_error_out;
105850       }
105851     }
105852   }else{
105853     DbSetProperty(db, iDb, DB_Empty);
105854   }
105855   pDb->pSchema->enc = ENC(db);
105856 
105857   if( pDb->pSchema->cache_size==0 ){
105858 #ifndef SQLITE_OMIT_DEPRECATED
105859     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
105860     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
105861     pDb->pSchema->cache_size = size;
105862 #else
105863     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
105864 #endif
105865     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
105866   }
105867 
105868   /*
105869   ** file_format==1    Version 3.0.0.
105870   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
105871   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
105872   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
105873   */
105874   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
105875   if( pDb->pSchema->file_format==0 ){
105876     pDb->pSchema->file_format = 1;
105877   }
105878   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
105879     sqlite3SetString(pzErrMsg, db, "unsupported file format");
105880     rc = SQLITE_ERROR;
105881     goto initone_error_out;
105882   }
105883 
105884   /* Ticket #2804:  When we open a database in the newer file format,
105885   ** clear the legacy_file_format pragma flag so that a VACUUM will
105886   ** not downgrade the database and thus invalidate any descending
105887   ** indices that the user might have created.
105888   */
105889   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
105890     db->flags &= ~SQLITE_LegacyFileFmt;
105891   }
105892 
105893   /* Read the schema information out of the schema tables
105894   */
105895   assert( db->init.busy );
105896   {
105897     char *zSql;
105898     zSql = sqlite3MPrintf(db,
105899         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
105900         db->aDb[iDb].zName, zMasterName);
105901 #ifndef SQLITE_OMIT_AUTHORIZATION
105902     {
105903       sqlite3_xauth xAuth;
105904       xAuth = db->xAuth;
105905       db->xAuth = 0;
105906 #endif
105907       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
105908 #ifndef SQLITE_OMIT_AUTHORIZATION
105909       db->xAuth = xAuth;
105910     }
105911 #endif
105912     if( rc==SQLITE_OK ) rc = initData.rc;
105913     sqlite3DbFree(db, zSql);
105914 #ifndef SQLITE_OMIT_ANALYZE
105915     if( rc==SQLITE_OK ){
105916       sqlite3AnalysisLoad(db, iDb);
105917     }
105918 #endif
105919   }
105920   if( db->mallocFailed ){
105921     rc = SQLITE_NOMEM;
105922     sqlite3ResetAllSchemasOfConnection(db);
105923   }
105924   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
105925     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
105926     ** the schema loaded, even if errors occurred. In this situation the
105927     ** current sqlite3_prepare() operation will fail, but the following one
105928     ** will attempt to compile the supplied statement against whatever subset
105929     ** of the schema was loaded before the error occurred. The primary
105930     ** purpose of this is to allow access to the sqlite_master table
105931     ** even when its contents have been corrupted.
105932     */
105933     DbSetProperty(db, iDb, DB_SchemaLoaded);
105934     rc = SQLITE_OK;
105935   }
105936 
105937   /* Jump here for an error that occurs after successfully allocating
105938   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
105939   ** before that point, jump to error_out.
105940   */
105941 initone_error_out:
105942   if( openedTransaction ){
105943     sqlite3BtreeCommit(pDb->pBt);
105944   }
105945   sqlite3BtreeLeave(pDb->pBt);
105946 
105947 error_out:
105948   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
105949     db->mallocFailed = 1;
105950   }
105951   return rc;
105952 }
105953 
105954 /*
105955 ** Initialize all database files - the main database file, the file
105956 ** used to store temporary tables, and any additional database files
105957 ** created using ATTACH statements.  Return a success code.  If an
105958 ** error occurs, write an error message into *pzErrMsg.
105959 **
105960 ** After a database is initialized, the DB_SchemaLoaded bit is set
105961 ** bit is set in the flags field of the Db structure. If the database
105962 ** file was of zero-length, then the DB_Empty flag is also set.
105963 */
105964 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
105965   int i, rc;
105966   int commit_internal = !(db->flags&SQLITE_InternChanges);
105967 
105968   assert( sqlite3_mutex_held(db->mutex) );
105969   assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
105970   assert( db->init.busy==0 );
105971   rc = SQLITE_OK;
105972   db->init.busy = 1;
105973   ENC(db) = SCHEMA_ENC(db);
105974   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
105975     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
105976     rc = sqlite3InitOne(db, i, pzErrMsg);
105977     if( rc ){
105978       sqlite3ResetOneSchema(db, i);
105979     }
105980   }
105981 
105982   /* Once all the other databases have been initialized, load the schema
105983   ** for the TEMP database. This is loaded last, as the TEMP database
105984   ** schema may contain references to objects in other databases.
105985   */
105986 #ifndef SQLITE_OMIT_TEMPDB
105987   assert( db->nDb>1 );
105988   if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
105989     rc = sqlite3InitOne(db, 1, pzErrMsg);
105990     if( rc ){
105991       sqlite3ResetOneSchema(db, 1);
105992     }
105993   }
105994 #endif
105995 
105996   db->init.busy = 0;
105997   if( rc==SQLITE_OK && commit_internal ){
105998     sqlite3CommitInternalChanges(db);
105999   }
106000 
106001   return rc;
106002 }
106003 
106004 /*
106005 ** This routine is a no-op if the database schema is already initialized.
106006 ** Otherwise, the schema is loaded. An error code is returned.
106007 */
106008 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
106009   int rc = SQLITE_OK;
106010   sqlite3 *db = pParse->db;
106011   assert( sqlite3_mutex_held(db->mutex) );
106012   if( !db->init.busy ){
106013     rc = sqlite3Init(db, &pParse->zErrMsg);
106014   }
106015   if( rc!=SQLITE_OK ){
106016     pParse->rc = rc;
106017     pParse->nErr++;
106018   }
106019   return rc;
106020 }
106021 
106022 
106023 /*
106024 ** Check schema cookies in all databases.  If any cookie is out
106025 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
106026 ** make no changes to pParse->rc.
106027 */
106028 static void schemaIsValid(Parse *pParse){
106029   sqlite3 *db = pParse->db;
106030   int iDb;
106031   int rc;
106032   int cookie;
106033 
106034   assert( pParse->checkSchema );
106035   assert( sqlite3_mutex_held(db->mutex) );
106036   for(iDb=0; iDb<db->nDb; iDb++){
106037     int openedTransaction = 0;         /* True if a transaction is opened */
106038     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
106039     if( pBt==0 ) continue;
106040 
106041     /* If there is not already a read-only (or read-write) transaction opened
106042     ** on the b-tree database, open one now. If a transaction is opened, it
106043     ** will be closed immediately after reading the meta-value. */
106044     if( !sqlite3BtreeIsInReadTrans(pBt) ){
106045       rc = sqlite3BtreeBeginTrans(pBt, 0);
106046       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
106047         db->mallocFailed = 1;
106048       }
106049       if( rc!=SQLITE_OK ) return;
106050       openedTransaction = 1;
106051     }
106052 
106053     /* Read the schema cookie from the database. If it does not match the
106054     ** value stored as part of the in-memory schema representation,
106055     ** set Parse.rc to SQLITE_SCHEMA. */
106056     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
106057     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
106058     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
106059       sqlite3ResetOneSchema(db, iDb);
106060       pParse->rc = SQLITE_SCHEMA;
106061     }
106062 
106063     /* Close the transaction, if one was opened. */
106064     if( openedTransaction ){
106065       sqlite3BtreeCommit(pBt);
106066     }
106067   }
106068 }
106069 
106070 /*
106071 ** Convert a schema pointer into the iDb index that indicates
106072 ** which database file in db->aDb[] the schema refers to.
106073 **
106074 ** If the same database is attached more than once, the first
106075 ** attached database is returned.
106076 */
106077 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
106078   int i = -1000000;
106079 
106080   /* If pSchema is NULL, then return -1000000. This happens when code in
106081   ** expr.c is trying to resolve a reference to a transient table (i.e. one
106082   ** created by a sub-select). In this case the return value of this
106083   ** function should never be used.
106084   **
106085   ** We return -1000000 instead of the more usual -1 simply because using
106086   ** -1000000 as the incorrect index into db->aDb[] is much
106087   ** more likely to cause a segfault than -1 (of course there are assert()
106088   ** statements too, but it never hurts to play the odds).
106089   */
106090   assert( sqlite3_mutex_held(db->mutex) );
106091   if( pSchema ){
106092     for(i=0; ALWAYS(i<db->nDb); i++){
106093       if( db->aDb[i].pSchema==pSchema ){
106094         break;
106095       }
106096     }
106097     assert( i>=0 && i<db->nDb );
106098   }
106099   return i;
106100 }
106101 
106102 /*
106103 ** Free all memory allocations in the pParse object
106104 */
106105 SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
106106   if( pParse ){
106107     sqlite3 *db = pParse->db;
106108     sqlite3DbFree(db, pParse->aLabel);
106109     sqlite3ExprListDelete(db, pParse->pConstExpr);
106110   }
106111 }
106112 
106113 /*
106114 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
106115 */
106116 static int sqlite3Prepare(
106117   sqlite3 *db,              /* Database handle. */
106118   const char *zSql,         /* UTF-8 encoded SQL statement. */
106119   int nBytes,               /* Length of zSql in bytes. */
106120   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
106121   Vdbe *pReprepare,         /* VM being reprepared */
106122   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
106123   const char **pzTail       /* OUT: End of parsed string */
106124 ){
106125   Parse *pParse;            /* Parsing context */
106126   char *zErrMsg = 0;        /* Error message */
106127   int rc = SQLITE_OK;       /* Result code */
106128   int i;                    /* Loop counter */
106129 
106130   /* Allocate the parsing context */
106131   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
106132   if( pParse==0 ){
106133     rc = SQLITE_NOMEM;
106134     goto end_prepare;
106135   }
106136   pParse->pReprepare = pReprepare;
106137   assert( ppStmt && *ppStmt==0 );
106138   assert( !db->mallocFailed );
106139   assert( sqlite3_mutex_held(db->mutex) );
106140 
106141   /* Check to verify that it is possible to get a read lock on all
106142   ** database schemas.  The inability to get a read lock indicates that
106143   ** some other database connection is holding a write-lock, which in
106144   ** turn means that the other connection has made uncommitted changes
106145   ** to the schema.
106146   **
106147   ** Were we to proceed and prepare the statement against the uncommitted
106148   ** schema changes and if those schema changes are subsequently rolled
106149   ** back and different changes are made in their place, then when this
106150   ** prepared statement goes to run the schema cookie would fail to detect
106151   ** the schema change.  Disaster would follow.
106152   **
106153   ** This thread is currently holding mutexes on all Btrees (because
106154   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
106155   ** is not possible for another thread to start a new schema change
106156   ** while this routine is running.  Hence, we do not need to hold
106157   ** locks on the schema, we just need to make sure nobody else is
106158   ** holding them.
106159   **
106160   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
106161   ** but it does *not* override schema lock detection, so this all still
106162   ** works even if READ_UNCOMMITTED is set.
106163   */
106164   for(i=0; i<db->nDb; i++) {
106165     Btree *pBt = db->aDb[i].pBt;
106166     if( pBt ){
106167       assert( sqlite3BtreeHoldsMutex(pBt) );
106168       rc = sqlite3BtreeSchemaLocked(pBt);
106169       if( rc ){
106170         const char *zDb = db->aDb[i].zName;
106171         sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
106172         testcase( db->flags & SQLITE_ReadUncommitted );
106173         goto end_prepare;
106174       }
106175     }
106176   }
106177 
106178   sqlite3VtabUnlockList(db);
106179 
106180   pParse->db = db;
106181   pParse->nQueryLoop = 0;  /* Logarithmic, so 0 really means 1 */
106182   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
106183     char *zSqlCopy;
106184     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
106185     testcase( nBytes==mxLen );
106186     testcase( nBytes==mxLen+1 );
106187     if( nBytes>mxLen ){
106188       sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
106189       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
106190       goto end_prepare;
106191     }
106192     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
106193     if( zSqlCopy ){
106194       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
106195       sqlite3DbFree(db, zSqlCopy);
106196       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
106197     }else{
106198       pParse->zTail = &zSql[nBytes];
106199     }
106200   }else{
106201     sqlite3RunParser(pParse, zSql, &zErrMsg);
106202   }
106203   assert( 0==pParse->nQueryLoop );
106204 
106205   if( db->mallocFailed ){
106206     pParse->rc = SQLITE_NOMEM;
106207   }
106208   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
106209   if( pParse->checkSchema ){
106210     schemaIsValid(pParse);
106211   }
106212   if( db->mallocFailed ){
106213     pParse->rc = SQLITE_NOMEM;
106214   }
106215   if( pzTail ){
106216     *pzTail = pParse->zTail;
106217   }
106218   rc = pParse->rc;
106219 
106220 #ifndef SQLITE_OMIT_EXPLAIN
106221   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
106222     static const char * const azColName[] = {
106223        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
106224        "selectid", "order", "from", "detail"
106225     };
106226     int iFirst, mx;
106227     if( pParse->explain==2 ){
106228       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
106229       iFirst = 8;
106230       mx = 12;
106231     }else{
106232       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
106233       iFirst = 0;
106234       mx = 8;
106235     }
106236     for(i=iFirst; i<mx; i++){
106237       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
106238                             azColName[i], SQLITE_STATIC);
106239     }
106240   }
106241 #endif
106242 
106243   if( db->init.busy==0 ){
106244     Vdbe *pVdbe = pParse->pVdbe;
106245     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
106246   }
106247   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
106248     sqlite3VdbeFinalize(pParse->pVdbe);
106249     assert(!(*ppStmt));
106250   }else{
106251     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
106252   }
106253 
106254   if( zErrMsg ){
106255     sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
106256     sqlite3DbFree(db, zErrMsg);
106257   }else{
106258     sqlite3Error(db, rc);
106259   }
106260 
106261   /* Delete any TriggerPrg structures allocated while parsing this statement. */
106262   while( pParse->pTriggerPrg ){
106263     TriggerPrg *pT = pParse->pTriggerPrg;
106264     pParse->pTriggerPrg = pT->pNext;
106265     sqlite3DbFree(db, pT);
106266   }
106267 
106268 end_prepare:
106269 
106270   sqlite3ParserReset(pParse);
106271   sqlite3StackFree(db, pParse);
106272   rc = sqlite3ApiExit(db, rc);
106273   assert( (rc&db->errMask)==rc );
106274   return rc;
106275 }
106276 static int sqlite3LockAndPrepare(
106277   sqlite3 *db,              /* Database handle. */
106278   const char *zSql,         /* UTF-8 encoded SQL statement. */
106279   int nBytes,               /* Length of zSql in bytes. */
106280   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
106281   Vdbe *pOld,               /* VM being reprepared */
106282   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
106283   const char **pzTail       /* OUT: End of parsed string */
106284 ){
106285   int rc;
106286 
106287 #ifdef SQLITE_ENABLE_API_ARMOR
106288   if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
106289 #endif
106290   *ppStmt = 0;
106291   if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
106292     return SQLITE_MISUSE_BKPT;
106293   }
106294   sqlite3_mutex_enter(db->mutex);
106295   sqlite3BtreeEnterAll(db);
106296   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
106297   if( rc==SQLITE_SCHEMA ){
106298     sqlite3_finalize(*ppStmt);
106299     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
106300   }
106301   sqlite3BtreeLeaveAll(db);
106302   sqlite3_mutex_leave(db->mutex);
106303   assert( rc==SQLITE_OK || *ppStmt==0 );
106304   return rc;
106305 }
106306 
106307 /*
106308 ** Rerun the compilation of a statement after a schema change.
106309 **
106310 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
106311 ** if the statement cannot be recompiled because another connection has
106312 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
106313 ** occurs, return SQLITE_SCHEMA.
106314 */
106315 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
106316   int rc;
106317   sqlite3_stmt *pNew;
106318   const char *zSql;
106319   sqlite3 *db;
106320 
106321   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
106322   zSql = sqlite3_sql((sqlite3_stmt *)p);
106323   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
106324   db = sqlite3VdbeDb(p);
106325   assert( sqlite3_mutex_held(db->mutex) );
106326   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
106327   if( rc ){
106328     if( rc==SQLITE_NOMEM ){
106329       db->mallocFailed = 1;
106330     }
106331     assert( pNew==0 );
106332     return rc;
106333   }else{
106334     assert( pNew!=0 );
106335   }
106336   sqlite3VdbeSwap((Vdbe*)pNew, p);
106337   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
106338   sqlite3VdbeResetStepResult((Vdbe*)pNew);
106339   sqlite3VdbeFinalize((Vdbe*)pNew);
106340   return SQLITE_OK;
106341 }
106342 
106343 
106344 /*
106345 ** Two versions of the official API.  Legacy and new use.  In the legacy
106346 ** version, the original SQL text is not saved in the prepared statement
106347 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
106348 ** sqlite3_step().  In the new version, the original SQL text is retained
106349 ** and the statement is automatically recompiled if an schema change
106350 ** occurs.
106351 */
106352 SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
106353   sqlite3 *db,              /* Database handle. */
106354   const char *zSql,         /* UTF-8 encoded SQL statement. */
106355   int nBytes,               /* Length of zSql in bytes. */
106356   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
106357   const char **pzTail       /* OUT: End of parsed string */
106358 ){
106359   int rc;
106360   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
106361   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
106362   return rc;
106363 }
106364 SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
106365   sqlite3 *db,              /* Database handle. */
106366   const char *zSql,         /* UTF-8 encoded SQL statement. */
106367   int nBytes,               /* Length of zSql in bytes. */
106368   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
106369   const char **pzTail       /* OUT: End of parsed string */
106370 ){
106371   int rc;
106372   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
106373   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
106374   return rc;
106375 }
106376 
106377 
106378 #ifndef SQLITE_OMIT_UTF16
106379 /*
106380 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
106381 */
106382 static int sqlite3Prepare16(
106383   sqlite3 *db,              /* Database handle. */
106384   const void *zSql,         /* UTF-16 encoded SQL statement. */
106385   int nBytes,               /* Length of zSql in bytes. */
106386   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
106387   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
106388   const void **pzTail       /* OUT: End of parsed string */
106389 ){
106390   /* This function currently works by first transforming the UTF-16
106391   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
106392   ** tricky bit is figuring out the pointer to return in *pzTail.
106393   */
106394   char *zSql8;
106395   const char *zTail8 = 0;
106396   int rc = SQLITE_OK;
106397 
106398 #ifdef SQLITE_ENABLE_API_ARMOR
106399   if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
106400 #endif
106401   *ppStmt = 0;
106402   if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
106403     return SQLITE_MISUSE_BKPT;
106404   }
106405   if( nBytes>=0 ){
106406     int sz;
106407     const char *z = (const char*)zSql;
106408     for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
106409     nBytes = sz;
106410   }
106411   sqlite3_mutex_enter(db->mutex);
106412   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
106413   if( zSql8 ){
106414     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
106415   }
106416 
106417   if( zTail8 && pzTail ){
106418     /* If sqlite3_prepare returns a tail pointer, we calculate the
106419     ** equivalent pointer into the UTF-16 string by counting the unicode
106420     ** characters between zSql8 and zTail8, and then returning a pointer
106421     ** the same number of characters into the UTF-16 string.
106422     */
106423     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
106424     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
106425   }
106426   sqlite3DbFree(db, zSql8);
106427   rc = sqlite3ApiExit(db, rc);
106428   sqlite3_mutex_leave(db->mutex);
106429   return rc;
106430 }
106431 
106432 /*
106433 ** Two versions of the official API.  Legacy and new use.  In the legacy
106434 ** version, the original SQL text is not saved in the prepared statement
106435 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
106436 ** sqlite3_step().  In the new version, the original SQL text is retained
106437 ** and the statement is automatically recompiled if an schema change
106438 ** occurs.
106439 */
106440 SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
106441   sqlite3 *db,              /* Database handle. */
106442   const void *zSql,         /* UTF-16 encoded SQL statement. */
106443   int nBytes,               /* Length of zSql in bytes. */
106444   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
106445   const void **pzTail       /* OUT: End of parsed string */
106446 ){
106447   int rc;
106448   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
106449   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
106450   return rc;
106451 }
106452 SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
106453   sqlite3 *db,              /* Database handle. */
106454   const void *zSql,         /* UTF-16 encoded SQL statement. */
106455   int nBytes,               /* Length of zSql in bytes. */
106456   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
106457   const void **pzTail       /* OUT: End of parsed string */
106458 ){
106459   int rc;
106460   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
106461   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
106462   return rc;
106463 }
106464 
106465 #endif /* SQLITE_OMIT_UTF16 */
106466 
106467 /************** End of prepare.c *********************************************/
106468 /************** Begin file select.c ******************************************/
106469 /*
106470 ** 2001 September 15
106471 **
106472 ** The author disclaims copyright to this source code.  In place of
106473 ** a legal notice, here is a blessing:
106474 **
106475 **    May you do good and not evil.
106476 **    May you find forgiveness for yourself and forgive others.
106477 **    May you share freely, never taking more than you give.
106478 **
106479 *************************************************************************
106480 ** This file contains C code routines that are called by the parser
106481 ** to handle SELECT statements in SQLite.
106482 */
106483 
106484 /*
106485 ** Trace output macros
106486 */
106487 #if SELECTTRACE_ENABLED
106488 /***/ int sqlite3SelectTrace = 0;
106489 # define SELECTTRACE(K,P,S,X)  \
106490   if(sqlite3SelectTrace&(K))   \
106491     sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",(S)->zSelName,(S)),\
106492     sqlite3DebugPrintf X
106493 #else
106494 # define SELECTTRACE(K,P,S,X)
106495 #endif
106496 
106497 
106498 /*
106499 ** An instance of the following object is used to record information about
106500 ** how to process the DISTINCT keyword, to simplify passing that information
106501 ** into the selectInnerLoop() routine.
106502 */
106503 typedef struct DistinctCtx DistinctCtx;
106504 struct DistinctCtx {
106505   u8 isTnct;      /* True if the DISTINCT keyword is present */
106506   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
106507   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
106508   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
106509 };
106510 
106511 /*
106512 ** An instance of the following object is used to record information about
106513 ** the ORDER BY (or GROUP BY) clause of query is being coded.
106514 */
106515 typedef struct SortCtx SortCtx;
106516 struct SortCtx {
106517   ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
106518   int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
106519   int iECursor;         /* Cursor number for the sorter */
106520   int regReturn;        /* Register holding block-output return address */
106521   int labelBkOut;       /* Start label for the block-output subroutine */
106522   int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
106523   u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
106524 };
106525 #define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
106526 
106527 /*
106528 ** Delete all the content of a Select structure.  Deallocate the structure
106529 ** itself only if bFree is true.
106530 */
106531 static void clearSelect(sqlite3 *db, Select *p, int bFree){
106532   while( p ){
106533     Select *pPrior = p->pPrior;
106534     sqlite3ExprListDelete(db, p->pEList);
106535     sqlite3SrcListDelete(db, p->pSrc);
106536     sqlite3ExprDelete(db, p->pWhere);
106537     sqlite3ExprListDelete(db, p->pGroupBy);
106538     sqlite3ExprDelete(db, p->pHaving);
106539     sqlite3ExprListDelete(db, p->pOrderBy);
106540     sqlite3ExprDelete(db, p->pLimit);
106541     sqlite3ExprDelete(db, p->pOffset);
106542     sqlite3WithDelete(db, p->pWith);
106543     if( bFree ) sqlite3DbFree(db, p);
106544     p = pPrior;
106545     bFree = 1;
106546   }
106547 }
106548 
106549 /*
106550 ** Initialize a SelectDest structure.
106551 */
106552 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
106553   pDest->eDest = (u8)eDest;
106554   pDest->iSDParm = iParm;
106555   pDest->affSdst = 0;
106556   pDest->iSdst = 0;
106557   pDest->nSdst = 0;
106558 }
106559 
106560 
106561 /*
106562 ** Allocate a new Select structure and return a pointer to that
106563 ** structure.
106564 */
106565 SQLITE_PRIVATE Select *sqlite3SelectNew(
106566   Parse *pParse,        /* Parsing context */
106567   ExprList *pEList,     /* which columns to include in the result */
106568   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
106569   Expr *pWhere,         /* the WHERE clause */
106570   ExprList *pGroupBy,   /* the GROUP BY clause */
106571   Expr *pHaving,        /* the HAVING clause */
106572   ExprList *pOrderBy,   /* the ORDER BY clause */
106573   u16 selFlags,         /* Flag parameters, such as SF_Distinct */
106574   Expr *pLimit,         /* LIMIT value.  NULL means not used */
106575   Expr *pOffset         /* OFFSET value.  NULL means no offset */
106576 ){
106577   Select *pNew;
106578   Select standin;
106579   sqlite3 *db = pParse->db;
106580   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
106581   if( pNew==0 ){
106582     assert( db->mallocFailed );
106583     pNew = &standin;
106584     memset(pNew, 0, sizeof(*pNew));
106585   }
106586   if( pEList==0 ){
106587     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
106588   }
106589   pNew->pEList = pEList;
106590   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
106591   pNew->pSrc = pSrc;
106592   pNew->pWhere = pWhere;
106593   pNew->pGroupBy = pGroupBy;
106594   pNew->pHaving = pHaving;
106595   pNew->pOrderBy = pOrderBy;
106596   pNew->selFlags = selFlags;
106597   pNew->op = TK_SELECT;
106598   pNew->pLimit = pLimit;
106599   pNew->pOffset = pOffset;
106600   assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
106601   pNew->addrOpenEphm[0] = -1;
106602   pNew->addrOpenEphm[1] = -1;
106603   if( db->mallocFailed ) {
106604     clearSelect(db, pNew, pNew!=&standin);
106605     pNew = 0;
106606   }else{
106607     assert( pNew->pSrc!=0 || pParse->nErr>0 );
106608   }
106609   assert( pNew!=&standin );
106610   return pNew;
106611 }
106612 
106613 #if SELECTTRACE_ENABLED
106614 /*
106615 ** Set the name of a Select object
106616 */
106617 SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
106618   if( p && zName ){
106619     sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
106620   }
106621 }
106622 #endif
106623 
106624 
106625 /*
106626 ** Delete the given Select structure and all of its substructures.
106627 */
106628 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
106629   clearSelect(db, p, 1);
106630 }
106631 
106632 /*
106633 ** Return a pointer to the right-most SELECT statement in a compound.
106634 */
106635 static Select *findRightmost(Select *p){
106636   while( p->pNext ) p = p->pNext;
106637   return p;
106638 }
106639 
106640 /*
106641 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
106642 ** type of join.  Return an integer constant that expresses that type
106643 ** in terms of the following bit values:
106644 **
106645 **     JT_INNER
106646 **     JT_CROSS
106647 **     JT_OUTER
106648 **     JT_NATURAL
106649 **     JT_LEFT
106650 **     JT_RIGHT
106651 **
106652 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
106653 **
106654 ** If an illegal or unsupported join type is seen, then still return
106655 ** a join type, but put an error in the pParse structure.
106656 */
106657 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
106658   int jointype = 0;
106659   Token *apAll[3];
106660   Token *p;
106661                              /*   0123456789 123456789 123456789 123 */
106662   static const char zKeyText[] = "naturaleftouterightfullinnercross";
106663   static const struct {
106664     u8 i;        /* Beginning of keyword text in zKeyText[] */
106665     u8 nChar;    /* Length of the keyword in characters */
106666     u8 code;     /* Join type mask */
106667   } aKeyword[] = {
106668     /* natural */ { 0,  7, JT_NATURAL                },
106669     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
106670     /* outer   */ { 10, 5, JT_OUTER                  },
106671     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
106672     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
106673     /* inner   */ { 23, 5, JT_INNER                  },
106674     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
106675   };
106676   int i, j;
106677   apAll[0] = pA;
106678   apAll[1] = pB;
106679   apAll[2] = pC;
106680   for(i=0; i<3 && apAll[i]; i++){
106681     p = apAll[i];
106682     for(j=0; j<ArraySize(aKeyword); j++){
106683       if( p->n==aKeyword[j].nChar
106684           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
106685         jointype |= aKeyword[j].code;
106686         break;
106687       }
106688     }
106689     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
106690     if( j>=ArraySize(aKeyword) ){
106691       jointype |= JT_ERROR;
106692       break;
106693     }
106694   }
106695   if(
106696      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
106697      (jointype & JT_ERROR)!=0
106698   ){
106699     const char *zSp = " ";
106700     assert( pB!=0 );
106701     if( pC==0 ){ zSp++; }
106702     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
106703        "%T %T%s%T", pA, pB, zSp, pC);
106704     jointype = JT_INNER;
106705   }else if( (jointype & JT_OUTER)!=0
106706          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
106707     sqlite3ErrorMsg(pParse,
106708       "RIGHT and FULL OUTER JOINs are not currently supported");
106709     jointype = JT_INNER;
106710   }
106711   return jointype;
106712 }
106713 
106714 /*
106715 ** Return the index of a column in a table.  Return -1 if the column
106716 ** is not contained in the table.
106717 */
106718 static int columnIndex(Table *pTab, const char *zCol){
106719   int i;
106720   for(i=0; i<pTab->nCol; i++){
106721     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
106722   }
106723   return -1;
106724 }
106725 
106726 /*
106727 ** Search the first N tables in pSrc, from left to right, looking for a
106728 ** table that has a column named zCol.
106729 **
106730 ** When found, set *piTab and *piCol to the table index and column index
106731 ** of the matching column and return TRUE.
106732 **
106733 ** If not found, return FALSE.
106734 */
106735 static int tableAndColumnIndex(
106736   SrcList *pSrc,       /* Array of tables to search */
106737   int N,               /* Number of tables in pSrc->a[] to search */
106738   const char *zCol,    /* Name of the column we are looking for */
106739   int *piTab,          /* Write index of pSrc->a[] here */
106740   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
106741 ){
106742   int i;               /* For looping over tables in pSrc */
106743   int iCol;            /* Index of column matching zCol */
106744 
106745   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
106746   for(i=0; i<N; i++){
106747     iCol = columnIndex(pSrc->a[i].pTab, zCol);
106748     if( iCol>=0 ){
106749       if( piTab ){
106750         *piTab = i;
106751         *piCol = iCol;
106752       }
106753       return 1;
106754     }
106755   }
106756   return 0;
106757 }
106758 
106759 /*
106760 ** This function is used to add terms implied by JOIN syntax to the
106761 ** WHERE clause expression of a SELECT statement. The new term, which
106762 ** is ANDed with the existing WHERE clause, is of the form:
106763 **
106764 **    (tab1.col1 = tab2.col2)
106765 **
106766 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
106767 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
106768 ** column iColRight of tab2.
106769 */
106770 static void addWhereTerm(
106771   Parse *pParse,                  /* Parsing context */
106772   SrcList *pSrc,                  /* List of tables in FROM clause */
106773   int iLeft,                      /* Index of first table to join in pSrc */
106774   int iColLeft,                   /* Index of column in first table */
106775   int iRight,                     /* Index of second table in pSrc */
106776   int iColRight,                  /* Index of column in second table */
106777   int isOuterJoin,                /* True if this is an OUTER join */
106778   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
106779 ){
106780   sqlite3 *db = pParse->db;
106781   Expr *pE1;
106782   Expr *pE2;
106783   Expr *pEq;
106784 
106785   assert( iLeft<iRight );
106786   assert( pSrc->nSrc>iRight );
106787   assert( pSrc->a[iLeft].pTab );
106788   assert( pSrc->a[iRight].pTab );
106789 
106790   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
106791   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
106792 
106793   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
106794   if( pEq && isOuterJoin ){
106795     ExprSetProperty(pEq, EP_FromJoin);
106796     assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
106797     ExprSetVVAProperty(pEq, EP_NoReduce);
106798     pEq->iRightJoinTable = (i16)pE2->iTable;
106799   }
106800   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
106801 }
106802 
106803 /*
106804 ** Set the EP_FromJoin property on all terms of the given expression.
106805 ** And set the Expr.iRightJoinTable to iTable for every term in the
106806 ** expression.
106807 **
106808 ** The EP_FromJoin property is used on terms of an expression to tell
106809 ** the LEFT OUTER JOIN processing logic that this term is part of the
106810 ** join restriction specified in the ON or USING clause and not a part
106811 ** of the more general WHERE clause.  These terms are moved over to the
106812 ** WHERE clause during join processing but we need to remember that they
106813 ** originated in the ON or USING clause.
106814 **
106815 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
106816 ** expression depends on table iRightJoinTable even if that table is not
106817 ** explicitly mentioned in the expression.  That information is needed
106818 ** for cases like this:
106819 **
106820 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
106821 **
106822 ** The where clause needs to defer the handling of the t1.x=5
106823 ** term until after the t2 loop of the join.  In that way, a
106824 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
106825 ** defer the handling of t1.x=5, it will be processed immediately
106826 ** after the t1 loop and rows with t1.x!=5 will never appear in
106827 ** the output, which is incorrect.
106828 */
106829 static void setJoinExpr(Expr *p, int iTable){
106830   while( p ){
106831     ExprSetProperty(p, EP_FromJoin);
106832     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
106833     ExprSetVVAProperty(p, EP_NoReduce);
106834     p->iRightJoinTable = (i16)iTable;
106835     setJoinExpr(p->pLeft, iTable);
106836     p = p->pRight;
106837   }
106838 }
106839 
106840 /*
106841 ** This routine processes the join information for a SELECT statement.
106842 ** ON and USING clauses are converted into extra terms of the WHERE clause.
106843 ** NATURAL joins also create extra WHERE clause terms.
106844 **
106845 ** The terms of a FROM clause are contained in the Select.pSrc structure.
106846 ** The left most table is the first entry in Select.pSrc.  The right-most
106847 ** table is the last entry.  The join operator is held in the entry to
106848 ** the left.  Thus entry 0 contains the join operator for the join between
106849 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
106850 ** also attached to the left entry.
106851 **
106852 ** This routine returns the number of errors encountered.
106853 */
106854 static int sqliteProcessJoin(Parse *pParse, Select *p){
106855   SrcList *pSrc;                  /* All tables in the FROM clause */
106856   int i, j;                       /* Loop counters */
106857   struct SrcList_item *pLeft;     /* Left table being joined */
106858   struct SrcList_item *pRight;    /* Right table being joined */
106859 
106860   pSrc = p->pSrc;
106861   pLeft = &pSrc->a[0];
106862   pRight = &pLeft[1];
106863   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
106864     Table *pLeftTab = pLeft->pTab;
106865     Table *pRightTab = pRight->pTab;
106866     int isOuter;
106867 
106868     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
106869     isOuter = (pRight->jointype & JT_OUTER)!=0;
106870 
106871     /* When the NATURAL keyword is present, add WHERE clause terms for
106872     ** every column that the two tables have in common.
106873     */
106874     if( pRight->jointype & JT_NATURAL ){
106875       if( pRight->pOn || pRight->pUsing ){
106876         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
106877            "an ON or USING clause", 0);
106878         return 1;
106879       }
106880       for(j=0; j<pRightTab->nCol; j++){
106881         char *zName;   /* Name of column in the right table */
106882         int iLeft;     /* Matching left table */
106883         int iLeftCol;  /* Matching column in the left table */
106884 
106885         zName = pRightTab->aCol[j].zName;
106886         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
106887           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
106888                        isOuter, &p->pWhere);
106889         }
106890       }
106891     }
106892 
106893     /* Disallow both ON and USING clauses in the same join
106894     */
106895     if( pRight->pOn && pRight->pUsing ){
106896       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
106897         "clauses in the same join");
106898       return 1;
106899     }
106900 
106901     /* Add the ON clause to the end of the WHERE clause, connected by
106902     ** an AND operator.
106903     */
106904     if( pRight->pOn ){
106905       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
106906       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
106907       pRight->pOn = 0;
106908     }
106909 
106910     /* Create extra terms on the WHERE clause for each column named
106911     ** in the USING clause.  Example: If the two tables to be joined are
106912     ** A and B and the USING clause names X, Y, and Z, then add this
106913     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
106914     ** Report an error if any column mentioned in the USING clause is
106915     ** not contained in both tables to be joined.
106916     */
106917     if( pRight->pUsing ){
106918       IdList *pList = pRight->pUsing;
106919       for(j=0; j<pList->nId; j++){
106920         char *zName;     /* Name of the term in the USING clause */
106921         int iLeft;       /* Table on the left with matching column name */
106922         int iLeftCol;    /* Column number of matching column on the left */
106923         int iRightCol;   /* Column number of matching column on the right */
106924 
106925         zName = pList->a[j].zName;
106926         iRightCol = columnIndex(pRightTab, zName);
106927         if( iRightCol<0
106928          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
106929         ){
106930           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
106931             "not present in both tables", zName);
106932           return 1;
106933         }
106934         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
106935                      isOuter, &p->pWhere);
106936       }
106937     }
106938   }
106939   return 0;
106940 }
106941 
106942 /* Forward reference */
106943 static KeyInfo *keyInfoFromExprList(
106944   Parse *pParse,       /* Parsing context */
106945   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
106946   int iStart,          /* Begin with this column of pList */
106947   int nExtra           /* Add this many extra columns to the end */
106948 );
106949 
106950 /*
106951 ** Generate code that will push the record in registers regData
106952 ** through regData+nData-1 onto the sorter.
106953 */
106954 static void pushOntoSorter(
106955   Parse *pParse,         /* Parser context */
106956   SortCtx *pSort,        /* Information about the ORDER BY clause */
106957   Select *pSelect,       /* The whole SELECT statement */
106958   int regData,           /* First register holding data to be sorted */
106959   int nData,             /* Number of elements in the data array */
106960   int nPrefixReg         /* No. of reg prior to regData available for use */
106961 ){
106962   Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
106963   int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
106964   int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
106965   int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
106966   int regBase;                                     /* Regs for sorter record */
106967   int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
106968   int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
106969   int op;                            /* Opcode to add sorter record to sorter */
106970 
106971   assert( bSeq==0 || bSeq==1 );
106972   if( nPrefixReg ){
106973     assert( nPrefixReg==nExpr+bSeq );
106974     regBase = regData - nExpr - bSeq;
106975   }else{
106976     regBase = pParse->nMem + 1;
106977     pParse->nMem += nBase;
106978   }
106979   sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, SQLITE_ECEL_DUP);
106980   if( bSeq ){
106981     sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
106982   }
106983   if( nPrefixReg==0 ){
106984     sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
106985   }
106986 
106987   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
106988   if( nOBSat>0 ){
106989     int regPrevKey;   /* The first nOBSat columns of the previous row */
106990     int addrFirst;    /* Address of the OP_IfNot opcode */
106991     int addrJmp;      /* Address of the OP_Jump opcode */
106992     VdbeOp *pOp;      /* Opcode that opens the sorter */
106993     int nKey;         /* Number of sorting key columns, including OP_Sequence */
106994     KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
106995 
106996     regPrevKey = pParse->nMem+1;
106997     pParse->nMem += pSort->nOBSat;
106998     nKey = nExpr - pSort->nOBSat + bSeq;
106999     if( bSeq ){
107000       addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
107001     }else{
107002       addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
107003     }
107004     VdbeCoverage(v);
107005     sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
107006     pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
107007     if( pParse->db->mallocFailed ) return;
107008     pOp->p2 = nKey + nData;
107009     pKI = pOp->p4.pKeyInfo;
107010     memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
107011     sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
107012     testcase( pKI->nXField>2 );
107013     pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
107014                                            pKI->nXField-1);
107015     addrJmp = sqlite3VdbeCurrentAddr(v);
107016     sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
107017     pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
107018     pSort->regReturn = ++pParse->nMem;
107019     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
107020     sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
107021     sqlite3VdbeJumpHere(v, addrFirst);
107022     sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
107023     sqlite3VdbeJumpHere(v, addrJmp);
107024   }
107025   if( pSort->sortFlags & SORTFLAG_UseSorter ){
107026     op = OP_SorterInsert;
107027   }else{
107028     op = OP_IdxInsert;
107029   }
107030   sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
107031   if( pSelect->iLimit ){
107032     int addr;
107033     int iLimit;
107034     if( pSelect->iOffset ){
107035       iLimit = pSelect->iOffset+1;
107036     }else{
107037       iLimit = pSelect->iLimit;
107038     }
107039     addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, -1); VdbeCoverage(v);
107040     sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
107041     sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
107042     sqlite3VdbeJumpHere(v, addr);
107043   }
107044 }
107045 
107046 /*
107047 ** Add code to implement the OFFSET
107048 */
107049 static void codeOffset(
107050   Vdbe *v,          /* Generate code into this VM */
107051   int iOffset,      /* Register holding the offset counter */
107052   int iContinue     /* Jump here to skip the current record */
107053 ){
107054   if( iOffset>0 ){
107055     int addr;
107056     addr = sqlite3VdbeAddOp3(v, OP_IfNeg, iOffset, 0, -1); VdbeCoverage(v);
107057     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
107058     VdbeComment((v, "skip OFFSET records"));
107059     sqlite3VdbeJumpHere(v, addr);
107060   }
107061 }
107062 
107063 /*
107064 ** Add code that will check to make sure the N registers starting at iMem
107065 ** form a distinct entry.  iTab is a sorting index that holds previously
107066 ** seen combinations of the N values.  A new entry is made in iTab
107067 ** if the current N values are new.
107068 **
107069 ** A jump to addrRepeat is made and the N+1 values are popped from the
107070 ** stack if the top N elements are not distinct.
107071 */
107072 static void codeDistinct(
107073   Parse *pParse,     /* Parsing and code generating context */
107074   int iTab,          /* A sorting index used to test for distinctness */
107075   int addrRepeat,    /* Jump to here if not distinct */
107076   int N,             /* Number of elements */
107077   int iMem           /* First element */
107078 ){
107079   Vdbe *v;
107080   int r1;
107081 
107082   v = pParse->pVdbe;
107083   r1 = sqlite3GetTempReg(pParse);
107084   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
107085   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
107086   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
107087   sqlite3ReleaseTempReg(pParse, r1);
107088 }
107089 
107090 #ifndef SQLITE_OMIT_SUBQUERY
107091 /*
107092 ** Generate an error message when a SELECT is used within a subexpression
107093 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
107094 ** column.  We do this in a subroutine because the error used to occur
107095 ** in multiple places.  (The error only occurs in one place now, but we
107096 ** retain the subroutine to minimize code disruption.)
107097 */
107098 static int checkForMultiColumnSelectError(
107099   Parse *pParse,       /* Parse context. */
107100   SelectDest *pDest,   /* Destination of SELECT results */
107101   int nExpr            /* Number of result columns returned by SELECT */
107102 ){
107103   int eDest = pDest->eDest;
107104   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
107105     sqlite3ErrorMsg(pParse, "only a single result allowed for "
107106        "a SELECT that is part of an expression");
107107     return 1;
107108   }else{
107109     return 0;
107110   }
107111 }
107112 #endif
107113 
107114 /*
107115 ** This routine generates the code for the inside of the inner loop
107116 ** of a SELECT.
107117 **
107118 ** If srcTab is negative, then the pEList expressions
107119 ** are evaluated in order to get the data for this row.  If srcTab is
107120 ** zero or more, then data is pulled from srcTab and pEList is used only
107121 ** to get number columns and the datatype for each column.
107122 */
107123 static void selectInnerLoop(
107124   Parse *pParse,          /* The parser context */
107125   Select *p,              /* The complete select statement being coded */
107126   ExprList *pEList,       /* List of values being extracted */
107127   int srcTab,             /* Pull data from this table */
107128   SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
107129   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
107130   SelectDest *pDest,      /* How to dispose of the results */
107131   int iContinue,          /* Jump here to continue with next row */
107132   int iBreak              /* Jump here to break out of the inner loop */
107133 ){
107134   Vdbe *v = pParse->pVdbe;
107135   int i;
107136   int hasDistinct;        /* True if the DISTINCT keyword is present */
107137   int regResult;              /* Start of memory holding result set */
107138   int eDest = pDest->eDest;   /* How to dispose of results */
107139   int iParm = pDest->iSDParm; /* First argument to disposal method */
107140   int nResultCol;             /* Number of result columns */
107141   int nPrefixReg = 0;         /* Number of extra registers before regResult */
107142 
107143   assert( v );
107144   assert( pEList!=0 );
107145   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
107146   if( pSort && pSort->pOrderBy==0 ) pSort = 0;
107147   if( pSort==0 && !hasDistinct ){
107148     assert( iContinue!=0 );
107149     codeOffset(v, p->iOffset, iContinue);
107150   }
107151 
107152   /* Pull the requested columns.
107153   */
107154   nResultCol = pEList->nExpr;
107155 
107156   if( pDest->iSdst==0 ){
107157     if( pSort ){
107158       nPrefixReg = pSort->pOrderBy->nExpr;
107159       if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
107160       pParse->nMem += nPrefixReg;
107161     }
107162     pDest->iSdst = pParse->nMem+1;
107163     pParse->nMem += nResultCol;
107164   }else if( pDest->iSdst+nResultCol > pParse->nMem ){
107165     /* This is an error condition that can result, for example, when a SELECT
107166     ** on the right-hand side of an INSERT contains more result columns than
107167     ** there are columns in the table on the left.  The error will be caught
107168     ** and reported later.  But we need to make sure enough memory is allocated
107169     ** to avoid other spurious errors in the meantime. */
107170     pParse->nMem += nResultCol;
107171   }
107172   pDest->nSdst = nResultCol;
107173   regResult = pDest->iSdst;
107174   if( srcTab>=0 ){
107175     for(i=0; i<nResultCol; i++){
107176       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
107177       VdbeComment((v, "%s", pEList->a[i].zName));
107178     }
107179   }else if( eDest!=SRT_Exists ){
107180     /* If the destination is an EXISTS(...) expression, the actual
107181     ** values returned by the SELECT are not required.
107182     */
107183     sqlite3ExprCodeExprList(pParse, pEList, regResult,
107184                   (eDest==SRT_Output||eDest==SRT_Coroutine)?SQLITE_ECEL_DUP:0);
107185   }
107186 
107187   /* If the DISTINCT keyword was present on the SELECT statement
107188   ** and this row has been seen before, then do not make this row
107189   ** part of the result.
107190   */
107191   if( hasDistinct ){
107192     switch( pDistinct->eTnctType ){
107193       case WHERE_DISTINCT_ORDERED: {
107194         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
107195         int iJump;              /* Jump destination */
107196         int regPrev;            /* Previous row content */
107197 
107198         /* Allocate space for the previous row */
107199         regPrev = pParse->nMem+1;
107200         pParse->nMem += nResultCol;
107201 
107202         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
107203         ** sets the MEM_Cleared bit on the first register of the
107204         ** previous value.  This will cause the OP_Ne below to always
107205         ** fail on the first iteration of the loop even if the first
107206         ** row is all NULLs.
107207         */
107208         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
107209         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
107210         pOp->opcode = OP_Null;
107211         pOp->p1 = 1;
107212         pOp->p2 = regPrev;
107213 
107214         iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
107215         for(i=0; i<nResultCol; i++){
107216           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
107217           if( i<nResultCol-1 ){
107218             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
107219             VdbeCoverage(v);
107220           }else{
107221             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
107222             VdbeCoverage(v);
107223            }
107224           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
107225           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
107226         }
107227         assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
107228         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
107229         break;
107230       }
107231 
107232       case WHERE_DISTINCT_UNIQUE: {
107233         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
107234         break;
107235       }
107236 
107237       default: {
107238         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
107239         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult);
107240         break;
107241       }
107242     }
107243     if( pSort==0 ){
107244       codeOffset(v, p->iOffset, iContinue);
107245     }
107246   }
107247 
107248   switch( eDest ){
107249     /* In this mode, write each query result to the key of the temporary
107250     ** table iParm.
107251     */
107252 #ifndef SQLITE_OMIT_COMPOUND_SELECT
107253     case SRT_Union: {
107254       int r1;
107255       r1 = sqlite3GetTempReg(pParse);
107256       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
107257       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
107258       sqlite3ReleaseTempReg(pParse, r1);
107259       break;
107260     }
107261 
107262     /* Construct a record from the query result, but instead of
107263     ** saving that record, use it as a key to delete elements from
107264     ** the temporary table iParm.
107265     */
107266     case SRT_Except: {
107267       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
107268       break;
107269     }
107270 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
107271 
107272     /* Store the result as data using a unique key.
107273     */
107274     case SRT_Fifo:
107275     case SRT_DistFifo:
107276     case SRT_Table:
107277     case SRT_EphemTab: {
107278       int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
107279       testcase( eDest==SRT_Table );
107280       testcase( eDest==SRT_EphemTab );
107281       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
107282 #ifndef SQLITE_OMIT_CTE
107283       if( eDest==SRT_DistFifo ){
107284         /* If the destination is DistFifo, then cursor (iParm+1) is open
107285         ** on an ephemeral index. If the current row is already present
107286         ** in the index, do not write it to the output. If not, add the
107287         ** current row to the index and proceed with writing it to the
107288         ** output table as well.  */
107289         int addr = sqlite3VdbeCurrentAddr(v) + 4;
107290         sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v);
107291         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
107292         assert( pSort==0 );
107293       }
107294 #endif
107295       if( pSort ){
107296         pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, 1, nPrefixReg);
107297       }else{
107298         int r2 = sqlite3GetTempReg(pParse);
107299         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
107300         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
107301         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
107302         sqlite3ReleaseTempReg(pParse, r2);
107303       }
107304       sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
107305       break;
107306     }
107307 
107308 #ifndef SQLITE_OMIT_SUBQUERY
107309     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
107310     ** then there should be a single item on the stack.  Write this
107311     ** item into the set table with bogus data.
107312     */
107313     case SRT_Set: {
107314       assert( nResultCol==1 );
107315       pDest->affSdst =
107316                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
107317       if( pSort ){
107318         /* At first glance you would think we could optimize out the
107319         ** ORDER BY in this case since the order of entries in the set
107320         ** does not matter.  But there might be a LIMIT clause, in which
107321         ** case the order does matter */
107322         pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
107323       }else{
107324         int r1 = sqlite3GetTempReg(pParse);
107325         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
107326         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
107327         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
107328         sqlite3ReleaseTempReg(pParse, r1);
107329       }
107330       break;
107331     }
107332 
107333     /* If any row exist in the result set, record that fact and abort.
107334     */
107335     case SRT_Exists: {
107336       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
107337       /* The LIMIT clause will terminate the loop for us */
107338       break;
107339     }
107340 
107341     /* If this is a scalar select that is part of an expression, then
107342     ** store the results in the appropriate memory cell and break out
107343     ** of the scan loop.
107344     */
107345     case SRT_Mem: {
107346       assert( nResultCol==1 );
107347       if( pSort ){
107348         pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
107349       }else{
107350         assert( regResult==iParm );
107351         /* The LIMIT clause will jump out of the loop for us */
107352       }
107353       break;
107354     }
107355 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
107356 
107357     case SRT_Coroutine:       /* Send data to a co-routine */
107358     case SRT_Output: {        /* Return the results */
107359       testcase( eDest==SRT_Coroutine );
107360       testcase( eDest==SRT_Output );
107361       if( pSort ){
107362         pushOntoSorter(pParse, pSort, p, regResult, nResultCol, nPrefixReg);
107363       }else if( eDest==SRT_Coroutine ){
107364         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
107365       }else{
107366         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
107367         sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
107368       }
107369       break;
107370     }
107371 
107372 #ifndef SQLITE_OMIT_CTE
107373     /* Write the results into a priority queue that is order according to
107374     ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
107375     ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
107376     ** pSO->nExpr columns, then make sure all keys are unique by adding a
107377     ** final OP_Sequence column.  The last column is the record as a blob.
107378     */
107379     case SRT_DistQueue:
107380     case SRT_Queue: {
107381       int nKey;
107382       int r1, r2, r3;
107383       int addrTest = 0;
107384       ExprList *pSO;
107385       pSO = pDest->pOrderBy;
107386       assert( pSO );
107387       nKey = pSO->nExpr;
107388       r1 = sqlite3GetTempReg(pParse);
107389       r2 = sqlite3GetTempRange(pParse, nKey+2);
107390       r3 = r2+nKey+1;
107391       if( eDest==SRT_DistQueue ){
107392         /* If the destination is DistQueue, then cursor (iParm+1) is open
107393         ** on a second ephemeral index that holds all values every previously
107394         ** added to the queue. */
107395         addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
107396                                         regResult, nResultCol);
107397         VdbeCoverage(v);
107398       }
107399       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
107400       if( eDest==SRT_DistQueue ){
107401         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
107402         sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
107403       }
107404       for(i=0; i<nKey; i++){
107405         sqlite3VdbeAddOp2(v, OP_SCopy,
107406                           regResult + pSO->a[i].u.x.iOrderByCol - 1,
107407                           r2+i);
107408       }
107409       sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
107410       sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
107411       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
107412       if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
107413       sqlite3ReleaseTempReg(pParse, r1);
107414       sqlite3ReleaseTempRange(pParse, r2, nKey+2);
107415       break;
107416     }
107417 #endif /* SQLITE_OMIT_CTE */
107418 
107419 
107420 
107421 #if !defined(SQLITE_OMIT_TRIGGER)
107422     /* Discard the results.  This is used for SELECT statements inside
107423     ** the body of a TRIGGER.  The purpose of such selects is to call
107424     ** user-defined functions that have side effects.  We do not care
107425     ** about the actual results of the select.
107426     */
107427     default: {
107428       assert( eDest==SRT_Discard );
107429       break;
107430     }
107431 #endif
107432   }
107433 
107434   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
107435   ** there is a sorter, in which case the sorter has already limited
107436   ** the output for us.
107437   */
107438   if( pSort==0 && p->iLimit ){
107439     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
107440   }
107441 }
107442 
107443 /*
107444 ** Allocate a KeyInfo object sufficient for an index of N key columns and
107445 ** X extra columns.
107446 */
107447 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
107448   KeyInfo *p = sqlite3DbMallocZero(0,
107449                    sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
107450   if( p ){
107451     p->aSortOrder = (u8*)&p->aColl[N+X];
107452     p->nField = (u16)N;
107453     p->nXField = (u16)X;
107454     p->enc = ENC(db);
107455     p->db = db;
107456     p->nRef = 1;
107457   }else{
107458     db->mallocFailed = 1;
107459   }
107460   return p;
107461 }
107462 
107463 /*
107464 ** Deallocate a KeyInfo object
107465 */
107466 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
107467   if( p ){
107468     assert( p->nRef>0 );
107469     p->nRef--;
107470     if( p->nRef==0 ) sqlite3DbFree(0, p);
107471   }
107472 }
107473 
107474 /*
107475 ** Make a new pointer to a KeyInfo object
107476 */
107477 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
107478   if( p ){
107479     assert( p->nRef>0 );
107480     p->nRef++;
107481   }
107482   return p;
107483 }
107484 
107485 #ifdef SQLITE_DEBUG
107486 /*
107487 ** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
107488 ** can only be changed if this is just a single reference to the object.
107489 **
107490 ** This routine is used only inside of assert() statements.
107491 */
107492 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
107493 #endif /* SQLITE_DEBUG */
107494 
107495 /*
107496 ** Given an expression list, generate a KeyInfo structure that records
107497 ** the collating sequence for each expression in that expression list.
107498 **
107499 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
107500 ** KeyInfo structure is appropriate for initializing a virtual index to
107501 ** implement that clause.  If the ExprList is the result set of a SELECT
107502 ** then the KeyInfo structure is appropriate for initializing a virtual
107503 ** index to implement a DISTINCT test.
107504 **
107505 ** Space to hold the KeyInfo structure is obtained from malloc.  The calling
107506 ** function is responsible for seeing that this structure is eventually
107507 ** freed.
107508 */
107509 static KeyInfo *keyInfoFromExprList(
107510   Parse *pParse,       /* Parsing context */
107511   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
107512   int iStart,          /* Begin with this column of pList */
107513   int nExtra           /* Add this many extra columns to the end */
107514 ){
107515   int nExpr;
107516   KeyInfo *pInfo;
107517   struct ExprList_item *pItem;
107518   sqlite3 *db = pParse->db;
107519   int i;
107520 
107521   nExpr = pList->nExpr;
107522   pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
107523   if( pInfo ){
107524     assert( sqlite3KeyInfoIsWriteable(pInfo) );
107525     for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
107526       CollSeq *pColl;
107527       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
107528       if( !pColl ) pColl = db->pDfltColl;
107529       pInfo->aColl[i-iStart] = pColl;
107530       pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
107531     }
107532   }
107533   return pInfo;
107534 }
107535 
107536 #ifndef SQLITE_OMIT_COMPOUND_SELECT
107537 /*
107538 ** Name of the connection operator, used for error messages.
107539 */
107540 static const char *selectOpName(int id){
107541   char *z;
107542   switch( id ){
107543     case TK_ALL:       z = "UNION ALL";   break;
107544     case TK_INTERSECT: z = "INTERSECT";   break;
107545     case TK_EXCEPT:    z = "EXCEPT";      break;
107546     default:           z = "UNION";       break;
107547   }
107548   return z;
107549 }
107550 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
107551 
107552 #ifndef SQLITE_OMIT_EXPLAIN
107553 /*
107554 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
107555 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
107556 ** where the caption is of the form:
107557 **
107558 **   "USE TEMP B-TREE FOR xxx"
107559 **
107560 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
107561 ** is determined by the zUsage argument.
107562 */
107563 static void explainTempTable(Parse *pParse, const char *zUsage){
107564   if( pParse->explain==2 ){
107565     Vdbe *v = pParse->pVdbe;
107566     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
107567     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
107568   }
107569 }
107570 
107571 /*
107572 ** Assign expression b to lvalue a. A second, no-op, version of this macro
107573 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
107574 ** in sqlite3Select() to assign values to structure member variables that
107575 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
107576 ** code with #ifndef directives.
107577 */
107578 # define explainSetInteger(a, b) a = b
107579 
107580 #else
107581 /* No-op versions of the explainXXX() functions and macros. */
107582 # define explainTempTable(y,z)
107583 # define explainSetInteger(y,z)
107584 #endif
107585 
107586 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
107587 /*
107588 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
107589 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
107590 ** where the caption is of one of the two forms:
107591 **
107592 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
107593 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
107594 **
107595 ** where iSub1 and iSub2 are the integers passed as the corresponding
107596 ** function parameters, and op is the text representation of the parameter
107597 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
107598 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
107599 ** false, or the second form if it is true.
107600 */
107601 static void explainComposite(
107602   Parse *pParse,                  /* Parse context */
107603   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
107604   int iSub1,                      /* Subquery id 1 */
107605   int iSub2,                      /* Subquery id 2 */
107606   int bUseTmp                     /* True if a temp table was used */
107607 ){
107608   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
107609   if( pParse->explain==2 ){
107610     Vdbe *v = pParse->pVdbe;
107611     char *zMsg = sqlite3MPrintf(
107612         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
107613         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
107614     );
107615     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
107616   }
107617 }
107618 #else
107619 /* No-op versions of the explainXXX() functions and macros. */
107620 # define explainComposite(v,w,x,y,z)
107621 #endif
107622 
107623 /*
107624 ** If the inner loop was generated using a non-null pOrderBy argument,
107625 ** then the results were placed in a sorter.  After the loop is terminated
107626 ** we need to run the sorter and output the results.  The following
107627 ** routine generates the code needed to do that.
107628 */
107629 static void generateSortTail(
107630   Parse *pParse,    /* Parsing context */
107631   Select *p,        /* The SELECT statement */
107632   SortCtx *pSort,   /* Information on the ORDER BY clause */
107633   int nColumn,      /* Number of columns of data */
107634   SelectDest *pDest /* Write the sorted results here */
107635 ){
107636   Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
107637   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
107638   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
107639   int addr;
107640   int addrOnce = 0;
107641   int iTab;
107642   ExprList *pOrderBy = pSort->pOrderBy;
107643   int eDest = pDest->eDest;
107644   int iParm = pDest->iSDParm;
107645   int regRow;
107646   int regRowid;
107647   int nKey;
107648   int iSortTab;                   /* Sorter cursor to read from */
107649   int nSortData;                  /* Trailing values to read from sorter */
107650   int i;
107651   int bSeq;                       /* True if sorter record includes seq. no. */
107652 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
107653   struct ExprList_item *aOutEx = p->pEList->a;
107654 #endif
107655 
107656   if( pSort->labelBkOut ){
107657     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
107658     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBreak);
107659     sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
107660   }
107661   iTab = pSort->iECursor;
107662   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
107663     regRowid = 0;
107664     regRow = pDest->iSdst;
107665     nSortData = nColumn;
107666   }else{
107667     regRowid = sqlite3GetTempReg(pParse);
107668     regRow = sqlite3GetTempReg(pParse);
107669     nSortData = 1;
107670   }
107671   nKey = pOrderBy->nExpr - pSort->nOBSat;
107672   if( pSort->sortFlags & SORTFLAG_UseSorter ){
107673     int regSortOut = ++pParse->nMem;
107674     iSortTab = pParse->nTab++;
107675     if( pSort->labelBkOut ){
107676       addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
107677     }
107678     sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
107679     if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
107680     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
107681     VdbeCoverage(v);
107682     codeOffset(v, p->iOffset, addrContinue);
107683     sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
107684     bSeq = 0;
107685   }else{
107686     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
107687     codeOffset(v, p->iOffset, addrContinue);
107688     iSortTab = iTab;
107689     bSeq = 1;
107690   }
107691   for(i=0; i<nSortData; i++){
107692     sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
107693     VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
107694   }
107695   switch( eDest ){
107696     case SRT_Table:
107697     case SRT_EphemTab: {
107698       testcase( eDest==SRT_Table );
107699       testcase( eDest==SRT_EphemTab );
107700       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
107701       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
107702       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
107703       break;
107704     }
107705 #ifndef SQLITE_OMIT_SUBQUERY
107706     case SRT_Set: {
107707       assert( nColumn==1 );
107708       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
107709                         &pDest->affSdst, 1);
107710       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
107711       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
107712       break;
107713     }
107714     case SRT_Mem: {
107715       assert( nColumn==1 );
107716       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
107717       /* The LIMIT clause will terminate the loop for us */
107718       break;
107719     }
107720 #endif
107721     default: {
107722       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
107723       testcase( eDest==SRT_Output );
107724       testcase( eDest==SRT_Coroutine );
107725       if( eDest==SRT_Output ){
107726         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
107727         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
107728       }else{
107729         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
107730       }
107731       break;
107732     }
107733   }
107734   if( regRowid ){
107735     sqlite3ReleaseTempReg(pParse, regRow);
107736     sqlite3ReleaseTempReg(pParse, regRowid);
107737   }
107738   /* The bottom of the loop
107739   */
107740   sqlite3VdbeResolveLabel(v, addrContinue);
107741   if( pSort->sortFlags & SORTFLAG_UseSorter ){
107742     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
107743   }else{
107744     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
107745   }
107746   if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
107747   sqlite3VdbeResolveLabel(v, addrBreak);
107748 }
107749 
107750 /*
107751 ** Return a pointer to a string containing the 'declaration type' of the
107752 ** expression pExpr. The string may be treated as static by the caller.
107753 **
107754 ** Also try to estimate the size of the returned value and return that
107755 ** result in *pEstWidth.
107756 **
107757 ** The declaration type is the exact datatype definition extracted from the
107758 ** original CREATE TABLE statement if the expression is a column. The
107759 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
107760 ** is considered a column can be complex in the presence of subqueries. The
107761 ** result-set expression in all of the following SELECT statements is
107762 ** considered a column by this function.
107763 **
107764 **   SELECT col FROM tbl;
107765 **   SELECT (SELECT col FROM tbl;
107766 **   SELECT (SELECT col FROM tbl);
107767 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
107768 **
107769 ** The declaration type for any expression other than a column is NULL.
107770 **
107771 ** This routine has either 3 or 6 parameters depending on whether or not
107772 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
107773 */
107774 #ifdef SQLITE_ENABLE_COLUMN_METADATA
107775 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
107776 static const char *columnTypeImpl(
107777   NameContext *pNC,
107778   Expr *pExpr,
107779   const char **pzOrigDb,
107780   const char **pzOrigTab,
107781   const char **pzOrigCol,
107782   u8 *pEstWidth
107783 ){
107784   char const *zOrigDb = 0;
107785   char const *zOrigTab = 0;
107786   char const *zOrigCol = 0;
107787 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
107788 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
107789 static const char *columnTypeImpl(
107790   NameContext *pNC,
107791   Expr *pExpr,
107792   u8 *pEstWidth
107793 ){
107794 #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
107795   char const *zType = 0;
107796   int j;
107797   u8 estWidth = 1;
107798 
107799   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
107800   switch( pExpr->op ){
107801     case TK_AGG_COLUMN:
107802     case TK_COLUMN: {
107803       /* The expression is a column. Locate the table the column is being
107804       ** extracted from in NameContext.pSrcList. This table may be real
107805       ** database table or a subquery.
107806       */
107807       Table *pTab = 0;            /* Table structure column is extracted from */
107808       Select *pS = 0;             /* Select the column is extracted from */
107809       int iCol = pExpr->iColumn;  /* Index of column in pTab */
107810       testcase( pExpr->op==TK_AGG_COLUMN );
107811       testcase( pExpr->op==TK_COLUMN );
107812       while( pNC && !pTab ){
107813         SrcList *pTabList = pNC->pSrcList;
107814         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
107815         if( j<pTabList->nSrc ){
107816           pTab = pTabList->a[j].pTab;
107817           pS = pTabList->a[j].pSelect;
107818         }else{
107819           pNC = pNC->pNext;
107820         }
107821       }
107822 
107823       if( pTab==0 ){
107824         /* At one time, code such as "SELECT new.x" within a trigger would
107825         ** cause this condition to run.  Since then, we have restructured how
107826         ** trigger code is generated and so this condition is no longer
107827         ** possible. However, it can still be true for statements like
107828         ** the following:
107829         **
107830         **   CREATE TABLE t1(col INTEGER);
107831         **   SELECT (SELECT t1.col) FROM FROM t1;
107832         **
107833         ** when columnType() is called on the expression "t1.col" in the
107834         ** sub-select. In this case, set the column type to NULL, even
107835         ** though it should really be "INTEGER".
107836         **
107837         ** This is not a problem, as the column type of "t1.col" is never
107838         ** used. When columnType() is called on the expression
107839         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
107840         ** branch below.  */
107841         break;
107842       }
107843 
107844       assert( pTab && pExpr->pTab==pTab );
107845       if( pS ){
107846         /* The "table" is actually a sub-select or a view in the FROM clause
107847         ** of the SELECT statement. Return the declaration type and origin
107848         ** data for the result-set column of the sub-select.
107849         */
107850         if( iCol>=0 && iCol<pS->pEList->nExpr ){
107851           /* If iCol is less than zero, then the expression requests the
107852           ** rowid of the sub-select or view. This expression is legal (see
107853           ** test case misc2.2.2) - it always evaluates to NULL.
107854           */
107855           NameContext sNC;
107856           Expr *p = pS->pEList->a[iCol].pExpr;
107857           sNC.pSrcList = pS->pSrc;
107858           sNC.pNext = pNC;
107859           sNC.pParse = pNC->pParse;
107860           zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
107861         }
107862       }else if( pTab->pSchema ){
107863         /* A real table */
107864         assert( !pS );
107865         if( iCol<0 ) iCol = pTab->iPKey;
107866         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
107867 #ifdef SQLITE_ENABLE_COLUMN_METADATA
107868         if( iCol<0 ){
107869           zType = "INTEGER";
107870           zOrigCol = "rowid";
107871         }else{
107872           zType = pTab->aCol[iCol].zType;
107873           zOrigCol = pTab->aCol[iCol].zName;
107874           estWidth = pTab->aCol[iCol].szEst;
107875         }
107876         zOrigTab = pTab->zName;
107877         if( pNC->pParse ){
107878           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
107879           zOrigDb = pNC->pParse->db->aDb[iDb].zName;
107880         }
107881 #else
107882         if( iCol<0 ){
107883           zType = "INTEGER";
107884         }else{
107885           zType = pTab->aCol[iCol].zType;
107886           estWidth = pTab->aCol[iCol].szEst;
107887         }
107888 #endif
107889       }
107890       break;
107891     }
107892 #ifndef SQLITE_OMIT_SUBQUERY
107893     case TK_SELECT: {
107894       /* The expression is a sub-select. Return the declaration type and
107895       ** origin info for the single column in the result set of the SELECT
107896       ** statement.
107897       */
107898       NameContext sNC;
107899       Select *pS = pExpr->x.pSelect;
107900       Expr *p = pS->pEList->a[0].pExpr;
107901       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
107902       sNC.pSrcList = pS->pSrc;
107903       sNC.pNext = pNC;
107904       sNC.pParse = pNC->pParse;
107905       zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
107906       break;
107907     }
107908 #endif
107909   }
107910 
107911 #ifdef SQLITE_ENABLE_COLUMN_METADATA
107912   if( pzOrigDb ){
107913     assert( pzOrigTab && pzOrigCol );
107914     *pzOrigDb = zOrigDb;
107915     *pzOrigTab = zOrigTab;
107916     *pzOrigCol = zOrigCol;
107917   }
107918 #endif
107919   if( pEstWidth ) *pEstWidth = estWidth;
107920   return zType;
107921 }
107922 
107923 /*
107924 ** Generate code that will tell the VDBE the declaration types of columns
107925 ** in the result set.
107926 */
107927 static void generateColumnTypes(
107928   Parse *pParse,      /* Parser context */
107929   SrcList *pTabList,  /* List of tables */
107930   ExprList *pEList    /* Expressions defining the result set */
107931 ){
107932 #ifndef SQLITE_OMIT_DECLTYPE
107933   Vdbe *v = pParse->pVdbe;
107934   int i;
107935   NameContext sNC;
107936   sNC.pSrcList = pTabList;
107937   sNC.pParse = pParse;
107938   for(i=0; i<pEList->nExpr; i++){
107939     Expr *p = pEList->a[i].pExpr;
107940     const char *zType;
107941 #ifdef SQLITE_ENABLE_COLUMN_METADATA
107942     const char *zOrigDb = 0;
107943     const char *zOrigTab = 0;
107944     const char *zOrigCol = 0;
107945     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
107946 
107947     /* The vdbe must make its own copy of the column-type and other
107948     ** column specific strings, in case the schema is reset before this
107949     ** virtual machine is deleted.
107950     */
107951     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
107952     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
107953     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
107954 #else
107955     zType = columnType(&sNC, p, 0, 0, 0, 0);
107956 #endif
107957     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
107958   }
107959 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
107960 }
107961 
107962 /*
107963 ** Generate code that will tell the VDBE the names of columns
107964 ** in the result set.  This information is used to provide the
107965 ** azCol[] values in the callback.
107966 */
107967 static void generateColumnNames(
107968   Parse *pParse,      /* Parser context */
107969   SrcList *pTabList,  /* List of tables */
107970   ExprList *pEList    /* Expressions defining the result set */
107971 ){
107972   Vdbe *v = pParse->pVdbe;
107973   int i, j;
107974   sqlite3 *db = pParse->db;
107975   int fullNames, shortNames;
107976 
107977 #ifndef SQLITE_OMIT_EXPLAIN
107978   /* If this is an EXPLAIN, skip this step */
107979   if( pParse->explain ){
107980     return;
107981   }
107982 #endif
107983 
107984   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
107985   pParse->colNamesSet = 1;
107986   fullNames = (db->flags & SQLITE_FullColNames)!=0;
107987   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
107988   sqlite3VdbeSetNumCols(v, pEList->nExpr);
107989   for(i=0; i<pEList->nExpr; i++){
107990     Expr *p;
107991     p = pEList->a[i].pExpr;
107992     if( NEVER(p==0) ) continue;
107993     if( pEList->a[i].zName ){
107994       char *zName = pEList->a[i].zName;
107995       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
107996     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
107997       Table *pTab;
107998       char *zCol;
107999       int iCol = p->iColumn;
108000       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
108001         if( pTabList->a[j].iCursor==p->iTable ) break;
108002       }
108003       assert( j<pTabList->nSrc );
108004       pTab = pTabList->a[j].pTab;
108005       if( iCol<0 ) iCol = pTab->iPKey;
108006       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
108007       if( iCol<0 ){
108008         zCol = "rowid";
108009       }else{
108010         zCol = pTab->aCol[iCol].zName;
108011       }
108012       if( !shortNames && !fullNames ){
108013         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
108014             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
108015       }else if( fullNames ){
108016         char *zName = 0;
108017         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
108018         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
108019       }else{
108020         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
108021       }
108022     }else{
108023       const char *z = pEList->a[i].zSpan;
108024       z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
108025       sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
108026     }
108027   }
108028   generateColumnTypes(pParse, pTabList, pEList);
108029 }
108030 
108031 /*
108032 ** Given an expression list (which is really the list of expressions
108033 ** that form the result set of a SELECT statement) compute appropriate
108034 ** column names for a table that would hold the expression list.
108035 **
108036 ** All column names will be unique.
108037 **
108038 ** Only the column names are computed.  Column.zType, Column.zColl,
108039 ** and other fields of Column are zeroed.
108040 **
108041 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
108042 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
108043 */
108044 static int selectColumnsFromExprList(
108045   Parse *pParse,          /* Parsing context */
108046   ExprList *pEList,       /* Expr list from which to derive column names */
108047   i16 *pnCol,             /* Write the number of columns here */
108048   Column **paCol          /* Write the new column list here */
108049 ){
108050   sqlite3 *db = pParse->db;   /* Database connection */
108051   int i, j;                   /* Loop counters */
108052   int cnt;                    /* Index added to make the name unique */
108053   Column *aCol, *pCol;        /* For looping over result columns */
108054   int nCol;                   /* Number of columns in the result set */
108055   Expr *p;                    /* Expression for a single result column */
108056   char *zName;                /* Column name */
108057   int nName;                  /* Size of name in zName[] */
108058 
108059   if( pEList ){
108060     nCol = pEList->nExpr;
108061     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
108062     testcase( aCol==0 );
108063   }else{
108064     nCol = 0;
108065     aCol = 0;
108066   }
108067   *pnCol = nCol;
108068   *paCol = aCol;
108069 
108070   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
108071     /* Get an appropriate name for the column
108072     */
108073     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
108074     if( (zName = pEList->a[i].zName)!=0 ){
108075       /* If the column contains an "AS <name>" phrase, use <name> as the name */
108076       zName = sqlite3DbStrDup(db, zName);
108077     }else{
108078       Expr *pColExpr = p;  /* The expression that is the result column name */
108079       Table *pTab;         /* Table associated with this expression */
108080       while( pColExpr->op==TK_DOT ){
108081         pColExpr = pColExpr->pRight;
108082         assert( pColExpr!=0 );
108083       }
108084       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
108085         /* For columns use the column name name */
108086         int iCol = pColExpr->iColumn;
108087         pTab = pColExpr->pTab;
108088         if( iCol<0 ) iCol = pTab->iPKey;
108089         zName = sqlite3MPrintf(db, "%s",
108090                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
108091       }else if( pColExpr->op==TK_ID ){
108092         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
108093         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
108094       }else{
108095         /* Use the original text of the column expression as its name */
108096         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
108097       }
108098     }
108099     if( db->mallocFailed ){
108100       sqlite3DbFree(db, zName);
108101       break;
108102     }
108103 
108104     /* Make sure the column name is unique.  If the name is not unique,
108105     ** append an integer to the name so that it becomes unique.
108106     */
108107     nName = sqlite3Strlen30(zName);
108108     for(j=cnt=0; j<i; j++){
108109       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
108110         char *zNewName;
108111         int k;
108112         for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
108113         if( k>=0 && zName[k]==':' ) nName = k;
108114         zName[nName] = 0;
108115         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
108116         sqlite3DbFree(db, zName);
108117         zName = zNewName;
108118         j = -1;
108119         if( zName==0 ) break;
108120       }
108121     }
108122     pCol->zName = zName;
108123   }
108124   if( db->mallocFailed ){
108125     for(j=0; j<i; j++){
108126       sqlite3DbFree(db, aCol[j].zName);
108127     }
108128     sqlite3DbFree(db, aCol);
108129     *paCol = 0;
108130     *pnCol = 0;
108131     return SQLITE_NOMEM;
108132   }
108133   return SQLITE_OK;
108134 }
108135 
108136 /*
108137 ** Add type and collation information to a column list based on
108138 ** a SELECT statement.
108139 **
108140 ** The column list presumably came from selectColumnNamesFromExprList().
108141 ** The column list has only names, not types or collations.  This
108142 ** routine goes through and adds the types and collations.
108143 **
108144 ** This routine requires that all identifiers in the SELECT
108145 ** statement be resolved.
108146 */
108147 static void selectAddColumnTypeAndCollation(
108148   Parse *pParse,        /* Parsing contexts */
108149   Table *pTab,          /* Add column type information to this table */
108150   Select *pSelect       /* SELECT used to determine types and collations */
108151 ){
108152   sqlite3 *db = pParse->db;
108153   NameContext sNC;
108154   Column *pCol;
108155   CollSeq *pColl;
108156   int i;
108157   Expr *p;
108158   struct ExprList_item *a;
108159   u64 szAll = 0;
108160 
108161   assert( pSelect!=0 );
108162   assert( (pSelect->selFlags & SF_Resolved)!=0 );
108163   assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
108164   if( db->mallocFailed ) return;
108165   memset(&sNC, 0, sizeof(sNC));
108166   sNC.pSrcList = pSelect->pSrc;
108167   a = pSelect->pEList->a;
108168   for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
108169     p = a[i].pExpr;
108170     if( pCol->zType==0 ){
108171       pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
108172     }
108173     szAll += pCol->szEst;
108174     pCol->affinity = sqlite3ExprAffinity(p);
108175     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
108176     pColl = sqlite3ExprCollSeq(pParse, p);
108177     if( pColl && pCol->zColl==0 ){
108178       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
108179     }
108180   }
108181   pTab->szTabRow = sqlite3LogEst(szAll*4);
108182 }
108183 
108184 /*
108185 ** Given a SELECT statement, generate a Table structure that describes
108186 ** the result set of that SELECT.
108187 */
108188 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
108189   Table *pTab;
108190   sqlite3 *db = pParse->db;
108191   int savedFlags;
108192 
108193   savedFlags = db->flags;
108194   db->flags &= ~SQLITE_FullColNames;
108195   db->flags |= SQLITE_ShortColNames;
108196   sqlite3SelectPrep(pParse, pSelect, 0);
108197   if( pParse->nErr ) return 0;
108198   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
108199   db->flags = savedFlags;
108200   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
108201   if( pTab==0 ){
108202     return 0;
108203   }
108204   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
108205   ** is disabled */
108206   assert( db->lookaside.bEnabled==0 );
108207   pTab->nRef = 1;
108208   pTab->zName = 0;
108209   pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
108210   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
108211   selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
108212   pTab->iPKey = -1;
108213   if( db->mallocFailed ){
108214     sqlite3DeleteTable(db, pTab);
108215     return 0;
108216   }
108217   return pTab;
108218 }
108219 
108220 /*
108221 ** Get a VDBE for the given parser context.  Create a new one if necessary.
108222 ** If an error occurs, return NULL and leave a message in pParse.
108223 */
108224 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
108225   Vdbe *v = pParse->pVdbe;
108226   if( v==0 ){
108227     v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
108228     if( v ) sqlite3VdbeAddOp0(v, OP_Init);
108229     if( pParse->pToplevel==0
108230      && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
108231     ){
108232       pParse->okConstFactor = 1;
108233     }
108234 
108235   }
108236   return v;
108237 }
108238 
108239 
108240 /*
108241 ** Compute the iLimit and iOffset fields of the SELECT based on the
108242 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
108243 ** that appear in the original SQL statement after the LIMIT and OFFSET
108244 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
108245 ** are the integer memory register numbers for counters used to compute
108246 ** the limit and offset.  If there is no limit and/or offset, then
108247 ** iLimit and iOffset are negative.
108248 **
108249 ** This routine changes the values of iLimit and iOffset only if
108250 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
108251 ** iOffset should have been preset to appropriate default values (zero)
108252 ** prior to calling this routine.
108253 **
108254 ** The iOffset register (if it exists) is initialized to the value
108255 ** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
108256 ** iOffset+1 is initialized to LIMIT+OFFSET.
108257 **
108258 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
108259 ** redefined.  The UNION ALL operator uses this property to force
108260 ** the reuse of the same limit and offset registers across multiple
108261 ** SELECT statements.
108262 */
108263 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
108264   Vdbe *v = 0;
108265   int iLimit = 0;
108266   int iOffset;
108267   int addr1, n;
108268   if( p->iLimit ) return;
108269 
108270   /*
108271   ** "LIMIT -1" always shows all rows.  There is some
108272   ** controversy about what the correct behavior should be.
108273   ** The current implementation interprets "LIMIT 0" to mean
108274   ** no rows.
108275   */
108276   sqlite3ExprCacheClear(pParse);
108277   assert( p->pOffset==0 || p->pLimit!=0 );
108278   if( p->pLimit ){
108279     p->iLimit = iLimit = ++pParse->nMem;
108280     v = sqlite3GetVdbe(pParse);
108281     assert( v!=0 );
108282     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
108283       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
108284       VdbeComment((v, "LIMIT counter"));
108285       if( n==0 ){
108286         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
108287       }else if( n>=0 && p->nSelectRow>(u64)n ){
108288         p->nSelectRow = n;
108289       }
108290     }else{
108291       sqlite3ExprCode(pParse, p->pLimit, iLimit);
108292       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
108293       VdbeComment((v, "LIMIT counter"));
108294       sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
108295     }
108296     if( p->pOffset ){
108297       p->iOffset = iOffset = ++pParse->nMem;
108298       pParse->nMem++;   /* Allocate an extra register for limit+offset */
108299       sqlite3ExprCode(pParse, p->pOffset, iOffset);
108300       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
108301       VdbeComment((v, "OFFSET counter"));
108302       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v);
108303       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
108304       sqlite3VdbeJumpHere(v, addr1);
108305       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
108306       VdbeComment((v, "LIMIT+OFFSET"));
108307       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v);
108308       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
108309       sqlite3VdbeJumpHere(v, addr1);
108310     }
108311   }
108312 }
108313 
108314 #ifndef SQLITE_OMIT_COMPOUND_SELECT
108315 /*
108316 ** Return the appropriate collating sequence for the iCol-th column of
108317 ** the result set for the compound-select statement "p".  Return NULL if
108318 ** the column has no default collating sequence.
108319 **
108320 ** The collating sequence for the compound select is taken from the
108321 ** left-most term of the select that has a collating sequence.
108322 */
108323 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
108324   CollSeq *pRet;
108325   if( p->pPrior ){
108326     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
108327   }else{
108328     pRet = 0;
108329   }
108330   assert( iCol>=0 );
108331   if( pRet==0 && iCol<p->pEList->nExpr ){
108332     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
108333   }
108334   return pRet;
108335 }
108336 
108337 /*
108338 ** The select statement passed as the second parameter is a compound SELECT
108339 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
108340 ** structure suitable for implementing the ORDER BY.
108341 **
108342 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
108343 ** function is responsible for ensuring that this structure is eventually
108344 ** freed.
108345 */
108346 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
108347   ExprList *pOrderBy = p->pOrderBy;
108348   int nOrderBy = p->pOrderBy->nExpr;
108349   sqlite3 *db = pParse->db;
108350   KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
108351   if( pRet ){
108352     int i;
108353     for(i=0; i<nOrderBy; i++){
108354       struct ExprList_item *pItem = &pOrderBy->a[i];
108355       Expr *pTerm = pItem->pExpr;
108356       CollSeq *pColl;
108357 
108358       if( pTerm->flags & EP_Collate ){
108359         pColl = sqlite3ExprCollSeq(pParse, pTerm);
108360       }else{
108361         pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
108362         if( pColl==0 ) pColl = db->pDfltColl;
108363         pOrderBy->a[i].pExpr =
108364           sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
108365       }
108366       assert( sqlite3KeyInfoIsWriteable(pRet) );
108367       pRet->aColl[i] = pColl;
108368       pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
108369     }
108370   }
108371 
108372   return pRet;
108373 }
108374 
108375 #ifndef SQLITE_OMIT_CTE
108376 /*
108377 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
108378 ** query of the form:
108379 **
108380 **   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
108381 **                         \___________/             \_______________/
108382 **                           p->pPrior                      p
108383 **
108384 **
108385 ** There is exactly one reference to the recursive-table in the FROM clause
108386 ** of recursive-query, marked with the SrcList->a[].isRecursive flag.
108387 **
108388 ** The setup-query runs once to generate an initial set of rows that go
108389 ** into a Queue table.  Rows are extracted from the Queue table one by
108390 ** one.  Each row extracted from Queue is output to pDest.  Then the single
108391 ** extracted row (now in the iCurrent table) becomes the content of the
108392 ** recursive-table for a recursive-query run.  The output of the recursive-query
108393 ** is added back into the Queue table.  Then another row is extracted from Queue
108394 ** and the iteration continues until the Queue table is empty.
108395 **
108396 ** If the compound query operator is UNION then no duplicate rows are ever
108397 ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
108398 ** that have ever been inserted into Queue and causes duplicates to be
108399 ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
108400 **
108401 ** If the query has an ORDER BY, then entries in the Queue table are kept in
108402 ** ORDER BY order and the first entry is extracted for each cycle.  Without
108403 ** an ORDER BY, the Queue table is just a FIFO.
108404 **
108405 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
108406 ** have been output to pDest.  A LIMIT of zero means to output no rows and a
108407 ** negative LIMIT means to output all rows.  If there is also an OFFSET clause
108408 ** with a positive value, then the first OFFSET outputs are discarded rather
108409 ** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
108410 ** rows have been skipped.
108411 */
108412 static void generateWithRecursiveQuery(
108413   Parse *pParse,        /* Parsing context */
108414   Select *p,            /* The recursive SELECT to be coded */
108415   SelectDest *pDest     /* What to do with query results */
108416 ){
108417   SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
108418   int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
108419   Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
108420   Select *pSetup = p->pPrior;   /* The setup query */
108421   int addrTop;                  /* Top of the loop */
108422   int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
108423   int iCurrent = 0;             /* The Current table */
108424   int regCurrent;               /* Register holding Current table */
108425   int iQueue;                   /* The Queue table */
108426   int iDistinct = 0;            /* To ensure unique results if UNION */
108427   int eDest = SRT_Fifo;         /* How to write to Queue */
108428   SelectDest destQueue;         /* SelectDest targetting the Queue table */
108429   int i;                        /* Loop counter */
108430   int rc;                       /* Result code */
108431   ExprList *pOrderBy;           /* The ORDER BY clause */
108432   Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
108433   int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
108434 
108435   /* Obtain authorization to do a recursive query */
108436   if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
108437 
108438   /* Process the LIMIT and OFFSET clauses, if they exist */
108439   addrBreak = sqlite3VdbeMakeLabel(v);
108440   computeLimitRegisters(pParse, p, addrBreak);
108441   pLimit = p->pLimit;
108442   pOffset = p->pOffset;
108443   regLimit = p->iLimit;
108444   regOffset = p->iOffset;
108445   p->pLimit = p->pOffset = 0;
108446   p->iLimit = p->iOffset = 0;
108447   pOrderBy = p->pOrderBy;
108448 
108449   /* Locate the cursor number of the Current table */
108450   for(i=0; ALWAYS(i<pSrc->nSrc); i++){
108451     if( pSrc->a[i].isRecursive ){
108452       iCurrent = pSrc->a[i].iCursor;
108453       break;
108454     }
108455   }
108456 
108457   /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
108458   ** the Distinct table must be exactly one greater than Queue in order
108459   ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
108460   iQueue = pParse->nTab++;
108461   if( p->op==TK_UNION ){
108462     eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
108463     iDistinct = pParse->nTab++;
108464   }else{
108465     eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
108466   }
108467   sqlite3SelectDestInit(&destQueue, eDest, iQueue);
108468 
108469   /* Allocate cursors for Current, Queue, and Distinct. */
108470   regCurrent = ++pParse->nMem;
108471   sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
108472   if( pOrderBy ){
108473     KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
108474     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
108475                       (char*)pKeyInfo, P4_KEYINFO);
108476     destQueue.pOrderBy = pOrderBy;
108477   }else{
108478     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
108479   }
108480   VdbeComment((v, "Queue table"));
108481   if( iDistinct ){
108482     p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
108483     p->selFlags |= SF_UsesEphemeral;
108484   }
108485 
108486   /* Detach the ORDER BY clause from the compound SELECT */
108487   p->pOrderBy = 0;
108488 
108489   /* Store the results of the setup-query in Queue. */
108490   pSetup->pNext = 0;
108491   rc = sqlite3Select(pParse, pSetup, &destQueue);
108492   pSetup->pNext = p;
108493   if( rc ) goto end_of_recursive_query;
108494 
108495   /* Find the next row in the Queue and output that row */
108496   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
108497 
108498   /* Transfer the next row in Queue over to Current */
108499   sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
108500   if( pOrderBy ){
108501     sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
108502   }else{
108503     sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
108504   }
108505   sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
108506 
108507   /* Output the single row in Current */
108508   addrCont = sqlite3VdbeMakeLabel(v);
108509   codeOffset(v, regOffset, addrCont);
108510   selectInnerLoop(pParse, p, p->pEList, iCurrent,
108511       0, 0, pDest, addrCont, addrBreak);
108512   if( regLimit ){
108513     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
108514     VdbeCoverage(v);
108515   }
108516   sqlite3VdbeResolveLabel(v, addrCont);
108517 
108518   /* Execute the recursive SELECT taking the single row in Current as
108519   ** the value for the recursive-table. Store the results in the Queue.
108520   */
108521   p->pPrior = 0;
108522   sqlite3Select(pParse, p, &destQueue);
108523   assert( p->pPrior==0 );
108524   p->pPrior = pSetup;
108525 
108526   /* Keep running the loop until the Queue is empty */
108527   sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
108528   sqlite3VdbeResolveLabel(v, addrBreak);
108529 
108530 end_of_recursive_query:
108531   sqlite3ExprListDelete(pParse->db, p->pOrderBy);
108532   p->pOrderBy = pOrderBy;
108533   p->pLimit = pLimit;
108534   p->pOffset = pOffset;
108535   return;
108536 }
108537 #endif /* SQLITE_OMIT_CTE */
108538 
108539 /* Forward references */
108540 static int multiSelectOrderBy(
108541   Parse *pParse,        /* Parsing context */
108542   Select *p,            /* The right-most of SELECTs to be coded */
108543   SelectDest *pDest     /* What to do with query results */
108544 );
108545 
108546 /*
108547 ** Error message for when two or more terms of a compound select have different
108548 ** size result sets.
108549 */
108550 static void selectWrongNumTermsError(Parse *pParse, Select *p){
108551   if( p->selFlags & SF_Values ){
108552     sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
108553   }else{
108554     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
108555       " do not have the same number of result columns", selectOpName(p->op));
108556   }
108557 }
108558 
108559 /*
108560 ** Handle the special case of a compound-select that originates from a
108561 ** VALUES clause.  By handling this as a special case, we avoid deep
108562 ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
108563 ** on a VALUES clause.
108564 **
108565 ** Because the Select object originates from a VALUES clause:
108566 **   (1) It has no LIMIT or OFFSET
108567 **   (2) All terms are UNION ALL
108568 **   (3) There is no ORDER BY clause
108569 */
108570 static int multiSelectValues(
108571   Parse *pParse,        /* Parsing context */
108572   Select *p,            /* The right-most of SELECTs to be coded */
108573   SelectDest *pDest     /* What to do with query results */
108574 ){
108575   Select *pPrior;
108576   int nExpr = p->pEList->nExpr;
108577   int nRow = 1;
108578   int rc = 0;
108579   assert( p->selFlags & SF_MultiValue );
108580   do{
108581     assert( p->selFlags & SF_Values );
108582     assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
108583     assert( p->pLimit==0 );
108584     assert( p->pOffset==0 );
108585     if( p->pEList->nExpr!=nExpr ){
108586       selectWrongNumTermsError(pParse, p);
108587       return 1;
108588     }
108589     if( p->pPrior==0 ) break;
108590     assert( p->pPrior->pNext==p );
108591     p = p->pPrior;
108592     nRow++;
108593   }while(1);
108594   while( p ){
108595     pPrior = p->pPrior;
108596     p->pPrior = 0;
108597     rc = sqlite3Select(pParse, p, pDest);
108598     p->pPrior = pPrior;
108599     if( rc ) break;
108600     p->nSelectRow = nRow;
108601     p = p->pNext;
108602   }
108603   return rc;
108604 }
108605 
108606 /*
108607 ** This routine is called to process a compound query form from
108608 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
108609 ** INTERSECT
108610 **
108611 ** "p" points to the right-most of the two queries.  the query on the
108612 ** left is p->pPrior.  The left query could also be a compound query
108613 ** in which case this routine will be called recursively.
108614 **
108615 ** The results of the total query are to be written into a destination
108616 ** of type eDest with parameter iParm.
108617 **
108618 ** Example 1:  Consider a three-way compound SQL statement.
108619 **
108620 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
108621 **
108622 ** This statement is parsed up as follows:
108623 **
108624 **     SELECT c FROM t3
108625 **      |
108626 **      `----->  SELECT b FROM t2
108627 **                |
108628 **                `------>  SELECT a FROM t1
108629 **
108630 ** The arrows in the diagram above represent the Select.pPrior pointer.
108631 ** So if this routine is called with p equal to the t3 query, then
108632 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
108633 **
108634 ** Notice that because of the way SQLite parses compound SELECTs, the
108635 ** individual selects always group from left to right.
108636 */
108637 static int multiSelect(
108638   Parse *pParse,        /* Parsing context */
108639   Select *p,            /* The right-most of SELECTs to be coded */
108640   SelectDest *pDest     /* What to do with query results */
108641 ){
108642   int rc = SQLITE_OK;   /* Success code from a subroutine */
108643   Select *pPrior;       /* Another SELECT immediately to our left */
108644   Vdbe *v;              /* Generate code to this VDBE */
108645   SelectDest dest;      /* Alternative data destination */
108646   Select *pDelete = 0;  /* Chain of simple selects to delete */
108647   sqlite3 *db;          /* Database connection */
108648 #ifndef SQLITE_OMIT_EXPLAIN
108649   int iSub1 = 0;        /* EQP id of left-hand query */
108650   int iSub2 = 0;        /* EQP id of right-hand query */
108651 #endif
108652 
108653   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
108654   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
108655   */
108656   assert( p && p->pPrior );  /* Calling function guarantees this much */
108657   assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
108658   db = pParse->db;
108659   pPrior = p->pPrior;
108660   dest = *pDest;
108661   if( pPrior->pOrderBy ){
108662     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
108663       selectOpName(p->op));
108664     rc = 1;
108665     goto multi_select_end;
108666   }
108667   if( pPrior->pLimit ){
108668     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
108669       selectOpName(p->op));
108670     rc = 1;
108671     goto multi_select_end;
108672   }
108673 
108674   v = sqlite3GetVdbe(pParse);
108675   assert( v!=0 );  /* The VDBE already created by calling function */
108676 
108677   /* Create the destination temporary table if necessary
108678   */
108679   if( dest.eDest==SRT_EphemTab ){
108680     assert( p->pEList );
108681     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
108682     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
108683     dest.eDest = SRT_Table;
108684   }
108685 
108686   /* Special handling for a compound-select that originates as a VALUES clause.
108687   */
108688   if( p->selFlags & SF_MultiValue ){
108689     rc = multiSelectValues(pParse, p, &dest);
108690     goto multi_select_end;
108691   }
108692 
108693   /* Make sure all SELECTs in the statement have the same number of elements
108694   ** in their result sets.
108695   */
108696   assert( p->pEList && pPrior->pEList );
108697   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
108698     selectWrongNumTermsError(pParse, p);
108699     rc = 1;
108700     goto multi_select_end;
108701   }
108702 
108703 #ifndef SQLITE_OMIT_CTE
108704   if( p->selFlags & SF_Recursive ){
108705     generateWithRecursiveQuery(pParse, p, &dest);
108706   }else
108707 #endif
108708 
108709   /* Compound SELECTs that have an ORDER BY clause are handled separately.
108710   */
108711   if( p->pOrderBy ){
108712     return multiSelectOrderBy(pParse, p, pDest);
108713   }else
108714 
108715   /* Generate code for the left and right SELECT statements.
108716   */
108717   switch( p->op ){
108718     case TK_ALL: {
108719       int addr = 0;
108720       int nLimit;
108721       assert( !pPrior->pLimit );
108722       pPrior->iLimit = p->iLimit;
108723       pPrior->iOffset = p->iOffset;
108724       pPrior->pLimit = p->pLimit;
108725       pPrior->pOffset = p->pOffset;
108726       explainSetInteger(iSub1, pParse->iNextSelectId);
108727       rc = sqlite3Select(pParse, pPrior, &dest);
108728       p->pLimit = 0;
108729       p->pOffset = 0;
108730       if( rc ){
108731         goto multi_select_end;
108732       }
108733       p->pPrior = 0;
108734       p->iLimit = pPrior->iLimit;
108735       p->iOffset = pPrior->iOffset;
108736       if( p->iLimit ){
108737         addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
108738         VdbeComment((v, "Jump ahead if LIMIT reached"));
108739       }
108740       explainSetInteger(iSub2, pParse->iNextSelectId);
108741       rc = sqlite3Select(pParse, p, &dest);
108742       testcase( rc!=SQLITE_OK );
108743       pDelete = p->pPrior;
108744       p->pPrior = pPrior;
108745       p->nSelectRow += pPrior->nSelectRow;
108746       if( pPrior->pLimit
108747        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
108748        && nLimit>0 && p->nSelectRow > (u64)nLimit
108749       ){
108750         p->nSelectRow = nLimit;
108751       }
108752       if( addr ){
108753         sqlite3VdbeJumpHere(v, addr);
108754       }
108755       break;
108756     }
108757     case TK_EXCEPT:
108758     case TK_UNION: {
108759       int unionTab;    /* Cursor number of the temporary table holding result */
108760       u8 op = 0;       /* One of the SRT_ operations to apply to self */
108761       int priorOp;     /* The SRT_ operation to apply to prior selects */
108762       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
108763       int addr;
108764       SelectDest uniondest;
108765 
108766       testcase( p->op==TK_EXCEPT );
108767       testcase( p->op==TK_UNION );
108768       priorOp = SRT_Union;
108769       if( dest.eDest==priorOp ){
108770         /* We can reuse a temporary table generated by a SELECT to our
108771         ** right.
108772         */
108773         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
108774         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
108775         unionTab = dest.iSDParm;
108776       }else{
108777         /* We will need to create our own temporary table to hold the
108778         ** intermediate results.
108779         */
108780         unionTab = pParse->nTab++;
108781         assert( p->pOrderBy==0 );
108782         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
108783         assert( p->addrOpenEphm[0] == -1 );
108784         p->addrOpenEphm[0] = addr;
108785         findRightmost(p)->selFlags |= SF_UsesEphemeral;
108786         assert( p->pEList );
108787       }
108788 
108789       /* Code the SELECT statements to our left
108790       */
108791       assert( !pPrior->pOrderBy );
108792       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
108793       explainSetInteger(iSub1, pParse->iNextSelectId);
108794       rc = sqlite3Select(pParse, pPrior, &uniondest);
108795       if( rc ){
108796         goto multi_select_end;
108797       }
108798 
108799       /* Code the current SELECT statement
108800       */
108801       if( p->op==TK_EXCEPT ){
108802         op = SRT_Except;
108803       }else{
108804         assert( p->op==TK_UNION );
108805         op = SRT_Union;
108806       }
108807       p->pPrior = 0;
108808       pLimit = p->pLimit;
108809       p->pLimit = 0;
108810       pOffset = p->pOffset;
108811       p->pOffset = 0;
108812       uniondest.eDest = op;
108813       explainSetInteger(iSub2, pParse->iNextSelectId);
108814       rc = sqlite3Select(pParse, p, &uniondest);
108815       testcase( rc!=SQLITE_OK );
108816       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
108817       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
108818       sqlite3ExprListDelete(db, p->pOrderBy);
108819       pDelete = p->pPrior;
108820       p->pPrior = pPrior;
108821       p->pOrderBy = 0;
108822       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
108823       sqlite3ExprDelete(db, p->pLimit);
108824       p->pLimit = pLimit;
108825       p->pOffset = pOffset;
108826       p->iLimit = 0;
108827       p->iOffset = 0;
108828 
108829       /* Convert the data in the temporary table into whatever form
108830       ** it is that we currently need.
108831       */
108832       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
108833       if( dest.eDest!=priorOp ){
108834         int iCont, iBreak, iStart;
108835         assert( p->pEList );
108836         if( dest.eDest==SRT_Output ){
108837           Select *pFirst = p;
108838           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
108839           generateColumnNames(pParse, 0, pFirst->pEList);
108840         }
108841         iBreak = sqlite3VdbeMakeLabel(v);
108842         iCont = sqlite3VdbeMakeLabel(v);
108843         computeLimitRegisters(pParse, p, iBreak);
108844         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
108845         iStart = sqlite3VdbeCurrentAddr(v);
108846         selectInnerLoop(pParse, p, p->pEList, unionTab,
108847                         0, 0, &dest, iCont, iBreak);
108848         sqlite3VdbeResolveLabel(v, iCont);
108849         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
108850         sqlite3VdbeResolveLabel(v, iBreak);
108851         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
108852       }
108853       break;
108854     }
108855     default: assert( p->op==TK_INTERSECT ); {
108856       int tab1, tab2;
108857       int iCont, iBreak, iStart;
108858       Expr *pLimit, *pOffset;
108859       int addr;
108860       SelectDest intersectdest;
108861       int r1;
108862 
108863       /* INTERSECT is different from the others since it requires
108864       ** two temporary tables.  Hence it has its own case.  Begin
108865       ** by allocating the tables we will need.
108866       */
108867       tab1 = pParse->nTab++;
108868       tab2 = pParse->nTab++;
108869       assert( p->pOrderBy==0 );
108870 
108871       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
108872       assert( p->addrOpenEphm[0] == -1 );
108873       p->addrOpenEphm[0] = addr;
108874       findRightmost(p)->selFlags |= SF_UsesEphemeral;
108875       assert( p->pEList );
108876 
108877       /* Code the SELECTs to our left into temporary table "tab1".
108878       */
108879       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
108880       explainSetInteger(iSub1, pParse->iNextSelectId);
108881       rc = sqlite3Select(pParse, pPrior, &intersectdest);
108882       if( rc ){
108883         goto multi_select_end;
108884       }
108885 
108886       /* Code the current SELECT into temporary table "tab2"
108887       */
108888       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
108889       assert( p->addrOpenEphm[1] == -1 );
108890       p->addrOpenEphm[1] = addr;
108891       p->pPrior = 0;
108892       pLimit = p->pLimit;
108893       p->pLimit = 0;
108894       pOffset = p->pOffset;
108895       p->pOffset = 0;
108896       intersectdest.iSDParm = tab2;
108897       explainSetInteger(iSub2, pParse->iNextSelectId);
108898       rc = sqlite3Select(pParse, p, &intersectdest);
108899       testcase( rc!=SQLITE_OK );
108900       pDelete = p->pPrior;
108901       p->pPrior = pPrior;
108902       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
108903       sqlite3ExprDelete(db, p->pLimit);
108904       p->pLimit = pLimit;
108905       p->pOffset = pOffset;
108906 
108907       /* Generate code to take the intersection of the two temporary
108908       ** tables.
108909       */
108910       assert( p->pEList );
108911       if( dest.eDest==SRT_Output ){
108912         Select *pFirst = p;
108913         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
108914         generateColumnNames(pParse, 0, pFirst->pEList);
108915       }
108916       iBreak = sqlite3VdbeMakeLabel(v);
108917       iCont = sqlite3VdbeMakeLabel(v);
108918       computeLimitRegisters(pParse, p, iBreak);
108919       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
108920       r1 = sqlite3GetTempReg(pParse);
108921       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
108922       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
108923       sqlite3ReleaseTempReg(pParse, r1);
108924       selectInnerLoop(pParse, p, p->pEList, tab1,
108925                       0, 0, &dest, iCont, iBreak);
108926       sqlite3VdbeResolveLabel(v, iCont);
108927       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
108928       sqlite3VdbeResolveLabel(v, iBreak);
108929       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
108930       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
108931       break;
108932     }
108933   }
108934 
108935   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
108936 
108937   /* Compute collating sequences used by
108938   ** temporary tables needed to implement the compound select.
108939   ** Attach the KeyInfo structure to all temporary tables.
108940   **
108941   ** This section is run by the right-most SELECT statement only.
108942   ** SELECT statements to the left always skip this part.  The right-most
108943   ** SELECT might also skip this part if it has no ORDER BY clause and
108944   ** no temp tables are required.
108945   */
108946   if( p->selFlags & SF_UsesEphemeral ){
108947     int i;                        /* Loop counter */
108948     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
108949     Select *pLoop;                /* For looping through SELECT statements */
108950     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
108951     int nCol;                     /* Number of columns in result set */
108952 
108953     assert( p->pNext==0 );
108954     nCol = p->pEList->nExpr;
108955     pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
108956     if( !pKeyInfo ){
108957       rc = SQLITE_NOMEM;
108958       goto multi_select_end;
108959     }
108960     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
108961       *apColl = multiSelectCollSeq(pParse, p, i);
108962       if( 0==*apColl ){
108963         *apColl = db->pDfltColl;
108964       }
108965     }
108966 
108967     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
108968       for(i=0; i<2; i++){
108969         int addr = pLoop->addrOpenEphm[i];
108970         if( addr<0 ){
108971           /* If [0] is unused then [1] is also unused.  So we can
108972           ** always safely abort as soon as the first unused slot is found */
108973           assert( pLoop->addrOpenEphm[1]<0 );
108974           break;
108975         }
108976         sqlite3VdbeChangeP2(v, addr, nCol);
108977         sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
108978                             P4_KEYINFO);
108979         pLoop->addrOpenEphm[i] = -1;
108980       }
108981     }
108982     sqlite3KeyInfoUnref(pKeyInfo);
108983   }
108984 
108985 multi_select_end:
108986   pDest->iSdst = dest.iSdst;
108987   pDest->nSdst = dest.nSdst;
108988   sqlite3SelectDelete(db, pDelete);
108989   return rc;
108990 }
108991 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
108992 
108993 /*
108994 ** Code an output subroutine for a coroutine implementation of a
108995 ** SELECT statment.
108996 **
108997 ** The data to be output is contained in pIn->iSdst.  There are
108998 ** pIn->nSdst columns to be output.  pDest is where the output should
108999 ** be sent.
109000 **
109001 ** regReturn is the number of the register holding the subroutine
109002 ** return address.
109003 **
109004 ** If regPrev>0 then it is the first register in a vector that
109005 ** records the previous output.  mem[regPrev] is a flag that is false
109006 ** if there has been no previous output.  If regPrev>0 then code is
109007 ** generated to suppress duplicates.  pKeyInfo is used for comparing
109008 ** keys.
109009 **
109010 ** If the LIMIT found in p->iLimit is reached, jump immediately to
109011 ** iBreak.
109012 */
109013 static int generateOutputSubroutine(
109014   Parse *pParse,          /* Parsing context */
109015   Select *p,              /* The SELECT statement */
109016   SelectDest *pIn,        /* Coroutine supplying data */
109017   SelectDest *pDest,      /* Where to send the data */
109018   int regReturn,          /* The return address register */
109019   int regPrev,            /* Previous result register.  No uniqueness if 0 */
109020   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
109021   int iBreak              /* Jump here if we hit the LIMIT */
109022 ){
109023   Vdbe *v = pParse->pVdbe;
109024   int iContinue;
109025   int addr;
109026 
109027   addr = sqlite3VdbeCurrentAddr(v);
109028   iContinue = sqlite3VdbeMakeLabel(v);
109029 
109030   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
109031   */
109032   if( regPrev ){
109033     int j1, j2;
109034     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
109035     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
109036                               (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
109037     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v);
109038     sqlite3VdbeJumpHere(v, j1);
109039     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
109040     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
109041   }
109042   if( pParse->db->mallocFailed ) return 0;
109043 
109044   /* Suppress the first OFFSET entries if there is an OFFSET clause
109045   */
109046   codeOffset(v, p->iOffset, iContinue);
109047 
109048   switch( pDest->eDest ){
109049     /* Store the result as data using a unique key.
109050     */
109051     case SRT_Table:
109052     case SRT_EphemTab: {
109053       int r1 = sqlite3GetTempReg(pParse);
109054       int r2 = sqlite3GetTempReg(pParse);
109055       testcase( pDest->eDest==SRT_Table );
109056       testcase( pDest->eDest==SRT_EphemTab );
109057       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
109058       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
109059       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
109060       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
109061       sqlite3ReleaseTempReg(pParse, r2);
109062       sqlite3ReleaseTempReg(pParse, r1);
109063       break;
109064     }
109065 
109066 #ifndef SQLITE_OMIT_SUBQUERY
109067     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
109068     ** then there should be a single item on the stack.  Write this
109069     ** item into the set table with bogus data.
109070     */
109071     case SRT_Set: {
109072       int r1;
109073       assert( pIn->nSdst==1 || pParse->nErr>0 );
109074       pDest->affSdst =
109075          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
109076       r1 = sqlite3GetTempReg(pParse);
109077       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
109078       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
109079       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
109080       sqlite3ReleaseTempReg(pParse, r1);
109081       break;
109082     }
109083 
109084 #if 0  /* Never occurs on an ORDER BY query */
109085     /* If any row exist in the result set, record that fact and abort.
109086     */
109087     case SRT_Exists: {
109088       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
109089       /* The LIMIT clause will terminate the loop for us */
109090       break;
109091     }
109092 #endif
109093 
109094     /* If this is a scalar select that is part of an expression, then
109095     ** store the results in the appropriate memory cell and break out
109096     ** of the scan loop.
109097     */
109098     case SRT_Mem: {
109099       assert( pIn->nSdst==1 || pParse->nErr>0 );  testcase( pIn->nSdst!=1 );
109100       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
109101       /* The LIMIT clause will jump out of the loop for us */
109102       break;
109103     }
109104 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
109105 
109106     /* The results are stored in a sequence of registers
109107     ** starting at pDest->iSdst.  Then the co-routine yields.
109108     */
109109     case SRT_Coroutine: {
109110       if( pDest->iSdst==0 ){
109111         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
109112         pDest->nSdst = pIn->nSdst;
109113       }
109114       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
109115       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
109116       break;
109117     }
109118 
109119     /* If none of the above, then the result destination must be
109120     ** SRT_Output.  This routine is never called with any other
109121     ** destination other than the ones handled above or SRT_Output.
109122     **
109123     ** For SRT_Output, results are stored in a sequence of registers.
109124     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
109125     ** return the next row of result.
109126     */
109127     default: {
109128       assert( pDest->eDest==SRT_Output );
109129       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
109130       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
109131       break;
109132     }
109133   }
109134 
109135   /* Jump to the end of the loop if the LIMIT is reached.
109136   */
109137   if( p->iLimit ){
109138     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
109139   }
109140 
109141   /* Generate the subroutine return
109142   */
109143   sqlite3VdbeResolveLabel(v, iContinue);
109144   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
109145 
109146   return addr;
109147 }
109148 
109149 /*
109150 ** Alternative compound select code generator for cases when there
109151 ** is an ORDER BY clause.
109152 **
109153 ** We assume a query of the following form:
109154 **
109155 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
109156 **
109157 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
109158 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
109159 ** co-routines.  Then run the co-routines in parallel and merge the results
109160 ** into the output.  In addition to the two coroutines (called selectA and
109161 ** selectB) there are 7 subroutines:
109162 **
109163 **    outA:    Move the output of the selectA coroutine into the output
109164 **             of the compound query.
109165 **
109166 **    outB:    Move the output of the selectB coroutine into the output
109167 **             of the compound query.  (Only generated for UNION and
109168 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
109169 **             appears only in B.)
109170 **
109171 **    AltB:    Called when there is data from both coroutines and A<B.
109172 **
109173 **    AeqB:    Called when there is data from both coroutines and A==B.
109174 **
109175 **    AgtB:    Called when there is data from both coroutines and A>B.
109176 **
109177 **    EofA:    Called when data is exhausted from selectA.
109178 **
109179 **    EofB:    Called when data is exhausted from selectB.
109180 **
109181 ** The implementation of the latter five subroutines depend on which
109182 ** <operator> is used:
109183 **
109184 **
109185 **             UNION ALL         UNION            EXCEPT          INTERSECT
109186 **          -------------  -----------------  --------------  -----------------
109187 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
109188 **
109189 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
109190 **
109191 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
109192 **
109193 **   EofA:   outB, nextB      outB, nextB          halt             halt
109194 **
109195 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
109196 **
109197 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
109198 ** causes an immediate jump to EofA and an EOF on B following nextB causes
109199 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
109200 ** following nextX causes a jump to the end of the select processing.
109201 **
109202 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
109203 ** within the output subroutine.  The regPrev register set holds the previously
109204 ** output value.  A comparison is made against this value and the output
109205 ** is skipped if the next results would be the same as the previous.
109206 **
109207 ** The implementation plan is to implement the two coroutines and seven
109208 ** subroutines first, then put the control logic at the bottom.  Like this:
109209 **
109210 **          goto Init
109211 **     coA: coroutine for left query (A)
109212 **     coB: coroutine for right query (B)
109213 **    outA: output one row of A
109214 **    outB: output one row of B (UNION and UNION ALL only)
109215 **    EofA: ...
109216 **    EofB: ...
109217 **    AltB: ...
109218 **    AeqB: ...
109219 **    AgtB: ...
109220 **    Init: initialize coroutine registers
109221 **          yield coA
109222 **          if eof(A) goto EofA
109223 **          yield coB
109224 **          if eof(B) goto EofB
109225 **    Cmpr: Compare A, B
109226 **          Jump AltB, AeqB, AgtB
109227 **     End: ...
109228 **
109229 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
109230 ** actually called using Gosub and they do not Return.  EofA and EofB loop
109231 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
109232 ** and AgtB jump to either L2 or to one of EofA or EofB.
109233 */
109234 #ifndef SQLITE_OMIT_COMPOUND_SELECT
109235 static int multiSelectOrderBy(
109236   Parse *pParse,        /* Parsing context */
109237   Select *p,            /* The right-most of SELECTs to be coded */
109238   SelectDest *pDest     /* What to do with query results */
109239 ){
109240   int i, j;             /* Loop counters */
109241   Select *pPrior;       /* Another SELECT immediately to our left */
109242   Vdbe *v;              /* Generate code to this VDBE */
109243   SelectDest destA;     /* Destination for coroutine A */
109244   SelectDest destB;     /* Destination for coroutine B */
109245   int regAddrA;         /* Address register for select-A coroutine */
109246   int regAddrB;         /* Address register for select-B coroutine */
109247   int addrSelectA;      /* Address of the select-A coroutine */
109248   int addrSelectB;      /* Address of the select-B coroutine */
109249   int regOutA;          /* Address register for the output-A subroutine */
109250   int regOutB;          /* Address register for the output-B subroutine */
109251   int addrOutA;         /* Address of the output-A subroutine */
109252   int addrOutB = 0;     /* Address of the output-B subroutine */
109253   int addrEofA;         /* Address of the select-A-exhausted subroutine */
109254   int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
109255   int addrEofB;         /* Address of the select-B-exhausted subroutine */
109256   int addrAltB;         /* Address of the A<B subroutine */
109257   int addrAeqB;         /* Address of the A==B subroutine */
109258   int addrAgtB;         /* Address of the A>B subroutine */
109259   int regLimitA;        /* Limit register for select-A */
109260   int regLimitB;        /* Limit register for select-A */
109261   int regPrev;          /* A range of registers to hold previous output */
109262   int savedLimit;       /* Saved value of p->iLimit */
109263   int savedOffset;      /* Saved value of p->iOffset */
109264   int labelCmpr;        /* Label for the start of the merge algorithm */
109265   int labelEnd;         /* Label for the end of the overall SELECT stmt */
109266   int j1;               /* Jump instructions that get retargetted */
109267   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
109268   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
109269   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
109270   sqlite3 *db;          /* Database connection */
109271   ExprList *pOrderBy;   /* The ORDER BY clause */
109272   int nOrderBy;         /* Number of terms in the ORDER BY clause */
109273   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
109274 #ifndef SQLITE_OMIT_EXPLAIN
109275   int iSub1;            /* EQP id of left-hand query */
109276   int iSub2;            /* EQP id of right-hand query */
109277 #endif
109278 
109279   assert( p->pOrderBy!=0 );
109280   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
109281   db = pParse->db;
109282   v = pParse->pVdbe;
109283   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
109284   labelEnd = sqlite3VdbeMakeLabel(v);
109285   labelCmpr = sqlite3VdbeMakeLabel(v);
109286 
109287 
109288   /* Patch up the ORDER BY clause
109289   */
109290   op = p->op;
109291   pPrior = p->pPrior;
109292   assert( pPrior->pOrderBy==0 );
109293   pOrderBy = p->pOrderBy;
109294   assert( pOrderBy );
109295   nOrderBy = pOrderBy->nExpr;
109296 
109297   /* For operators other than UNION ALL we have to make sure that
109298   ** the ORDER BY clause covers every term of the result set.  Add
109299   ** terms to the ORDER BY clause as necessary.
109300   */
109301   if( op!=TK_ALL ){
109302     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
109303       struct ExprList_item *pItem;
109304       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
109305         assert( pItem->u.x.iOrderByCol>0 );
109306         if( pItem->u.x.iOrderByCol==i ) break;
109307       }
109308       if( j==nOrderBy ){
109309         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
109310         if( pNew==0 ) return SQLITE_NOMEM;
109311         pNew->flags |= EP_IntValue;
109312         pNew->u.iValue = i;
109313         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
109314         if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
109315       }
109316     }
109317   }
109318 
109319   /* Compute the comparison permutation and keyinfo that is used with
109320   ** the permutation used to determine if the next
109321   ** row of results comes from selectA or selectB.  Also add explicit
109322   ** collations to the ORDER BY clause terms so that when the subqueries
109323   ** to the right and the left are evaluated, they use the correct
109324   ** collation.
109325   */
109326   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
109327   if( aPermute ){
109328     struct ExprList_item *pItem;
109329     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
109330       assert( pItem->u.x.iOrderByCol>0 );
109331       /* assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr ) is also true
109332       ** but only for well-formed SELECT statements. */
109333       testcase( pItem->u.x.iOrderByCol > p->pEList->nExpr );
109334       aPermute[i] = pItem->u.x.iOrderByCol - 1;
109335     }
109336     pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
109337   }else{
109338     pKeyMerge = 0;
109339   }
109340 
109341   /* Reattach the ORDER BY clause to the query.
109342   */
109343   p->pOrderBy = pOrderBy;
109344   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
109345 
109346   /* Allocate a range of temporary registers and the KeyInfo needed
109347   ** for the logic that removes duplicate result rows when the
109348   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
109349   */
109350   if( op==TK_ALL ){
109351     regPrev = 0;
109352   }else{
109353     int nExpr = p->pEList->nExpr;
109354     assert( nOrderBy>=nExpr || db->mallocFailed );
109355     regPrev = pParse->nMem+1;
109356     pParse->nMem += nExpr+1;
109357     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
109358     pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
109359     if( pKeyDup ){
109360       assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
109361       for(i=0; i<nExpr; i++){
109362         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
109363         pKeyDup->aSortOrder[i] = 0;
109364       }
109365     }
109366   }
109367 
109368   /* Separate the left and the right query from one another
109369   */
109370   p->pPrior = 0;
109371   pPrior->pNext = 0;
109372   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
109373   if( pPrior->pPrior==0 ){
109374     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
109375   }
109376 
109377   /* Compute the limit registers */
109378   computeLimitRegisters(pParse, p, labelEnd);
109379   if( p->iLimit && op==TK_ALL ){
109380     regLimitA = ++pParse->nMem;
109381     regLimitB = ++pParse->nMem;
109382     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
109383                                   regLimitA);
109384     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
109385   }else{
109386     regLimitA = regLimitB = 0;
109387   }
109388   sqlite3ExprDelete(db, p->pLimit);
109389   p->pLimit = 0;
109390   sqlite3ExprDelete(db, p->pOffset);
109391   p->pOffset = 0;
109392 
109393   regAddrA = ++pParse->nMem;
109394   regAddrB = ++pParse->nMem;
109395   regOutA = ++pParse->nMem;
109396   regOutB = ++pParse->nMem;
109397   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
109398   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
109399 
109400   /* Generate a coroutine to evaluate the SELECT statement to the
109401   ** left of the compound operator - the "A" select.
109402   */
109403   addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
109404   j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
109405   VdbeComment((v, "left SELECT"));
109406   pPrior->iLimit = regLimitA;
109407   explainSetInteger(iSub1, pParse->iNextSelectId);
109408   sqlite3Select(pParse, pPrior, &destA);
109409   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
109410   sqlite3VdbeJumpHere(v, j1);
109411 
109412   /* Generate a coroutine to evaluate the SELECT statement on
109413   ** the right - the "B" select
109414   */
109415   addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
109416   j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
109417   VdbeComment((v, "right SELECT"));
109418   savedLimit = p->iLimit;
109419   savedOffset = p->iOffset;
109420   p->iLimit = regLimitB;
109421   p->iOffset = 0;
109422   explainSetInteger(iSub2, pParse->iNextSelectId);
109423   sqlite3Select(pParse, p, &destB);
109424   p->iLimit = savedLimit;
109425   p->iOffset = savedOffset;
109426   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
109427 
109428   /* Generate a subroutine that outputs the current row of the A
109429   ** select as the next output row of the compound select.
109430   */
109431   VdbeNoopComment((v, "Output routine for A"));
109432   addrOutA = generateOutputSubroutine(pParse,
109433                  p, &destA, pDest, regOutA,
109434                  regPrev, pKeyDup, labelEnd);
109435 
109436   /* Generate a subroutine that outputs the current row of the B
109437   ** select as the next output row of the compound select.
109438   */
109439   if( op==TK_ALL || op==TK_UNION ){
109440     VdbeNoopComment((v, "Output routine for B"));
109441     addrOutB = generateOutputSubroutine(pParse,
109442                  p, &destB, pDest, regOutB,
109443                  regPrev, pKeyDup, labelEnd);
109444   }
109445   sqlite3KeyInfoUnref(pKeyDup);
109446 
109447   /* Generate a subroutine to run when the results from select A
109448   ** are exhausted and only data in select B remains.
109449   */
109450   if( op==TK_EXCEPT || op==TK_INTERSECT ){
109451     addrEofA_noB = addrEofA = labelEnd;
109452   }else{
109453     VdbeNoopComment((v, "eof-A subroutine"));
109454     addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
109455     addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
109456                                      VdbeCoverage(v);
109457     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
109458     p->nSelectRow += pPrior->nSelectRow;
109459   }
109460 
109461   /* Generate a subroutine to run when the results from select B
109462   ** are exhausted and only data in select A remains.
109463   */
109464   if( op==TK_INTERSECT ){
109465     addrEofB = addrEofA;
109466     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
109467   }else{
109468     VdbeNoopComment((v, "eof-B subroutine"));
109469     addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
109470     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
109471     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
109472   }
109473 
109474   /* Generate code to handle the case of A<B
109475   */
109476   VdbeNoopComment((v, "A-lt-B subroutine"));
109477   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
109478   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
109479   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
109480 
109481   /* Generate code to handle the case of A==B
109482   */
109483   if( op==TK_ALL ){
109484     addrAeqB = addrAltB;
109485   }else if( op==TK_INTERSECT ){
109486     addrAeqB = addrAltB;
109487     addrAltB++;
109488   }else{
109489     VdbeNoopComment((v, "A-eq-B subroutine"));
109490     addrAeqB =
109491     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
109492     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
109493   }
109494 
109495   /* Generate code to handle the case of A>B
109496   */
109497   VdbeNoopComment((v, "A-gt-B subroutine"));
109498   addrAgtB = sqlite3VdbeCurrentAddr(v);
109499   if( op==TK_ALL || op==TK_UNION ){
109500     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
109501   }
109502   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
109503   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
109504 
109505   /* This code runs once to initialize everything.
109506   */
109507   sqlite3VdbeJumpHere(v, j1);
109508   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
109509   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
109510 
109511   /* Implement the main merge loop
109512   */
109513   sqlite3VdbeResolveLabel(v, labelCmpr);
109514   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
109515   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
109516                          (char*)pKeyMerge, P4_KEYINFO);
109517   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
109518   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
109519 
109520   /* Jump to the this point in order to terminate the query.
109521   */
109522   sqlite3VdbeResolveLabel(v, labelEnd);
109523 
109524   /* Set the number of output columns
109525   */
109526   if( pDest->eDest==SRT_Output ){
109527     Select *pFirst = pPrior;
109528     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
109529     generateColumnNames(pParse, 0, pFirst->pEList);
109530   }
109531 
109532   /* Reassembly the compound query so that it will be freed correctly
109533   ** by the calling function */
109534   if( p->pPrior ){
109535     sqlite3SelectDelete(db, p->pPrior);
109536   }
109537   p->pPrior = pPrior;
109538   pPrior->pNext = p;
109539 
109540   /*** TBD:  Insert subroutine calls to close cursors on incomplete
109541   **** subqueries ****/
109542   explainComposite(pParse, p->op, iSub1, iSub2, 0);
109543   return pParse->nErr!=0;
109544 }
109545 #endif
109546 
109547 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
109548 /* Forward Declarations */
109549 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
109550 static void substSelect(sqlite3*, Select *, int, ExprList *);
109551 
109552 /*
109553 ** Scan through the expression pExpr.  Replace every reference to
109554 ** a column in table number iTable with a copy of the iColumn-th
109555 ** entry in pEList.  (But leave references to the ROWID column
109556 ** unchanged.)
109557 **
109558 ** This routine is part of the flattening procedure.  A subquery
109559 ** whose result set is defined by pEList appears as entry in the
109560 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
109561 ** FORM clause entry is iTable.  This routine make the necessary
109562 ** changes to pExpr so that it refers directly to the source table
109563 ** of the subquery rather the result set of the subquery.
109564 */
109565 static Expr *substExpr(
109566   sqlite3 *db,        /* Report malloc errors to this connection */
109567   Expr *pExpr,        /* Expr in which substitution occurs */
109568   int iTable,         /* Table to be substituted */
109569   ExprList *pEList    /* Substitute expressions */
109570 ){
109571   if( pExpr==0 ) return 0;
109572   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
109573     if( pExpr->iColumn<0 ){
109574       pExpr->op = TK_NULL;
109575     }else{
109576       Expr *pNew;
109577       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
109578       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
109579       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
109580       sqlite3ExprDelete(db, pExpr);
109581       pExpr = pNew;
109582     }
109583   }else{
109584     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
109585     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
109586     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
109587       substSelect(db, pExpr->x.pSelect, iTable, pEList);
109588     }else{
109589       substExprList(db, pExpr->x.pList, iTable, pEList);
109590     }
109591   }
109592   return pExpr;
109593 }
109594 static void substExprList(
109595   sqlite3 *db,         /* Report malloc errors here */
109596   ExprList *pList,     /* List to scan and in which to make substitutes */
109597   int iTable,          /* Table to be substituted */
109598   ExprList *pEList     /* Substitute values */
109599 ){
109600   int i;
109601   if( pList==0 ) return;
109602   for(i=0; i<pList->nExpr; i++){
109603     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
109604   }
109605 }
109606 static void substSelect(
109607   sqlite3 *db,         /* Report malloc errors here */
109608   Select *p,           /* SELECT statement in which to make substitutions */
109609   int iTable,          /* Table to be replaced */
109610   ExprList *pEList     /* Substitute values */
109611 ){
109612   SrcList *pSrc;
109613   struct SrcList_item *pItem;
109614   int i;
109615   if( !p ) return;
109616   substExprList(db, p->pEList, iTable, pEList);
109617   substExprList(db, p->pGroupBy, iTable, pEList);
109618   substExprList(db, p->pOrderBy, iTable, pEList);
109619   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
109620   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
109621   substSelect(db, p->pPrior, iTable, pEList);
109622   pSrc = p->pSrc;
109623   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
109624   if( ALWAYS(pSrc) ){
109625     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
109626       substSelect(db, pItem->pSelect, iTable, pEList);
109627     }
109628   }
109629 }
109630 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
109631 
109632 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
109633 /*
109634 ** This routine attempts to flatten subqueries as a performance optimization.
109635 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
109636 **
109637 ** To understand the concept of flattening, consider the following
109638 ** query:
109639 **
109640 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
109641 **
109642 ** The default way of implementing this query is to execute the
109643 ** subquery first and store the results in a temporary table, then
109644 ** run the outer query on that temporary table.  This requires two
109645 ** passes over the data.  Furthermore, because the temporary table
109646 ** has no indices, the WHERE clause on the outer query cannot be
109647 ** optimized.
109648 **
109649 ** This routine attempts to rewrite queries such as the above into
109650 ** a single flat select, like this:
109651 **
109652 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
109653 **
109654 ** The code generated for this simplification gives the same result
109655 ** but only has to scan the data once.  And because indices might
109656 ** exist on the table t1, a complete scan of the data might be
109657 ** avoided.
109658 **
109659 ** Flattening is only attempted if all of the following are true:
109660 **
109661 **   (1)  The subquery and the outer query do not both use aggregates.
109662 **
109663 **   (2)  The subquery is not an aggregate or (2a) the outer query is not a join
109664 **        and (2b) the outer query does not use subqueries other than the one
109665 **        FROM-clause subquery that is a candidate for flattening.  (2b is
109666 **        due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
109667 **
109668 **   (3)  The subquery is not the right operand of a left outer join
109669 **        (Originally ticket #306.  Strengthened by ticket #3300)
109670 **
109671 **   (4)  The subquery is not DISTINCT.
109672 **
109673 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
109674 **        sub-queries that were excluded from this optimization. Restriction
109675 **        (4) has since been expanded to exclude all DISTINCT subqueries.
109676 **
109677 **   (6)  The subquery does not use aggregates or the outer query is not
109678 **        DISTINCT.
109679 **
109680 **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
109681 **        A FROM clause, consider adding a FROM close with the special
109682 **        table sqlite_once that consists of a single row containing a
109683 **        single NULL.
109684 **
109685 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
109686 **
109687 **   (9)  The subquery does not use LIMIT or the outer query does not use
109688 **        aggregates.
109689 **
109690 **  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
109691 **        accidently carried the comment forward until 2014-09-15.  Original
109692 **        text: "The subquery does not use aggregates or the outer query does not
109693 **        use LIMIT."
109694 **
109695 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
109696 **
109697 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
109698 **        a separate restriction deriving from ticket #350.
109699 **
109700 **  (13)  The subquery and outer query do not both use LIMIT.
109701 **
109702 **  (14)  The subquery does not use OFFSET.
109703 **
109704 **  (15)  The outer query is not part of a compound select or the
109705 **        subquery does not have a LIMIT clause.
109706 **        (See ticket #2339 and ticket [02a8e81d44]).
109707 **
109708 **  (16)  The outer query is not an aggregate or the subquery does
109709 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
109710 **        until we introduced the group_concat() function.
109711 **
109712 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
109713 **        compound clause made up entirely of non-aggregate queries, and
109714 **        the parent query:
109715 **
109716 **          * is not itself part of a compound select,
109717 **          * is not an aggregate or DISTINCT query, and
109718 **          * is not a join
109719 **
109720 **        The parent and sub-query may contain WHERE clauses. Subject to
109721 **        rules (11), (13) and (14), they may also contain ORDER BY,
109722 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
109723 **        operator other than UNION ALL because all the other compound
109724 **        operators have an implied DISTINCT which is disallowed by
109725 **        restriction (4).
109726 **
109727 **        Also, each component of the sub-query must return the same number
109728 **        of result columns. This is actually a requirement for any compound
109729 **        SELECT statement, but all the code here does is make sure that no
109730 **        such (illegal) sub-query is flattened. The caller will detect the
109731 **        syntax error and return a detailed message.
109732 **
109733 **  (18)  If the sub-query is a compound select, then all terms of the
109734 **        ORDER by clause of the parent must be simple references to
109735 **        columns of the sub-query.
109736 **
109737 **  (19)  The subquery does not use LIMIT or the outer query does not
109738 **        have a WHERE clause.
109739 **
109740 **  (20)  If the sub-query is a compound select, then it must not use
109741 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
109742 **        somewhat by saying that the terms of the ORDER BY clause must
109743 **        appear as unmodified result columns in the outer query.  But we
109744 **        have other optimizations in mind to deal with that case.
109745 **
109746 **  (21)  The subquery does not use LIMIT or the outer query is not
109747 **        DISTINCT.  (See ticket [752e1646fc]).
109748 **
109749 **  (22)  The subquery is not a recursive CTE.
109750 **
109751 **  (23)  The parent is not a recursive CTE, or the sub-query is not a
109752 **        compound query. This restriction is because transforming the
109753 **        parent to a compound query confuses the code that handles
109754 **        recursive queries in multiSelect().
109755 **
109756 **  (24)  The subquery is not an aggregate that uses the built-in min() or
109757 **        or max() functions.  (Without this restriction, a query like:
109758 **        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
109759 **        return the value X for which Y was maximal.)
109760 **
109761 **
109762 ** In this routine, the "p" parameter is a pointer to the outer query.
109763 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
109764 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
109765 **
109766 ** If flattening is not attempted, this routine is a no-op and returns 0.
109767 ** If flattening is attempted this routine returns 1.
109768 **
109769 ** All of the expression analysis must occur on both the outer query and
109770 ** the subquery before this routine runs.
109771 */
109772 static int flattenSubquery(
109773   Parse *pParse,       /* Parsing context */
109774   Select *p,           /* The parent or outer SELECT statement */
109775   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
109776   int isAgg,           /* True if outer SELECT uses aggregate functions */
109777   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
109778 ){
109779   const char *zSavedAuthContext = pParse->zAuthContext;
109780   Select *pParent;
109781   Select *pSub;       /* The inner query or "subquery" */
109782   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
109783   SrcList *pSrc;      /* The FROM clause of the outer query */
109784   SrcList *pSubSrc;   /* The FROM clause of the subquery */
109785   ExprList *pList;    /* The result set of the outer query */
109786   int iParent;        /* VDBE cursor number of the pSub result set temp table */
109787   int i;              /* Loop counter */
109788   Expr *pWhere;                    /* The WHERE clause */
109789   struct SrcList_item *pSubitem;   /* The subquery */
109790   sqlite3 *db = pParse->db;
109791 
109792   /* Check to see if flattening is permitted.  Return 0 if not.
109793   */
109794   assert( p!=0 );
109795   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
109796   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
109797   pSrc = p->pSrc;
109798   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
109799   pSubitem = &pSrc->a[iFrom];
109800   iParent = pSubitem->iCursor;
109801   pSub = pSubitem->pSelect;
109802   assert( pSub!=0 );
109803   if( subqueryIsAgg ){
109804     if( isAgg ) return 0;                                /* Restriction (1)   */
109805     if( pSrc->nSrc>1 ) return 0;                         /* Restriction (2a)  */
109806     if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
109807      || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
109808      || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
109809     ){
109810       return 0;                                          /* Restriction (2b)  */
109811     }
109812   }
109813 
109814   pSubSrc = pSub->pSrc;
109815   assert( pSubSrc );
109816   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
109817   ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
109818   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
109819   ** became arbitrary expressions, we were forced to add restrictions (13)
109820   ** and (14). */
109821   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
109822   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
109823   if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
109824     return 0;                                            /* Restriction (15) */
109825   }
109826   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
109827   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
109828   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
109829      return 0;         /* Restrictions (8)(9) */
109830   }
109831   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
109832      return 0;         /* Restriction (6)  */
109833   }
109834   if( p->pOrderBy && pSub->pOrderBy ){
109835      return 0;                                           /* Restriction (11) */
109836   }
109837   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
109838   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
109839   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
109840      return 0;         /* Restriction (21) */
109841   }
109842   testcase( pSub->selFlags & SF_Recursive );
109843   testcase( pSub->selFlags & SF_MinMaxAgg );
109844   if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
109845     return 0; /* Restrictions (22) and (24) */
109846   }
109847   if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
109848     return 0; /* Restriction (23) */
109849   }
109850 
109851   /* OBSOLETE COMMENT 1:
109852   ** Restriction 3:  If the subquery is a join, make sure the subquery is
109853   ** not used as the right operand of an outer join.  Examples of why this
109854   ** is not allowed:
109855   **
109856   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
109857   **
109858   ** If we flatten the above, we would get
109859   **
109860   **         (t1 LEFT OUTER JOIN t2) JOIN t3
109861   **
109862   ** which is not at all the same thing.
109863   **
109864   ** OBSOLETE COMMENT 2:
109865   ** Restriction 12:  If the subquery is the right operand of a left outer
109866   ** join, make sure the subquery has no WHERE clause.
109867   ** An examples of why this is not allowed:
109868   **
109869   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
109870   **
109871   ** If we flatten the above, we would get
109872   **
109873   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
109874   **
109875   ** But the t2.x>0 test will always fail on a NULL row of t2, which
109876   ** effectively converts the OUTER JOIN into an INNER JOIN.
109877   **
109878   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
109879   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
109880   ** is fraught with danger.  Best to avoid the whole thing.  If the
109881   ** subquery is the right term of a LEFT JOIN, then do not flatten.
109882   */
109883   if( (pSubitem->jointype & JT_OUTER)!=0 ){
109884     return 0;
109885   }
109886 
109887   /* Restriction 17: If the sub-query is a compound SELECT, then it must
109888   ** use only the UNION ALL operator. And none of the simple select queries
109889   ** that make up the compound SELECT are allowed to be aggregate or distinct
109890   ** queries.
109891   */
109892   if( pSub->pPrior ){
109893     if( pSub->pOrderBy ){
109894       return 0;  /* Restriction 20 */
109895     }
109896     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
109897       return 0;
109898     }
109899     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
109900       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
109901       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
109902       assert( pSub->pSrc!=0 );
109903       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
109904        || (pSub1->pPrior && pSub1->op!=TK_ALL)
109905        || pSub1->pSrc->nSrc<1
109906        || pSub->pEList->nExpr!=pSub1->pEList->nExpr
109907       ){
109908         return 0;
109909       }
109910       testcase( pSub1->pSrc->nSrc>1 );
109911     }
109912 
109913     /* Restriction 18. */
109914     if( p->pOrderBy ){
109915       int ii;
109916       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
109917         if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
109918       }
109919     }
109920   }
109921 
109922   /***** If we reach this point, flattening is permitted. *****/
109923   SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
109924                    pSub->zSelName, pSub, iFrom));
109925 
109926   /* Authorize the subquery */
109927   pParse->zAuthContext = pSubitem->zName;
109928   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
109929   testcase( i==SQLITE_DENY );
109930   pParse->zAuthContext = zSavedAuthContext;
109931 
109932   /* If the sub-query is a compound SELECT statement, then (by restrictions
109933   ** 17 and 18 above) it must be a UNION ALL and the parent query must
109934   ** be of the form:
109935   **
109936   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
109937   **
109938   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
109939   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
109940   ** OFFSET clauses and joins them to the left-hand-side of the original
109941   ** using UNION ALL operators. In this case N is the number of simple
109942   ** select statements in the compound sub-query.
109943   **
109944   ** Example:
109945   **
109946   **     SELECT a+1 FROM (
109947   **        SELECT x FROM tab
109948   **        UNION ALL
109949   **        SELECT y FROM tab
109950   **        UNION ALL
109951   **        SELECT abs(z*2) FROM tab2
109952   **     ) WHERE a!=5 ORDER BY 1
109953   **
109954   ** Transformed into:
109955   **
109956   **     SELECT x+1 FROM tab WHERE x+1!=5
109957   **     UNION ALL
109958   **     SELECT y+1 FROM tab WHERE y+1!=5
109959   **     UNION ALL
109960   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
109961   **     ORDER BY 1
109962   **
109963   ** We call this the "compound-subquery flattening".
109964   */
109965   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
109966     Select *pNew;
109967     ExprList *pOrderBy = p->pOrderBy;
109968     Expr *pLimit = p->pLimit;
109969     Expr *pOffset = p->pOffset;
109970     Select *pPrior = p->pPrior;
109971     p->pOrderBy = 0;
109972     p->pSrc = 0;
109973     p->pPrior = 0;
109974     p->pLimit = 0;
109975     p->pOffset = 0;
109976     pNew = sqlite3SelectDup(db, p, 0);
109977     sqlite3SelectSetName(pNew, pSub->zSelName);
109978     p->pOffset = pOffset;
109979     p->pLimit = pLimit;
109980     p->pOrderBy = pOrderBy;
109981     p->pSrc = pSrc;
109982     p->op = TK_ALL;
109983     if( pNew==0 ){
109984       p->pPrior = pPrior;
109985     }else{
109986       pNew->pPrior = pPrior;
109987       if( pPrior ) pPrior->pNext = pNew;
109988       pNew->pNext = p;
109989       p->pPrior = pNew;
109990       SELECTTRACE(2,pParse,p,
109991          ("compound-subquery flattener creates %s.%p as peer\n",
109992          pNew->zSelName, pNew));
109993     }
109994     if( db->mallocFailed ) return 1;
109995   }
109996 
109997   /* Begin flattening the iFrom-th entry of the FROM clause
109998   ** in the outer query.
109999   */
110000   pSub = pSub1 = pSubitem->pSelect;
110001 
110002   /* Delete the transient table structure associated with the
110003   ** subquery
110004   */
110005   sqlite3DbFree(db, pSubitem->zDatabase);
110006   sqlite3DbFree(db, pSubitem->zName);
110007   sqlite3DbFree(db, pSubitem->zAlias);
110008   pSubitem->zDatabase = 0;
110009   pSubitem->zName = 0;
110010   pSubitem->zAlias = 0;
110011   pSubitem->pSelect = 0;
110012 
110013   /* Defer deleting the Table object associated with the
110014   ** subquery until code generation is
110015   ** complete, since there may still exist Expr.pTab entries that
110016   ** refer to the subquery even after flattening.  Ticket #3346.
110017   **
110018   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
110019   */
110020   if( ALWAYS(pSubitem->pTab!=0) ){
110021     Table *pTabToDel = pSubitem->pTab;
110022     if( pTabToDel->nRef==1 ){
110023       Parse *pToplevel = sqlite3ParseToplevel(pParse);
110024       pTabToDel->pNextZombie = pToplevel->pZombieTab;
110025       pToplevel->pZombieTab = pTabToDel;
110026     }else{
110027       pTabToDel->nRef--;
110028     }
110029     pSubitem->pTab = 0;
110030   }
110031 
110032   /* The following loop runs once for each term in a compound-subquery
110033   ** flattening (as described above).  If we are doing a different kind
110034   ** of flattening - a flattening other than a compound-subquery flattening -
110035   ** then this loop only runs once.
110036   **
110037   ** This loop moves all of the FROM elements of the subquery into the
110038   ** the FROM clause of the outer query.  Before doing this, remember
110039   ** the cursor number for the original outer query FROM element in
110040   ** iParent.  The iParent cursor will never be used.  Subsequent code
110041   ** will scan expressions looking for iParent references and replace
110042   ** those references with expressions that resolve to the subquery FROM
110043   ** elements we are now copying in.
110044   */
110045   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
110046     int nSubSrc;
110047     u8 jointype = 0;
110048     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
110049     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
110050     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
110051 
110052     if( pSrc ){
110053       assert( pParent==p );  /* First time through the loop */
110054       jointype = pSubitem->jointype;
110055     }else{
110056       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
110057       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
110058       if( pSrc==0 ){
110059         assert( db->mallocFailed );
110060         break;
110061       }
110062     }
110063 
110064     /* The subquery uses a single slot of the FROM clause of the outer
110065     ** query.  If the subquery has more than one element in its FROM clause,
110066     ** then expand the outer query to make space for it to hold all elements
110067     ** of the subquery.
110068     **
110069     ** Example:
110070     **
110071     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
110072     **
110073     ** The outer query has 3 slots in its FROM clause.  One slot of the
110074     ** outer query (the middle slot) is used by the subquery.  The next
110075     ** block of code will expand the out query to 4 slots.  The middle
110076     ** slot is expanded to two slots in order to make space for the
110077     ** two elements in the FROM clause of the subquery.
110078     */
110079     if( nSubSrc>1 ){
110080       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
110081       if( db->mallocFailed ){
110082         break;
110083       }
110084     }
110085 
110086     /* Transfer the FROM clause terms from the subquery into the
110087     ** outer query.
110088     */
110089     for(i=0; i<nSubSrc; i++){
110090       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
110091       pSrc->a[i+iFrom] = pSubSrc->a[i];
110092       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
110093     }
110094     pSrc->a[iFrom].jointype = jointype;
110095 
110096     /* Now begin substituting subquery result set expressions for
110097     ** references to the iParent in the outer query.
110098     **
110099     ** Example:
110100     **
110101     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
110102     **   \                     \_____________ subquery __________/          /
110103     **    \_____________________ outer query ______________________________/
110104     **
110105     ** We look at every expression in the outer query and every place we see
110106     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
110107     */
110108     pList = pParent->pEList;
110109     for(i=0; i<pList->nExpr; i++){
110110       if( pList->a[i].zName==0 ){
110111         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
110112         sqlite3Dequote(zName);
110113         pList->a[i].zName = zName;
110114       }
110115     }
110116     substExprList(db, pParent->pEList, iParent, pSub->pEList);
110117     if( isAgg ){
110118       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
110119       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
110120     }
110121     if( pSub->pOrderBy ){
110122       /* At this point, any non-zero iOrderByCol values indicate that the
110123       ** ORDER BY column expression is identical to the iOrderByCol'th
110124       ** expression returned by SELECT statement pSub. Since these values
110125       ** do not necessarily correspond to columns in SELECT statement pParent,
110126       ** zero them before transfering the ORDER BY clause.
110127       **
110128       ** Not doing this may cause an error if a subsequent call to this
110129       ** function attempts to flatten a compound sub-query into pParent
110130       ** (the only way this can happen is if the compound sub-query is
110131       ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
110132       ExprList *pOrderBy = pSub->pOrderBy;
110133       for(i=0; i<pOrderBy->nExpr; i++){
110134         pOrderBy->a[i].u.x.iOrderByCol = 0;
110135       }
110136       assert( pParent->pOrderBy==0 );
110137       assert( pSub->pPrior==0 );
110138       pParent->pOrderBy = pOrderBy;
110139       pSub->pOrderBy = 0;
110140     }else if( pParent->pOrderBy ){
110141       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
110142     }
110143     if( pSub->pWhere ){
110144       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
110145     }else{
110146       pWhere = 0;
110147     }
110148     if( subqueryIsAgg ){
110149       assert( pParent->pHaving==0 );
110150       pParent->pHaving = pParent->pWhere;
110151       pParent->pWhere = pWhere;
110152       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
110153       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
110154                                   sqlite3ExprDup(db, pSub->pHaving, 0));
110155       assert( pParent->pGroupBy==0 );
110156       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
110157     }else{
110158       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
110159       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
110160     }
110161 
110162     /* The flattened query is distinct if either the inner or the
110163     ** outer query is distinct.
110164     */
110165     pParent->selFlags |= pSub->selFlags & SF_Distinct;
110166 
110167     /*
110168     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
110169     **
110170     ** One is tempted to try to add a and b to combine the limits.  But this
110171     ** does not work if either limit is negative.
110172     */
110173     if( pSub->pLimit ){
110174       pParent->pLimit = pSub->pLimit;
110175       pSub->pLimit = 0;
110176     }
110177   }
110178 
110179   /* Finially, delete what is left of the subquery and return
110180   ** success.
110181   */
110182   sqlite3SelectDelete(db, pSub1);
110183 
110184 #if SELECTTRACE_ENABLED
110185   if( sqlite3SelectTrace & 0x100 ){
110186     sqlite3DebugPrintf("After flattening:\n");
110187     sqlite3TreeViewSelect(0, p, 0);
110188   }
110189 #endif
110190 
110191   return 1;
110192 }
110193 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
110194 
110195 /*
110196 ** Based on the contents of the AggInfo structure indicated by the first
110197 ** argument, this function checks if the following are true:
110198 **
110199 **    * the query contains just a single aggregate function,
110200 **    * the aggregate function is either min() or max(), and
110201 **    * the argument to the aggregate function is a column value.
110202 **
110203 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
110204 ** is returned as appropriate. Also, *ppMinMax is set to point to the
110205 ** list of arguments passed to the aggregate before returning.
110206 **
110207 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
110208 ** WHERE_ORDERBY_NORMAL is returned.
110209 */
110210 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
110211   int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
110212 
110213   *ppMinMax = 0;
110214   if( pAggInfo->nFunc==1 ){
110215     Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
110216     ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
110217 
110218     assert( pExpr->op==TK_AGG_FUNCTION );
110219     if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
110220       const char *zFunc = pExpr->u.zToken;
110221       if( sqlite3StrICmp(zFunc, "min")==0 ){
110222         eRet = WHERE_ORDERBY_MIN;
110223         *ppMinMax = pEList;
110224       }else if( sqlite3StrICmp(zFunc, "max")==0 ){
110225         eRet = WHERE_ORDERBY_MAX;
110226         *ppMinMax = pEList;
110227       }
110228     }
110229   }
110230 
110231   assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
110232   return eRet;
110233 }
110234 
110235 /*
110236 ** The select statement passed as the first argument is an aggregate query.
110237 ** The second argument is the associated aggregate-info object. This
110238 ** function tests if the SELECT is of the form:
110239 **
110240 **   SELECT count(*) FROM <tbl>
110241 **
110242 ** where table is a database table, not a sub-select or view. If the query
110243 ** does match this pattern, then a pointer to the Table object representing
110244 ** <tbl> is returned. Otherwise, 0 is returned.
110245 */
110246 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
110247   Table *pTab;
110248   Expr *pExpr;
110249 
110250   assert( !p->pGroupBy );
110251 
110252   if( p->pWhere || p->pEList->nExpr!=1
110253    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
110254   ){
110255     return 0;
110256   }
110257   pTab = p->pSrc->a[0].pTab;
110258   pExpr = p->pEList->a[0].pExpr;
110259   assert( pTab && !pTab->pSelect && pExpr );
110260 
110261   if( IsVirtual(pTab) ) return 0;
110262   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
110263   if( NEVER(pAggInfo->nFunc==0) ) return 0;
110264   if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
110265   if( pExpr->flags&EP_Distinct ) return 0;
110266 
110267   return pTab;
110268 }
110269 
110270 /*
110271 ** If the source-list item passed as an argument was augmented with an
110272 ** INDEXED BY clause, then try to locate the specified index. If there
110273 ** was such a clause and the named index cannot be found, return
110274 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
110275 ** pFrom->pIndex and return SQLITE_OK.
110276 */
110277 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
110278   if( pFrom->pTab && pFrom->zIndex ){
110279     Table *pTab = pFrom->pTab;
110280     char *zIndex = pFrom->zIndex;
110281     Index *pIdx;
110282     for(pIdx=pTab->pIndex;
110283         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
110284         pIdx=pIdx->pNext
110285     );
110286     if( !pIdx ){
110287       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
110288       pParse->checkSchema = 1;
110289       return SQLITE_ERROR;
110290     }
110291     pFrom->pIndex = pIdx;
110292   }
110293   return SQLITE_OK;
110294 }
110295 /*
110296 ** Detect compound SELECT statements that use an ORDER BY clause with
110297 ** an alternative collating sequence.
110298 **
110299 **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
110300 **
110301 ** These are rewritten as a subquery:
110302 **
110303 **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
110304 **     ORDER BY ... COLLATE ...
110305 **
110306 ** This transformation is necessary because the multiSelectOrderBy() routine
110307 ** above that generates the code for a compound SELECT with an ORDER BY clause
110308 ** uses a merge algorithm that requires the same collating sequence on the
110309 ** result columns as on the ORDER BY clause.  See ticket
110310 ** http://www.sqlite.org/src/info/6709574d2a
110311 **
110312 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
110313 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
110314 ** there are COLLATE terms in the ORDER BY.
110315 */
110316 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
110317   int i;
110318   Select *pNew;
110319   Select *pX;
110320   sqlite3 *db;
110321   struct ExprList_item *a;
110322   SrcList *pNewSrc;
110323   Parse *pParse;
110324   Token dummy;
110325 
110326   if( p->pPrior==0 ) return WRC_Continue;
110327   if( p->pOrderBy==0 ) return WRC_Continue;
110328   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
110329   if( pX==0 ) return WRC_Continue;
110330   a = p->pOrderBy->a;
110331   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
110332     if( a[i].pExpr->flags & EP_Collate ) break;
110333   }
110334   if( i<0 ) return WRC_Continue;
110335 
110336   /* If we reach this point, that means the transformation is required. */
110337 
110338   pParse = pWalker->pParse;
110339   db = pParse->db;
110340   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
110341   if( pNew==0 ) return WRC_Abort;
110342   memset(&dummy, 0, sizeof(dummy));
110343   pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
110344   if( pNewSrc==0 ) return WRC_Abort;
110345   *pNew = *p;
110346   p->pSrc = pNewSrc;
110347   p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
110348   p->op = TK_SELECT;
110349   p->pWhere = 0;
110350   pNew->pGroupBy = 0;
110351   pNew->pHaving = 0;
110352   pNew->pOrderBy = 0;
110353   p->pPrior = 0;
110354   p->pNext = 0;
110355   p->pWith = 0;
110356   p->selFlags &= ~SF_Compound;
110357   assert( (p->selFlags & SF_Converted)==0 );
110358   p->selFlags |= SF_Converted;
110359   assert( pNew->pPrior!=0 );
110360   pNew->pPrior->pNext = pNew;
110361   pNew->pLimit = 0;
110362   pNew->pOffset = 0;
110363   return WRC_Continue;
110364 }
110365 
110366 #ifndef SQLITE_OMIT_CTE
110367 /*
110368 ** Argument pWith (which may be NULL) points to a linked list of nested
110369 ** WITH contexts, from inner to outermost. If the table identified by
110370 ** FROM clause element pItem is really a common-table-expression (CTE)
110371 ** then return a pointer to the CTE definition for that table. Otherwise
110372 ** return NULL.
110373 **
110374 ** If a non-NULL value is returned, set *ppContext to point to the With
110375 ** object that the returned CTE belongs to.
110376 */
110377 static struct Cte *searchWith(
110378   With *pWith,                    /* Current outermost WITH clause */
110379   struct SrcList_item *pItem,     /* FROM clause element to resolve */
110380   With **ppContext                /* OUT: WITH clause return value belongs to */
110381 ){
110382   const char *zName;
110383   if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
110384     With *p;
110385     for(p=pWith; p; p=p->pOuter){
110386       int i;
110387       for(i=0; i<p->nCte; i++){
110388         if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
110389           *ppContext = p;
110390           return &p->a[i];
110391         }
110392       }
110393     }
110394   }
110395   return 0;
110396 }
110397 
110398 /* The code generator maintains a stack of active WITH clauses
110399 ** with the inner-most WITH clause being at the top of the stack.
110400 **
110401 ** This routine pushes the WITH clause passed as the second argument
110402 ** onto the top of the stack. If argument bFree is true, then this
110403 ** WITH clause will never be popped from the stack. In this case it
110404 ** should be freed along with the Parse object. In other cases, when
110405 ** bFree==0, the With object will be freed along with the SELECT
110406 ** statement with which it is associated.
110407 */
110408 SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
110409   assert( bFree==0 || pParse->pWith==0 );
110410   if( pWith ){
110411     pWith->pOuter = pParse->pWith;
110412     pParse->pWith = pWith;
110413     pParse->bFreeWith = bFree;
110414   }
110415 }
110416 
110417 /*
110418 ** This function checks if argument pFrom refers to a CTE declared by
110419 ** a WITH clause on the stack currently maintained by the parser. And,
110420 ** if currently processing a CTE expression, if it is a recursive
110421 ** reference to the current CTE.
110422 **
110423 ** If pFrom falls into either of the two categories above, pFrom->pTab
110424 ** and other fields are populated accordingly. The caller should check
110425 ** (pFrom->pTab!=0) to determine whether or not a successful match
110426 ** was found.
110427 **
110428 ** Whether or not a match is found, SQLITE_OK is returned if no error
110429 ** occurs. If an error does occur, an error message is stored in the
110430 ** parser and some error code other than SQLITE_OK returned.
110431 */
110432 static int withExpand(
110433   Walker *pWalker,
110434   struct SrcList_item *pFrom
110435 ){
110436   Parse *pParse = pWalker->pParse;
110437   sqlite3 *db = pParse->db;
110438   struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
110439   With *pWith;                    /* WITH clause that pCte belongs to */
110440 
110441   assert( pFrom->pTab==0 );
110442 
110443   pCte = searchWith(pParse->pWith, pFrom, &pWith);
110444   if( pCte ){
110445     Table *pTab;
110446     ExprList *pEList;
110447     Select *pSel;
110448     Select *pLeft;                /* Left-most SELECT statement */
110449     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
110450     With *pSavedWith;             /* Initial value of pParse->pWith */
110451 
110452     /* If pCte->zErr is non-NULL at this point, then this is an illegal
110453     ** recursive reference to CTE pCte. Leave an error in pParse and return
110454     ** early. If pCte->zErr is NULL, then this is not a recursive reference.
110455     ** In this case, proceed.  */
110456     if( pCte->zErr ){
110457       sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
110458       return SQLITE_ERROR;
110459     }
110460 
110461     assert( pFrom->pTab==0 );
110462     pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
110463     if( pTab==0 ) return WRC_Abort;
110464     pTab->nRef = 1;
110465     pTab->zName = sqlite3DbStrDup(db, pCte->zName);
110466     pTab->iPKey = -1;
110467     pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
110468     pTab->tabFlags |= TF_Ephemeral;
110469     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
110470     if( db->mallocFailed ) return SQLITE_NOMEM;
110471     assert( pFrom->pSelect );
110472 
110473     /* Check if this is a recursive CTE. */
110474     pSel = pFrom->pSelect;
110475     bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
110476     if( bMayRecursive ){
110477       int i;
110478       SrcList *pSrc = pFrom->pSelect->pSrc;
110479       for(i=0; i<pSrc->nSrc; i++){
110480         struct SrcList_item *pItem = &pSrc->a[i];
110481         if( pItem->zDatabase==0
110482          && pItem->zName!=0
110483          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
110484           ){
110485           pItem->pTab = pTab;
110486           pItem->isRecursive = 1;
110487           pTab->nRef++;
110488           pSel->selFlags |= SF_Recursive;
110489         }
110490       }
110491     }
110492 
110493     /* Only one recursive reference is permitted. */
110494     if( pTab->nRef>2 ){
110495       sqlite3ErrorMsg(
110496           pParse, "multiple references to recursive table: %s", pCte->zName
110497       );
110498       return SQLITE_ERROR;
110499     }
110500     assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
110501 
110502     pCte->zErr = "circular reference: %s";
110503     pSavedWith = pParse->pWith;
110504     pParse->pWith = pWith;
110505     sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
110506 
110507     for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
110508     pEList = pLeft->pEList;
110509     if( pCte->pCols ){
110510       if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
110511         sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
110512             pCte->zName, pEList->nExpr, pCte->pCols->nExpr
110513         );
110514         pParse->pWith = pSavedWith;
110515         return SQLITE_ERROR;
110516       }
110517       pEList = pCte->pCols;
110518     }
110519 
110520     selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
110521     if( bMayRecursive ){
110522       if( pSel->selFlags & SF_Recursive ){
110523         pCte->zErr = "multiple recursive references: %s";
110524       }else{
110525         pCte->zErr = "recursive reference in a subquery: %s";
110526       }
110527       sqlite3WalkSelect(pWalker, pSel);
110528     }
110529     pCte->zErr = 0;
110530     pParse->pWith = pSavedWith;
110531   }
110532 
110533   return SQLITE_OK;
110534 }
110535 #endif
110536 
110537 #ifndef SQLITE_OMIT_CTE
110538 /*
110539 ** If the SELECT passed as the second argument has an associated WITH
110540 ** clause, pop it from the stack stored as part of the Parse object.
110541 **
110542 ** This function is used as the xSelectCallback2() callback by
110543 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
110544 ** names and other FROM clause elements.
110545 */
110546 static void selectPopWith(Walker *pWalker, Select *p){
110547   Parse *pParse = pWalker->pParse;
110548   With *pWith = findRightmost(p)->pWith;
110549   if( pWith!=0 ){
110550     assert( pParse->pWith==pWith );
110551     pParse->pWith = pWith->pOuter;
110552   }
110553 }
110554 #else
110555 #define selectPopWith 0
110556 #endif
110557 
110558 /*
110559 ** This routine is a Walker callback for "expanding" a SELECT statement.
110560 ** "Expanding" means to do the following:
110561 **
110562 **    (1)  Make sure VDBE cursor numbers have been assigned to every
110563 **         element of the FROM clause.
110564 **
110565 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
110566 **         defines FROM clause.  When views appear in the FROM clause,
110567 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
110568 **         that implements the view.  A copy is made of the view's SELECT
110569 **         statement so that we can freely modify or delete that statement
110570 **         without worrying about messing up the persistent representation
110571 **         of the view.
110572 **
110573 **    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
110574 **         on joins and the ON and USING clause of joins.
110575 **
110576 **    (4)  Scan the list of columns in the result set (pEList) looking
110577 **         for instances of the "*" operator or the TABLE.* operator.
110578 **         If found, expand each "*" to be every column in every table
110579 **         and TABLE.* to be every column in TABLE.
110580 **
110581 */
110582 static int selectExpander(Walker *pWalker, Select *p){
110583   Parse *pParse = pWalker->pParse;
110584   int i, j, k;
110585   SrcList *pTabList;
110586   ExprList *pEList;
110587   struct SrcList_item *pFrom;
110588   sqlite3 *db = pParse->db;
110589   Expr *pE, *pRight, *pExpr;
110590   u16 selFlags = p->selFlags;
110591 
110592   p->selFlags |= SF_Expanded;
110593   if( db->mallocFailed  ){
110594     return WRC_Abort;
110595   }
110596   if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
110597     return WRC_Prune;
110598   }
110599   pTabList = p->pSrc;
110600   pEList = p->pEList;
110601   if( pWalker->xSelectCallback2==selectPopWith ){
110602     sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
110603   }
110604 
110605   /* Make sure cursor numbers have been assigned to all entries in
110606   ** the FROM clause of the SELECT statement.
110607   */
110608   sqlite3SrcListAssignCursors(pParse, pTabList);
110609 
110610   /* Look up every table named in the FROM clause of the select.  If
110611   ** an entry of the FROM clause is a subquery instead of a table or view,
110612   ** then create a transient table structure to describe the subquery.
110613   */
110614   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
110615     Table *pTab;
110616     assert( pFrom->isRecursive==0 || pFrom->pTab );
110617     if( pFrom->isRecursive ) continue;
110618     if( pFrom->pTab!=0 ){
110619       /* This statement has already been prepared.  There is no need
110620       ** to go further. */
110621       assert( i==0 );
110622 #ifndef SQLITE_OMIT_CTE
110623       selectPopWith(pWalker, p);
110624 #endif
110625       return WRC_Prune;
110626     }
110627 #ifndef SQLITE_OMIT_CTE
110628     if( withExpand(pWalker, pFrom) ) return WRC_Abort;
110629     if( pFrom->pTab ) {} else
110630 #endif
110631     if( pFrom->zName==0 ){
110632 #ifndef SQLITE_OMIT_SUBQUERY
110633       Select *pSel = pFrom->pSelect;
110634       /* A sub-query in the FROM clause of a SELECT */
110635       assert( pSel!=0 );
110636       assert( pFrom->pTab==0 );
110637       if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
110638       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
110639       if( pTab==0 ) return WRC_Abort;
110640       pTab->nRef = 1;
110641       pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
110642       while( pSel->pPrior ){ pSel = pSel->pPrior; }
110643       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
110644       pTab->iPKey = -1;
110645       pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
110646       pTab->tabFlags |= TF_Ephemeral;
110647 #endif
110648     }else{
110649       /* An ordinary table or view name in the FROM clause */
110650       assert( pFrom->pTab==0 );
110651       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
110652       if( pTab==0 ) return WRC_Abort;
110653       if( pTab->nRef==0xffff ){
110654         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
110655            pTab->zName);
110656         pFrom->pTab = 0;
110657         return WRC_Abort;
110658       }
110659       pTab->nRef++;
110660 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
110661       if( pTab->pSelect || IsVirtual(pTab) ){
110662         /* We reach here if the named table is a really a view */
110663         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
110664         assert( pFrom->pSelect==0 );
110665         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
110666         sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
110667         sqlite3WalkSelect(pWalker, pFrom->pSelect);
110668       }
110669 #endif
110670     }
110671 
110672     /* Locate the index named by the INDEXED BY clause, if any. */
110673     if( sqlite3IndexedByLookup(pParse, pFrom) ){
110674       return WRC_Abort;
110675     }
110676   }
110677 
110678   /* Process NATURAL keywords, and ON and USING clauses of joins.
110679   */
110680   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
110681     return WRC_Abort;
110682   }
110683 
110684   /* For every "*" that occurs in the column list, insert the names of
110685   ** all columns in all tables.  And for every TABLE.* insert the names
110686   ** of all columns in TABLE.  The parser inserted a special expression
110687   ** with the TK_ALL operator for each "*" that it found in the column list.
110688   ** The following code just has to locate the TK_ALL expressions and expand
110689   ** each one to the list of all columns in all tables.
110690   **
110691   ** The first loop just checks to see if there are any "*" operators
110692   ** that need expanding.
110693   */
110694   for(k=0; k<pEList->nExpr; k++){
110695     pE = pEList->a[k].pExpr;
110696     if( pE->op==TK_ALL ) break;
110697     assert( pE->op!=TK_DOT || pE->pRight!=0 );
110698     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
110699     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
110700   }
110701   if( k<pEList->nExpr ){
110702     /*
110703     ** If we get here it means the result set contains one or more "*"
110704     ** operators that need to be expanded.  Loop through each expression
110705     ** in the result set and expand them one by one.
110706     */
110707     struct ExprList_item *a = pEList->a;
110708     ExprList *pNew = 0;
110709     int flags = pParse->db->flags;
110710     int longNames = (flags & SQLITE_FullColNames)!=0
110711                       && (flags & SQLITE_ShortColNames)==0;
110712 
110713     /* When processing FROM-clause subqueries, it is always the case
110714     ** that full_column_names=OFF and short_column_names=ON.  The
110715     ** sqlite3ResultSetOfSelect() routine makes it so. */
110716     assert( (p->selFlags & SF_NestedFrom)==0
110717           || ((flags & SQLITE_FullColNames)==0 &&
110718               (flags & SQLITE_ShortColNames)!=0) );
110719 
110720     for(k=0; k<pEList->nExpr; k++){
110721       pE = a[k].pExpr;
110722       pRight = pE->pRight;
110723       assert( pE->op!=TK_DOT || pRight!=0 );
110724       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
110725         /* This particular expression does not need to be expanded.
110726         */
110727         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
110728         if( pNew ){
110729           pNew->a[pNew->nExpr-1].zName = a[k].zName;
110730           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
110731           a[k].zName = 0;
110732           a[k].zSpan = 0;
110733         }
110734         a[k].pExpr = 0;
110735       }else{
110736         /* This expression is a "*" or a "TABLE.*" and needs to be
110737         ** expanded. */
110738         int tableSeen = 0;      /* Set to 1 when TABLE matches */
110739         char *zTName = 0;       /* text of name of TABLE */
110740         if( pE->op==TK_DOT ){
110741           assert( pE->pLeft!=0 );
110742           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
110743           zTName = pE->pLeft->u.zToken;
110744         }
110745         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
110746           Table *pTab = pFrom->pTab;
110747           Select *pSub = pFrom->pSelect;
110748           char *zTabName = pFrom->zAlias;
110749           const char *zSchemaName = 0;
110750           int iDb;
110751           if( zTabName==0 ){
110752             zTabName = pTab->zName;
110753           }
110754           if( db->mallocFailed ) break;
110755           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
110756             pSub = 0;
110757             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
110758               continue;
110759             }
110760             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
110761             zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
110762           }
110763           for(j=0; j<pTab->nCol; j++){
110764             char *zName = pTab->aCol[j].zName;
110765             char *zColname;  /* The computed column name */
110766             char *zToFree;   /* Malloced string that needs to be freed */
110767             Token sColname;  /* Computed column name as a token */
110768 
110769             assert( zName );
110770             if( zTName && pSub
110771              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
110772             ){
110773               continue;
110774             }
110775 
110776             /* If a column is marked as 'hidden' (currently only possible
110777             ** for virtual tables), do not include it in the expanded
110778             ** result-set list.
110779             */
110780             if( IsHiddenColumn(&pTab->aCol[j]) ){
110781               assert(IsVirtual(pTab));
110782               continue;
110783             }
110784             tableSeen = 1;
110785 
110786             if( i>0 && zTName==0 ){
110787               if( (pFrom->jointype & JT_NATURAL)!=0
110788                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
110789               ){
110790                 /* In a NATURAL join, omit the join columns from the
110791                 ** table to the right of the join */
110792                 continue;
110793               }
110794               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
110795                 /* In a join with a USING clause, omit columns in the
110796                 ** using clause from the table on the right. */
110797                 continue;
110798               }
110799             }
110800             pRight = sqlite3Expr(db, TK_ID, zName);
110801             zColname = zName;
110802             zToFree = 0;
110803             if( longNames || pTabList->nSrc>1 ){
110804               Expr *pLeft;
110805               pLeft = sqlite3Expr(db, TK_ID, zTabName);
110806               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
110807               if( zSchemaName ){
110808                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
110809                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
110810               }
110811               if( longNames ){
110812                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
110813                 zToFree = zColname;
110814               }
110815             }else{
110816               pExpr = pRight;
110817             }
110818             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
110819             sColname.z = zColname;
110820             sColname.n = sqlite3Strlen30(zColname);
110821             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
110822             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
110823               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
110824               if( pSub ){
110825                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
110826                 testcase( pX->zSpan==0 );
110827               }else{
110828                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
110829                                            zSchemaName, zTabName, zColname);
110830                 testcase( pX->zSpan==0 );
110831               }
110832               pX->bSpanIsTab = 1;
110833             }
110834             sqlite3DbFree(db, zToFree);
110835           }
110836         }
110837         if( !tableSeen ){
110838           if( zTName ){
110839             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
110840           }else{
110841             sqlite3ErrorMsg(pParse, "no tables specified");
110842           }
110843         }
110844       }
110845     }
110846     sqlite3ExprListDelete(db, pEList);
110847     p->pEList = pNew;
110848   }
110849 #if SQLITE_MAX_COLUMN
110850   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
110851     sqlite3ErrorMsg(pParse, "too many columns in result set");
110852   }
110853 #endif
110854   return WRC_Continue;
110855 }
110856 
110857 /*
110858 ** No-op routine for the parse-tree walker.
110859 **
110860 ** When this routine is the Walker.xExprCallback then expression trees
110861 ** are walked without any actions being taken at each node.  Presumably,
110862 ** when this routine is used for Walker.xExprCallback then
110863 ** Walker.xSelectCallback is set to do something useful for every
110864 ** subquery in the parser tree.
110865 */
110866 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
110867   UNUSED_PARAMETER2(NotUsed, NotUsed2);
110868   return WRC_Continue;
110869 }
110870 
110871 /*
110872 ** This routine "expands" a SELECT statement and all of its subqueries.
110873 ** For additional information on what it means to "expand" a SELECT
110874 ** statement, see the comment on the selectExpand worker callback above.
110875 **
110876 ** Expanding a SELECT statement is the first step in processing a
110877 ** SELECT statement.  The SELECT statement must be expanded before
110878 ** name resolution is performed.
110879 **
110880 ** If anything goes wrong, an error message is written into pParse.
110881 ** The calling function can detect the problem by looking at pParse->nErr
110882 ** and/or pParse->db->mallocFailed.
110883 */
110884 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
110885   Walker w;
110886   memset(&w, 0, sizeof(w));
110887   w.xExprCallback = exprWalkNoop;
110888   w.pParse = pParse;
110889   if( pParse->hasCompound ){
110890     w.xSelectCallback = convertCompoundSelectToSubquery;
110891     sqlite3WalkSelect(&w, pSelect);
110892   }
110893   w.xSelectCallback = selectExpander;
110894   if( (pSelect->selFlags & SF_MultiValue)==0 ){
110895     w.xSelectCallback2 = selectPopWith;
110896   }
110897   sqlite3WalkSelect(&w, pSelect);
110898 }
110899 
110900 
110901 #ifndef SQLITE_OMIT_SUBQUERY
110902 /*
110903 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
110904 ** interface.
110905 **
110906 ** For each FROM-clause subquery, add Column.zType and Column.zColl
110907 ** information to the Table structure that represents the result set
110908 ** of that subquery.
110909 **
110910 ** The Table structure that represents the result set was constructed
110911 ** by selectExpander() but the type and collation information was omitted
110912 ** at that point because identifiers had not yet been resolved.  This
110913 ** routine is called after identifier resolution.
110914 */
110915 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
110916   Parse *pParse;
110917   int i;
110918   SrcList *pTabList;
110919   struct SrcList_item *pFrom;
110920 
110921   assert( p->selFlags & SF_Resolved );
110922   if( (p->selFlags & SF_HasTypeInfo)==0 ){
110923     p->selFlags |= SF_HasTypeInfo;
110924     pParse = pWalker->pParse;
110925     pTabList = p->pSrc;
110926     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
110927       Table *pTab = pFrom->pTab;
110928       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
110929         /* A sub-query in the FROM clause of a SELECT */
110930         Select *pSel = pFrom->pSelect;
110931         if( pSel ){
110932           while( pSel->pPrior ) pSel = pSel->pPrior;
110933           selectAddColumnTypeAndCollation(pParse, pTab, pSel);
110934         }
110935       }
110936     }
110937   }
110938 }
110939 #endif
110940 
110941 
110942 /*
110943 ** This routine adds datatype and collating sequence information to
110944 ** the Table structures of all FROM-clause subqueries in a
110945 ** SELECT statement.
110946 **
110947 ** Use this routine after name resolution.
110948 */
110949 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
110950 #ifndef SQLITE_OMIT_SUBQUERY
110951   Walker w;
110952   memset(&w, 0, sizeof(w));
110953   w.xSelectCallback2 = selectAddSubqueryTypeInfo;
110954   w.xExprCallback = exprWalkNoop;
110955   w.pParse = pParse;
110956   sqlite3WalkSelect(&w, pSelect);
110957 #endif
110958 }
110959 
110960 
110961 /*
110962 ** This routine sets up a SELECT statement for processing.  The
110963 ** following is accomplished:
110964 **
110965 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
110966 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
110967 **     *  ON and USING clauses are shifted into WHERE statements
110968 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
110969 **     *  Identifiers in expression are matched to tables.
110970 **
110971 ** This routine acts recursively on all subqueries within the SELECT.
110972 */
110973 SQLITE_PRIVATE void sqlite3SelectPrep(
110974   Parse *pParse,         /* The parser context */
110975   Select *p,             /* The SELECT statement being coded. */
110976   NameContext *pOuterNC  /* Name context for container */
110977 ){
110978   sqlite3 *db;
110979   if( NEVER(p==0) ) return;
110980   db = pParse->db;
110981   if( db->mallocFailed ) return;
110982   if( p->selFlags & SF_HasTypeInfo ) return;
110983   sqlite3SelectExpand(pParse, p);
110984   if( pParse->nErr || db->mallocFailed ) return;
110985   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
110986   if( pParse->nErr || db->mallocFailed ) return;
110987   sqlite3SelectAddTypeInfo(pParse, p);
110988 }
110989 
110990 /*
110991 ** Reset the aggregate accumulator.
110992 **
110993 ** The aggregate accumulator is a set of memory cells that hold
110994 ** intermediate results while calculating an aggregate.  This
110995 ** routine generates code that stores NULLs in all of those memory
110996 ** cells.
110997 */
110998 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
110999   Vdbe *v = pParse->pVdbe;
111000   int i;
111001   struct AggInfo_func *pFunc;
111002   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
111003   if( nReg==0 ) return;
111004 #ifdef SQLITE_DEBUG
111005   /* Verify that all AggInfo registers are within the range specified by
111006   ** AggInfo.mnReg..AggInfo.mxReg */
111007   assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
111008   for(i=0; i<pAggInfo->nColumn; i++){
111009     assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
111010          && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
111011   }
111012   for(i=0; i<pAggInfo->nFunc; i++){
111013     assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
111014          && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
111015   }
111016 #endif
111017   sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
111018   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
111019     if( pFunc->iDistinct>=0 ){
111020       Expr *pE = pFunc->pExpr;
111021       assert( !ExprHasProperty(pE, EP_xIsSelect) );
111022       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
111023         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
111024            "argument");
111025         pFunc->iDistinct = -1;
111026       }else{
111027         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
111028         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
111029                           (char*)pKeyInfo, P4_KEYINFO);
111030       }
111031     }
111032   }
111033 }
111034 
111035 /*
111036 ** Invoke the OP_AggFinalize opcode for every aggregate function
111037 ** in the AggInfo structure.
111038 */
111039 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
111040   Vdbe *v = pParse->pVdbe;
111041   int i;
111042   struct AggInfo_func *pF;
111043   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
111044     ExprList *pList = pF->pExpr->x.pList;
111045     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
111046     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
111047                       (void*)pF->pFunc, P4_FUNCDEF);
111048   }
111049 }
111050 
111051 /*
111052 ** Update the accumulator memory cells for an aggregate based on
111053 ** the current cursor position.
111054 */
111055 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
111056   Vdbe *v = pParse->pVdbe;
111057   int i;
111058   int regHit = 0;
111059   int addrHitTest = 0;
111060   struct AggInfo_func *pF;
111061   struct AggInfo_col *pC;
111062 
111063   pAggInfo->directMode = 1;
111064   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
111065     int nArg;
111066     int addrNext = 0;
111067     int regAgg;
111068     ExprList *pList = pF->pExpr->x.pList;
111069     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
111070     if( pList ){
111071       nArg = pList->nExpr;
111072       regAgg = sqlite3GetTempRange(pParse, nArg);
111073       sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
111074     }else{
111075       nArg = 0;
111076       regAgg = 0;
111077     }
111078     if( pF->iDistinct>=0 ){
111079       addrNext = sqlite3VdbeMakeLabel(v);
111080       testcase( nArg==0 );  /* Error condition */
111081       testcase( nArg>1 );   /* Also an error */
111082       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
111083     }
111084     if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
111085       CollSeq *pColl = 0;
111086       struct ExprList_item *pItem;
111087       int j;
111088       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
111089       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
111090         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
111091       }
111092       if( !pColl ){
111093         pColl = pParse->db->pDfltColl;
111094       }
111095       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
111096       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
111097     }
111098     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
111099                       (void*)pF->pFunc, P4_FUNCDEF);
111100     sqlite3VdbeChangeP5(v, (u8)nArg);
111101     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
111102     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
111103     if( addrNext ){
111104       sqlite3VdbeResolveLabel(v, addrNext);
111105       sqlite3ExprCacheClear(pParse);
111106     }
111107   }
111108 
111109   /* Before populating the accumulator registers, clear the column cache.
111110   ** Otherwise, if any of the required column values are already present
111111   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
111112   ** to pC->iMem. But by the time the value is used, the original register
111113   ** may have been used, invalidating the underlying buffer holding the
111114   ** text or blob value. See ticket [883034dcb5].
111115   **
111116   ** Another solution would be to change the OP_SCopy used to copy cached
111117   ** values to an OP_Copy.
111118   */
111119   if( regHit ){
111120     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
111121   }
111122   sqlite3ExprCacheClear(pParse);
111123   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
111124     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
111125   }
111126   pAggInfo->directMode = 0;
111127   sqlite3ExprCacheClear(pParse);
111128   if( addrHitTest ){
111129     sqlite3VdbeJumpHere(v, addrHitTest);
111130   }
111131 }
111132 
111133 /*
111134 ** Add a single OP_Explain instruction to the VDBE to explain a simple
111135 ** count(*) query ("SELECT count(*) FROM pTab").
111136 */
111137 #ifndef SQLITE_OMIT_EXPLAIN
111138 static void explainSimpleCount(
111139   Parse *pParse,                  /* Parse context */
111140   Table *pTab,                    /* Table being queried */
111141   Index *pIdx                     /* Index used to optimize scan, or NULL */
111142 ){
111143   if( pParse->explain==2 ){
111144     int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
111145     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
111146         pTab->zName,
111147         bCover ? " USING COVERING INDEX " : "",
111148         bCover ? pIdx->zName : ""
111149     );
111150     sqlite3VdbeAddOp4(
111151         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
111152     );
111153   }
111154 }
111155 #else
111156 # define explainSimpleCount(a,b,c)
111157 #endif
111158 
111159 /*
111160 ** Generate code for the SELECT statement given in the p argument.
111161 **
111162 ** The results are returned according to the SelectDest structure.
111163 ** See comments in sqliteInt.h for further information.
111164 **
111165 ** This routine returns the number of errors.  If any errors are
111166 ** encountered, then an appropriate error message is left in
111167 ** pParse->zErrMsg.
111168 **
111169 ** This routine does NOT free the Select structure passed in.  The
111170 ** calling function needs to do that.
111171 */
111172 SQLITE_PRIVATE int sqlite3Select(
111173   Parse *pParse,         /* The parser context */
111174   Select *p,             /* The SELECT statement being coded. */
111175   SelectDest *pDest      /* What to do with the query results */
111176 ){
111177   int i, j;              /* Loop counters */
111178   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
111179   Vdbe *v;               /* The virtual machine under construction */
111180   int isAgg;             /* True for select lists like "count(*)" */
111181   ExprList *pEList;      /* List of columns to extract. */
111182   SrcList *pTabList;     /* List of tables to select from */
111183   Expr *pWhere;          /* The WHERE clause.  May be NULL */
111184   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
111185   Expr *pHaving;         /* The HAVING clause.  May be NULL */
111186   int rc = 1;            /* Value to return from this function */
111187   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
111188   SortCtx sSort;         /* Info on how to code the ORDER BY clause */
111189   AggInfo sAggInfo;      /* Information used by aggregate queries */
111190   int iEnd;              /* Address of the end of the query */
111191   sqlite3 *db;           /* The database connection */
111192 
111193 #ifndef SQLITE_OMIT_EXPLAIN
111194   int iRestoreSelectId = pParse->iSelectId;
111195   pParse->iSelectId = pParse->iNextSelectId++;
111196 #endif
111197 
111198   db = pParse->db;
111199   if( p==0 || db->mallocFailed || pParse->nErr ){
111200     return 1;
111201   }
111202   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
111203   memset(&sAggInfo, 0, sizeof(sAggInfo));
111204 #if SELECTTRACE_ENABLED
111205   pParse->nSelectIndent++;
111206   SELECTTRACE(1,pParse,p, ("begin processing:\n"));
111207   if( sqlite3SelectTrace & 0x100 ){
111208     sqlite3TreeViewSelect(0, p, 0);
111209   }
111210 #endif
111211 
111212   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
111213   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
111214   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
111215   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
111216   if( IgnorableOrderby(pDest) ){
111217     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
111218            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
111219            pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
111220            pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
111221     /* If ORDER BY makes no difference in the output then neither does
111222     ** DISTINCT so it can be removed too. */
111223     sqlite3ExprListDelete(db, p->pOrderBy);
111224     p->pOrderBy = 0;
111225     p->selFlags &= ~SF_Distinct;
111226   }
111227   sqlite3SelectPrep(pParse, p, 0);
111228   memset(&sSort, 0, sizeof(sSort));
111229   sSort.pOrderBy = p->pOrderBy;
111230   pTabList = p->pSrc;
111231   pEList = p->pEList;
111232   if( pParse->nErr || db->mallocFailed ){
111233     goto select_end;
111234   }
111235   isAgg = (p->selFlags & SF_Aggregate)!=0;
111236   assert( pEList!=0 );
111237 #if SELECTTRACE_ENABLED
111238   if( sqlite3SelectTrace & 0x100 ){
111239     SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
111240     sqlite3TreeViewSelect(0, p, 0);
111241   }
111242 #endif
111243 
111244 
111245   /* Begin generating code.
111246   */
111247   v = sqlite3GetVdbe(pParse);
111248   if( v==0 ) goto select_end;
111249 
111250   /* If writing to memory or generating a set
111251   ** only a single column may be output.
111252   */
111253 #ifndef SQLITE_OMIT_SUBQUERY
111254   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
111255     goto select_end;
111256   }
111257 #endif
111258 
111259   /* Generate code for all sub-queries in the FROM clause
111260   */
111261 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
111262   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
111263     struct SrcList_item *pItem = &pTabList->a[i];
111264     SelectDest dest;
111265     Select *pSub = pItem->pSelect;
111266     int isAggSub;
111267 
111268     if( pSub==0 ) continue;
111269 
111270     /* Sometimes the code for a subquery will be generated more than
111271     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
111272     ** for example.  In that case, do not regenerate the code to manifest
111273     ** a view or the co-routine to implement a view.  The first instance
111274     ** is sufficient, though the subroutine to manifest the view does need
111275     ** to be invoked again. */
111276     if( pItem->addrFillSub ){
111277       if( pItem->viaCoroutine==0 ){
111278         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
111279       }
111280       continue;
111281     }
111282 
111283     /* Increment Parse.nHeight by the height of the largest expression
111284     ** tree referred to by this, the parent select. The child select
111285     ** may contain expression trees of at most
111286     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
111287     ** more conservative than necessary, but much easier than enforcing
111288     ** an exact limit.
111289     */
111290     pParse->nHeight += sqlite3SelectExprHeight(p);
111291 
111292     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
111293     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
111294       /* This subquery can be absorbed into its parent. */
111295       if( isAggSub ){
111296         isAgg = 1;
111297         p->selFlags |= SF_Aggregate;
111298       }
111299       i = -1;
111300     }else if( pTabList->nSrc==1
111301            && OptimizationEnabled(db, SQLITE_SubqCoroutine)
111302     ){
111303       /* Implement a co-routine that will return a single row of the result
111304       ** set on each invocation.
111305       */
111306       int addrTop = sqlite3VdbeCurrentAddr(v)+1;
111307       pItem->regReturn = ++pParse->nMem;
111308       sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
111309       VdbeComment((v, "%s", pItem->pTab->zName));
111310       pItem->addrFillSub = addrTop;
111311       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
111312       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
111313       sqlite3Select(pParse, pSub, &dest);
111314       pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
111315       pItem->viaCoroutine = 1;
111316       pItem->regResult = dest.iSdst;
111317       sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
111318       sqlite3VdbeJumpHere(v, addrTop-1);
111319       sqlite3ClearTempRegCache(pParse);
111320     }else{
111321       /* Generate a subroutine that will fill an ephemeral table with
111322       ** the content of this subquery.  pItem->addrFillSub will point
111323       ** to the address of the generated subroutine.  pItem->regReturn
111324       ** is a register allocated to hold the subroutine return address
111325       */
111326       int topAddr;
111327       int onceAddr = 0;
111328       int retAddr;
111329       assert( pItem->addrFillSub==0 );
111330       pItem->regReturn = ++pParse->nMem;
111331       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
111332       pItem->addrFillSub = topAddr+1;
111333       if( pItem->isCorrelated==0 ){
111334         /* If the subquery is not correlated and if we are not inside of
111335         ** a trigger, then we only need to compute the value of the subquery
111336         ** once. */
111337         onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
111338         VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
111339       }else{
111340         VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
111341       }
111342       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
111343       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
111344       sqlite3Select(pParse, pSub, &dest);
111345       pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
111346       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
111347       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
111348       VdbeComment((v, "end %s", pItem->pTab->zName));
111349       sqlite3VdbeChangeP1(v, topAddr, retAddr);
111350       sqlite3ClearTempRegCache(pParse);
111351     }
111352     if( /*pParse->nErr ||*/ db->mallocFailed ){
111353       goto select_end;
111354     }
111355     pParse->nHeight -= sqlite3SelectExprHeight(p);
111356     pTabList = p->pSrc;
111357     if( !IgnorableOrderby(pDest) ){
111358       sSort.pOrderBy = p->pOrderBy;
111359     }
111360   }
111361   pEList = p->pEList;
111362 #endif
111363   pWhere = p->pWhere;
111364   pGroupBy = p->pGroupBy;
111365   pHaving = p->pHaving;
111366   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
111367 
111368 #ifndef SQLITE_OMIT_COMPOUND_SELECT
111369   /* If there is are a sequence of queries, do the earlier ones first.
111370   */
111371   if( p->pPrior ){
111372     rc = multiSelect(pParse, p, pDest);
111373     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
111374 #if SELECTTRACE_ENABLED
111375     SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
111376     pParse->nSelectIndent--;
111377 #endif
111378     return rc;
111379   }
111380 #endif
111381 
111382   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
111383   ** if the select-list is the same as the ORDER BY list, then this query
111384   ** can be rewritten as a GROUP BY. In other words, this:
111385   **
111386   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
111387   **
111388   ** is transformed to:
111389   **
111390   **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
111391   **
111392   ** The second form is preferred as a single index (or temp-table) may be
111393   ** used for both the ORDER BY and DISTINCT processing. As originally
111394   ** written the query must use a temp-table for at least one of the ORDER
111395   ** BY and DISTINCT, and an index or separate temp-table for the other.
111396   */
111397   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
111398    && sqlite3ExprListCompare(sSort.pOrderBy, p->pEList, -1)==0
111399   ){
111400     p->selFlags &= ~SF_Distinct;
111401     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
111402     pGroupBy = p->pGroupBy;
111403     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
111404     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
111405     ** original setting of the SF_Distinct flag, not the current setting */
111406     assert( sDistinct.isTnct );
111407   }
111408 
111409   /* If there is an ORDER BY clause, then this sorting
111410   ** index might end up being unused if the data can be
111411   ** extracted in pre-sorted order.  If that is the case, then the
111412   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
111413   ** we figure out that the sorting index is not needed.  The addrSortIndex
111414   ** variable is used to facilitate that change.
111415   */
111416   if( sSort.pOrderBy ){
111417     KeyInfo *pKeyInfo;
111418     pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
111419     sSort.iECursor = pParse->nTab++;
111420     sSort.addrSortIndex =
111421       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
111422           sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
111423           (char*)pKeyInfo, P4_KEYINFO
111424       );
111425   }else{
111426     sSort.addrSortIndex = -1;
111427   }
111428 
111429   /* If the output is destined for a temporary table, open that table.
111430   */
111431   if( pDest->eDest==SRT_EphemTab ){
111432     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
111433   }
111434 
111435   /* Set the limiter.
111436   */
111437   iEnd = sqlite3VdbeMakeLabel(v);
111438   p->nSelectRow = LARGEST_INT64;
111439   computeLimitRegisters(pParse, p, iEnd);
111440   if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
111441     sqlite3VdbeGetOp(v, sSort.addrSortIndex)->opcode = OP_SorterOpen;
111442     sSort.sortFlags |= SORTFLAG_UseSorter;
111443   }
111444 
111445   /* Open a virtual index to use for the distinct set.
111446   */
111447   if( p->selFlags & SF_Distinct ){
111448     sDistinct.tabTnct = pParse->nTab++;
111449     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
111450                                 sDistinct.tabTnct, 0, 0,
111451                                 (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
111452                                 P4_KEYINFO);
111453     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
111454     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
111455   }else{
111456     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
111457   }
111458 
111459   if( !isAgg && pGroupBy==0 ){
111460     /* No aggregate functions and no GROUP BY clause */
111461     u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
111462 
111463     /* Begin the database scan. */
111464     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
111465                                p->pEList, wctrlFlags, 0);
111466     if( pWInfo==0 ) goto select_end;
111467     if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
111468       p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
111469     }
111470     if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
111471       sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
111472     }
111473     if( sSort.pOrderBy ){
111474       sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
111475       if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
111476         sSort.pOrderBy = 0;
111477       }
111478     }
111479 
111480     /* If sorting index that was created by a prior OP_OpenEphemeral
111481     ** instruction ended up not being needed, then change the OP_OpenEphemeral
111482     ** into an OP_Noop.
111483     */
111484     if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
111485       sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
111486     }
111487 
111488     /* Use the standard inner loop. */
111489     selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
111490                     sqlite3WhereContinueLabel(pWInfo),
111491                     sqlite3WhereBreakLabel(pWInfo));
111492 
111493     /* End the database scan loop.
111494     */
111495     sqlite3WhereEnd(pWInfo);
111496   }else{
111497     /* This case when there exist aggregate functions or a GROUP BY clause
111498     ** or both */
111499     NameContext sNC;    /* Name context for processing aggregate information */
111500     int iAMem;          /* First Mem address for storing current GROUP BY */
111501     int iBMem;          /* First Mem address for previous GROUP BY */
111502     int iUseFlag;       /* Mem address holding flag indicating that at least
111503                         ** one row of the input to the aggregator has been
111504                         ** processed */
111505     int iAbortFlag;     /* Mem address which causes query abort if positive */
111506     int groupBySort;    /* Rows come from source in GROUP BY order */
111507     int addrEnd;        /* End of processing for this SELECT */
111508     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
111509     int sortOut = 0;    /* Output register from the sorter */
111510     int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
111511 
111512     /* Remove any and all aliases between the result set and the
111513     ** GROUP BY clause.
111514     */
111515     if( pGroupBy ){
111516       int k;                        /* Loop counter */
111517       struct ExprList_item *pItem;  /* For looping over expression in a list */
111518 
111519       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
111520         pItem->u.x.iAlias = 0;
111521       }
111522       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
111523         pItem->u.x.iAlias = 0;
111524       }
111525       if( p->nSelectRow>100 ) p->nSelectRow = 100;
111526     }else{
111527       p->nSelectRow = 1;
111528     }
111529 
111530 
111531     /* If there is both a GROUP BY and an ORDER BY clause and they are
111532     ** identical, then it may be possible to disable the ORDER BY clause
111533     ** on the grounds that the GROUP BY will cause elements to come out
111534     ** in the correct order. It also may not - the GROUP BY may use a
111535     ** database index that causes rows to be grouped together as required
111536     ** but not actually sorted. Either way, record the fact that the
111537     ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
111538     ** variable.  */
111539     if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
111540       orderByGrp = 1;
111541     }
111542 
111543     /* Create a label to jump to when we want to abort the query */
111544     addrEnd = sqlite3VdbeMakeLabel(v);
111545 
111546     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
111547     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
111548     ** SELECT statement.
111549     */
111550     memset(&sNC, 0, sizeof(sNC));
111551     sNC.pParse = pParse;
111552     sNC.pSrcList = pTabList;
111553     sNC.pAggInfo = &sAggInfo;
111554     sAggInfo.mnReg = pParse->nMem+1;
111555     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
111556     sAggInfo.pGroupBy = pGroupBy;
111557     sqlite3ExprAnalyzeAggList(&sNC, pEList);
111558     sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
111559     if( pHaving ){
111560       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
111561     }
111562     sAggInfo.nAccumulator = sAggInfo.nColumn;
111563     for(i=0; i<sAggInfo.nFunc; i++){
111564       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
111565       sNC.ncFlags |= NC_InAggFunc;
111566       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
111567       sNC.ncFlags &= ~NC_InAggFunc;
111568     }
111569     sAggInfo.mxReg = pParse->nMem;
111570     if( db->mallocFailed ) goto select_end;
111571 
111572     /* Processing for aggregates with GROUP BY is very different and
111573     ** much more complex than aggregates without a GROUP BY.
111574     */
111575     if( pGroupBy ){
111576       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
111577       int j1;             /* A-vs-B comparision jump */
111578       int addrOutputRow;  /* Start of subroutine that outputs a result row */
111579       int regOutputRow;   /* Return address register for output subroutine */
111580       int addrSetAbort;   /* Set the abort flag and return */
111581       int addrTopOfLoop;  /* Top of the input loop */
111582       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
111583       int addrReset;      /* Subroutine for resetting the accumulator */
111584       int regReset;       /* Return address register for reset subroutine */
111585 
111586       /* If there is a GROUP BY clause we might need a sorting index to
111587       ** implement it.  Allocate that sorting index now.  If it turns out
111588       ** that we do not need it after all, the OP_SorterOpen instruction
111589       ** will be converted into a Noop.
111590       */
111591       sAggInfo.sortingIdx = pParse->nTab++;
111592       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
111593       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
111594           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
111595           0, (char*)pKeyInfo, P4_KEYINFO);
111596 
111597       /* Initialize memory locations used by GROUP BY aggregate processing
111598       */
111599       iUseFlag = ++pParse->nMem;
111600       iAbortFlag = ++pParse->nMem;
111601       regOutputRow = ++pParse->nMem;
111602       addrOutputRow = sqlite3VdbeMakeLabel(v);
111603       regReset = ++pParse->nMem;
111604       addrReset = sqlite3VdbeMakeLabel(v);
111605       iAMem = pParse->nMem + 1;
111606       pParse->nMem += pGroupBy->nExpr;
111607       iBMem = pParse->nMem + 1;
111608       pParse->nMem += pGroupBy->nExpr;
111609       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
111610       VdbeComment((v, "clear abort flag"));
111611       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
111612       VdbeComment((v, "indicate accumulator empty"));
111613       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
111614 
111615       /* Begin a loop that will extract all source rows in GROUP BY order.
111616       ** This might involve two separate loops with an OP_Sort in between, or
111617       ** it might be a single loop that uses an index to extract information
111618       ** in the right order to begin with.
111619       */
111620       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
111621       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
111622           WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
111623       );
111624       if( pWInfo==0 ) goto select_end;
111625       if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
111626         /* The optimizer is able to deliver rows in group by order so
111627         ** we do not have to sort.  The OP_OpenEphemeral table will be
111628         ** cancelled later because we still need to use the pKeyInfo
111629         */
111630         groupBySort = 0;
111631       }else{
111632         /* Rows are coming out in undetermined order.  We have to push
111633         ** each row into a sorting index, terminate the first loop,
111634         ** then loop over the sorting index in order to get the output
111635         ** in sorted order
111636         */
111637         int regBase;
111638         int regRecord;
111639         int nCol;
111640         int nGroupBy;
111641 
111642         explainTempTable(pParse,
111643             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
111644                     "DISTINCT" : "GROUP BY");
111645 
111646         groupBySort = 1;
111647         nGroupBy = pGroupBy->nExpr;
111648         nCol = nGroupBy;
111649         j = nGroupBy;
111650         for(i=0; i<sAggInfo.nColumn; i++){
111651           if( sAggInfo.aCol[i].iSorterColumn>=j ){
111652             nCol++;
111653             j++;
111654           }
111655         }
111656         regBase = sqlite3GetTempRange(pParse, nCol);
111657         sqlite3ExprCacheClear(pParse);
111658         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
111659         j = nGroupBy;
111660         for(i=0; i<sAggInfo.nColumn; i++){
111661           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
111662           if( pCol->iSorterColumn>=j ){
111663             int r1 = j + regBase;
111664             int r2;
111665 
111666             r2 = sqlite3ExprCodeGetColumn(pParse,
111667                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
111668             if( r1!=r2 ){
111669               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
111670             }
111671             j++;
111672           }
111673         }
111674         regRecord = sqlite3GetTempReg(pParse);
111675         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
111676         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
111677         sqlite3ReleaseTempReg(pParse, regRecord);
111678         sqlite3ReleaseTempRange(pParse, regBase, nCol);
111679         sqlite3WhereEnd(pWInfo);
111680         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
111681         sortOut = sqlite3GetTempReg(pParse);
111682         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
111683         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
111684         VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
111685         sAggInfo.useSortingIdx = 1;
111686         sqlite3ExprCacheClear(pParse);
111687 
111688       }
111689 
111690       /* If the index or temporary table used by the GROUP BY sort
111691       ** will naturally deliver rows in the order required by the ORDER BY
111692       ** clause, cancel the ephemeral table open coded earlier.
111693       **
111694       ** This is an optimization - the correct answer should result regardless.
111695       ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
111696       ** disable this optimization for testing purposes.  */
111697       if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
111698        && (groupBySort || sqlite3WhereIsSorted(pWInfo))
111699       ){
111700         sSort.pOrderBy = 0;
111701         sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
111702       }
111703 
111704       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
111705       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
111706       ** Then compare the current GROUP BY terms against the GROUP BY terms
111707       ** from the previous row currently stored in a0, a1, a2...
111708       */
111709       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
111710       sqlite3ExprCacheClear(pParse);
111711       if( groupBySort ){
111712         sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, sortOut,sortPTab);
111713       }
111714       for(j=0; j<pGroupBy->nExpr; j++){
111715         if( groupBySort ){
111716           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
111717         }else{
111718           sAggInfo.directMode = 1;
111719           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
111720         }
111721       }
111722       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
111723                           (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
111724       j1 = sqlite3VdbeCurrentAddr(v);
111725       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v);
111726 
111727       /* Generate code that runs whenever the GROUP BY changes.
111728       ** Changes in the GROUP BY are detected by the previous code
111729       ** block.  If there were no changes, this block is skipped.
111730       **
111731       ** This code copies current group by terms in b0,b1,b2,...
111732       ** over to a0,a1,a2.  It then calls the output subroutine
111733       ** and resets the aggregate accumulator registers in preparation
111734       ** for the next GROUP BY batch.
111735       */
111736       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
111737       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
111738       VdbeComment((v, "output one row"));
111739       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
111740       VdbeComment((v, "check abort flag"));
111741       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
111742       VdbeComment((v, "reset accumulator"));
111743 
111744       /* Update the aggregate accumulators based on the content of
111745       ** the current row
111746       */
111747       sqlite3VdbeJumpHere(v, j1);
111748       updateAccumulator(pParse, &sAggInfo);
111749       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
111750       VdbeComment((v, "indicate data in accumulator"));
111751 
111752       /* End of the loop
111753       */
111754       if( groupBySort ){
111755         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
111756         VdbeCoverage(v);
111757       }else{
111758         sqlite3WhereEnd(pWInfo);
111759         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
111760       }
111761 
111762       /* Output the final row of result
111763       */
111764       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
111765       VdbeComment((v, "output final row"));
111766 
111767       /* Jump over the subroutines
111768       */
111769       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
111770 
111771       /* Generate a subroutine that outputs a single row of the result
111772       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
111773       ** is less than or equal to zero, the subroutine is a no-op.  If
111774       ** the processing calls for the query to abort, this subroutine
111775       ** increments the iAbortFlag memory location before returning in
111776       ** order to signal the caller to abort.
111777       */
111778       addrSetAbort = sqlite3VdbeCurrentAddr(v);
111779       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
111780       VdbeComment((v, "set abort flag"));
111781       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
111782       sqlite3VdbeResolveLabel(v, addrOutputRow);
111783       addrOutputRow = sqlite3VdbeCurrentAddr(v);
111784       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v);
111785       VdbeComment((v, "Groupby result generator entry point"));
111786       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
111787       finalizeAggFunctions(pParse, &sAggInfo);
111788       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
111789       selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
111790                       &sDistinct, pDest,
111791                       addrOutputRow+1, addrSetAbort);
111792       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
111793       VdbeComment((v, "end groupby result generator"));
111794 
111795       /* Generate a subroutine that will reset the group-by accumulator
111796       */
111797       sqlite3VdbeResolveLabel(v, addrReset);
111798       resetAccumulator(pParse, &sAggInfo);
111799       sqlite3VdbeAddOp1(v, OP_Return, regReset);
111800 
111801     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
111802     else {
111803       ExprList *pDel = 0;
111804 #ifndef SQLITE_OMIT_BTREECOUNT
111805       Table *pTab;
111806       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
111807         /* If isSimpleCount() returns a pointer to a Table structure, then
111808         ** the SQL statement is of the form:
111809         **
111810         **   SELECT count(*) FROM <tbl>
111811         **
111812         ** where the Table structure returned represents table <tbl>.
111813         **
111814         ** This statement is so common that it is optimized specially. The
111815         ** OP_Count instruction is executed either on the intkey table that
111816         ** contains the data for table <tbl> or on one of its indexes. It
111817         ** is better to execute the op on an index, as indexes are almost
111818         ** always spread across less pages than their corresponding tables.
111819         */
111820         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
111821         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
111822         Index *pIdx;                         /* Iterator variable */
111823         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
111824         Index *pBest = 0;                    /* Best index found so far */
111825         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
111826 
111827         sqlite3CodeVerifySchema(pParse, iDb);
111828         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
111829 
111830         /* Search for the index that has the lowest scan cost.
111831         **
111832         ** (2011-04-15) Do not do a full scan of an unordered index.
111833         **
111834         ** (2013-10-03) Do not count the entries in a partial index.
111835         **
111836         ** In practice the KeyInfo structure will not be used. It is only
111837         ** passed to keep OP_OpenRead happy.
111838         */
111839         if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
111840         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
111841           if( pIdx->bUnordered==0
111842            && pIdx->szIdxRow<pTab->szTabRow
111843            && pIdx->pPartIdxWhere==0
111844            && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
111845           ){
111846             pBest = pIdx;
111847           }
111848         }
111849         if( pBest ){
111850           iRoot = pBest->tnum;
111851           pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
111852         }
111853 
111854         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
111855         sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
111856         if( pKeyInfo ){
111857           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
111858         }
111859         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
111860         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
111861         explainSimpleCount(pParse, pTab, pBest);
111862       }else
111863 #endif /* SQLITE_OMIT_BTREECOUNT */
111864       {
111865         /* Check if the query is of one of the following forms:
111866         **
111867         **   SELECT min(x) FROM ...
111868         **   SELECT max(x) FROM ...
111869         **
111870         ** If it is, then ask the code in where.c to attempt to sort results
111871         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
111872         ** If where.c is able to produce results sorted in this order, then
111873         ** add vdbe code to break out of the processing loop after the
111874         ** first iteration (since the first iteration of the loop is
111875         ** guaranteed to operate on the row with the minimum or maximum
111876         ** value of x, the only row required).
111877         **
111878         ** A special flag must be passed to sqlite3WhereBegin() to slightly
111879         ** modify behavior as follows:
111880         **
111881         **   + If the query is a "SELECT min(x)", then the loop coded by
111882         **     where.c should not iterate over any values with a NULL value
111883         **     for x.
111884         **
111885         **   + The optimizer code in where.c (the thing that decides which
111886         **     index or indices to use) should place a different priority on
111887         **     satisfying the 'ORDER BY' clause than it does in other cases.
111888         **     Refer to code and comments in where.c for details.
111889         */
111890         ExprList *pMinMax = 0;
111891         u8 flag = WHERE_ORDERBY_NORMAL;
111892 
111893         assert( p->pGroupBy==0 );
111894         assert( flag==0 );
111895         if( p->pHaving==0 ){
111896           flag = minMaxQuery(&sAggInfo, &pMinMax);
111897         }
111898         assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
111899 
111900         if( flag ){
111901           pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
111902           pDel = pMinMax;
111903           if( pMinMax && !db->mallocFailed ){
111904             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
111905             pMinMax->a[0].pExpr->op = TK_COLUMN;
111906           }
111907         }
111908 
111909         /* This case runs if the aggregate has no GROUP BY clause.  The
111910         ** processing is much simpler since there is only a single row
111911         ** of output.
111912         */
111913         resetAccumulator(pParse, &sAggInfo);
111914         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
111915         if( pWInfo==0 ){
111916           sqlite3ExprListDelete(db, pDel);
111917           goto select_end;
111918         }
111919         updateAccumulator(pParse, &sAggInfo);
111920         assert( pMinMax==0 || pMinMax->nExpr==1 );
111921         if( sqlite3WhereIsOrdered(pWInfo)>0 ){
111922           sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
111923           VdbeComment((v, "%s() by index",
111924                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
111925         }
111926         sqlite3WhereEnd(pWInfo);
111927         finalizeAggFunctions(pParse, &sAggInfo);
111928       }
111929 
111930       sSort.pOrderBy = 0;
111931       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
111932       selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
111933                       pDest, addrEnd, addrEnd);
111934       sqlite3ExprListDelete(db, pDel);
111935     }
111936     sqlite3VdbeResolveLabel(v, addrEnd);
111937 
111938   } /* endif aggregate query */
111939 
111940   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
111941     explainTempTable(pParse, "DISTINCT");
111942   }
111943 
111944   /* If there is an ORDER BY clause, then we need to sort the results
111945   ** and send them to the callback one by one.
111946   */
111947   if( sSort.pOrderBy ){
111948     explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
111949     generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
111950   }
111951 
111952   /* Jump here to skip this query
111953   */
111954   sqlite3VdbeResolveLabel(v, iEnd);
111955 
111956   /* The SELECT has been coded. If there is an error in the Parse structure,
111957   ** set the return code to 1. Otherwise 0. */
111958   rc = (pParse->nErr>0);
111959 
111960   /* Control jumps to here if an error is encountered above, or upon
111961   ** successful coding of the SELECT.
111962   */
111963 select_end:
111964   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
111965 
111966   /* Identify column names if results of the SELECT are to be output.
111967   */
111968   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
111969     generateColumnNames(pParse, pTabList, pEList);
111970   }
111971 
111972   sqlite3DbFree(db, sAggInfo.aCol);
111973   sqlite3DbFree(db, sAggInfo.aFunc);
111974 #if SELECTTRACE_ENABLED
111975   SELECTTRACE(1,pParse,p,("end processing\n"));
111976   pParse->nSelectIndent--;
111977 #endif
111978   return rc;
111979 }
111980 
111981 #ifdef SQLITE_DEBUG
111982 /*
111983 ** Generate a human-readable description of a the Select object.
111984 */
111985 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
111986   int n = 0;
111987   pView = sqlite3TreeViewPush(pView, moreToFollow);
111988   sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p)",
111989     ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
111990     ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p
111991   );
111992   if( p->pSrc && p->pSrc->nSrc ) n++;
111993   if( p->pWhere ) n++;
111994   if( p->pGroupBy ) n++;
111995   if( p->pHaving ) n++;
111996   if( p->pOrderBy ) n++;
111997   if( p->pLimit ) n++;
111998   if( p->pOffset ) n++;
111999   if( p->pPrior ) n++;
112000   sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
112001   if( p->pSrc && p->pSrc->nSrc ){
112002     int i;
112003     pView = sqlite3TreeViewPush(pView, (n--)>0);
112004     sqlite3TreeViewLine(pView, "FROM");
112005     for(i=0; i<p->pSrc->nSrc; i++){
112006       struct SrcList_item *pItem = &p->pSrc->a[i];
112007       StrAccum x;
112008       char zLine[100];
112009       sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
112010       sqlite3XPrintf(&x, 0, "{%d,*}", pItem->iCursor);
112011       if( pItem->zDatabase ){
112012         sqlite3XPrintf(&x, 0, " %s.%s", pItem->zDatabase, pItem->zName);
112013       }else if( pItem->zName ){
112014         sqlite3XPrintf(&x, 0, " %s", pItem->zName);
112015       }
112016       if( pItem->pTab ){
112017         sqlite3XPrintf(&x, 0, " tabname=%Q", pItem->pTab->zName);
112018       }
112019       if( pItem->zAlias ){
112020         sqlite3XPrintf(&x, 0, " (AS %s)", pItem->zAlias);
112021       }
112022       if( pItem->jointype & JT_LEFT ){
112023         sqlite3XPrintf(&x, 0, " LEFT-JOIN");
112024       }
112025       sqlite3StrAccumFinish(&x);
112026       sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
112027       if( pItem->pSelect ){
112028         sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
112029       }
112030       sqlite3TreeViewPop(pView);
112031     }
112032     sqlite3TreeViewPop(pView);
112033   }
112034   if( p->pWhere ){
112035     sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
112036     sqlite3TreeViewExpr(pView, p->pWhere, 0);
112037     sqlite3TreeViewPop(pView);
112038   }
112039   if( p->pGroupBy ){
112040     sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
112041   }
112042   if( p->pHaving ){
112043     sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
112044     sqlite3TreeViewExpr(pView, p->pHaving, 0);
112045     sqlite3TreeViewPop(pView);
112046   }
112047   if( p->pOrderBy ){
112048     sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
112049   }
112050   if( p->pLimit ){
112051     sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
112052     sqlite3TreeViewExpr(pView, p->pLimit, 0);
112053     sqlite3TreeViewPop(pView);
112054   }
112055   if( p->pOffset ){
112056     sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
112057     sqlite3TreeViewExpr(pView, p->pOffset, 0);
112058     sqlite3TreeViewPop(pView);
112059   }
112060   if( p->pPrior ){
112061     const char *zOp = "UNION";
112062     switch( p->op ){
112063       case TK_ALL:         zOp = "UNION ALL";  break;
112064       case TK_INTERSECT:   zOp = "INTERSECT";  break;
112065       case TK_EXCEPT:      zOp = "EXCEPT";     break;
112066     }
112067     sqlite3TreeViewItem(pView, zOp, (n--)>0);
112068     sqlite3TreeViewSelect(pView, p->pPrior, 0);
112069     sqlite3TreeViewPop(pView);
112070   }
112071   sqlite3TreeViewPop(pView);
112072 }
112073 #endif /* SQLITE_DEBUG */
112074 
112075 /************** End of select.c **********************************************/
112076 /************** Begin file table.c *******************************************/
112077 /*
112078 ** 2001 September 15
112079 **
112080 ** The author disclaims copyright to this source code.  In place of
112081 ** a legal notice, here is a blessing:
112082 **
112083 **    May you do good and not evil.
112084 **    May you find forgiveness for yourself and forgive others.
112085 **    May you share freely, never taking more than you give.
112086 **
112087 *************************************************************************
112088 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
112089 ** interface routines.  These are just wrappers around the main
112090 ** interface routine of sqlite3_exec().
112091 **
112092 ** These routines are in a separate files so that they will not be linked
112093 ** if they are not used.
112094 */
112095 /* #include <stdlib.h> */
112096 /* #include <string.h> */
112097 
112098 #ifndef SQLITE_OMIT_GET_TABLE
112099 
112100 /*
112101 ** This structure is used to pass data from sqlite3_get_table() through
112102 ** to the callback function is uses to build the result.
112103 */
112104 typedef struct TabResult {
112105   char **azResult;   /* Accumulated output */
112106   char *zErrMsg;     /* Error message text, if an error occurs */
112107   u32 nAlloc;        /* Slots allocated for azResult[] */
112108   u32 nRow;          /* Number of rows in the result */
112109   u32 nColumn;       /* Number of columns in the result */
112110   u32 nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
112111   int rc;            /* Return code from sqlite3_exec() */
112112 } TabResult;
112113 
112114 /*
112115 ** This routine is called once for each row in the result table.  Its job
112116 ** is to fill in the TabResult structure appropriately, allocating new
112117 ** memory as necessary.
112118 */
112119 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
112120   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
112121   int need;                         /* Slots needed in p->azResult[] */
112122   int i;                            /* Loop counter */
112123   char *z;                          /* A single column of result */
112124 
112125   /* Make sure there is enough space in p->azResult to hold everything
112126   ** we need to remember from this invocation of the callback.
112127   */
112128   if( p->nRow==0 && argv!=0 ){
112129     need = nCol*2;
112130   }else{
112131     need = nCol;
112132   }
112133   if( p->nData + need > p->nAlloc ){
112134     char **azNew;
112135     p->nAlloc = p->nAlloc*2 + need;
112136     azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
112137     if( azNew==0 ) goto malloc_failed;
112138     p->azResult = azNew;
112139   }
112140 
112141   /* If this is the first row, then generate an extra row containing
112142   ** the names of all columns.
112143   */
112144   if( p->nRow==0 ){
112145     p->nColumn = nCol;
112146     for(i=0; i<nCol; i++){
112147       z = sqlite3_mprintf("%s", colv[i]);
112148       if( z==0 ) goto malloc_failed;
112149       p->azResult[p->nData++] = z;
112150     }
112151   }else if( (int)p->nColumn!=nCol ){
112152     sqlite3_free(p->zErrMsg);
112153     p->zErrMsg = sqlite3_mprintf(
112154        "sqlite3_get_table() called with two or more incompatible queries"
112155     );
112156     p->rc = SQLITE_ERROR;
112157     return 1;
112158   }
112159 
112160   /* Copy over the row data
112161   */
112162   if( argv!=0 ){
112163     for(i=0; i<nCol; i++){
112164       if( argv[i]==0 ){
112165         z = 0;
112166       }else{
112167         int n = sqlite3Strlen30(argv[i])+1;
112168         z = sqlite3_malloc64( n );
112169         if( z==0 ) goto malloc_failed;
112170         memcpy(z, argv[i], n);
112171       }
112172       p->azResult[p->nData++] = z;
112173     }
112174     p->nRow++;
112175   }
112176   return 0;
112177 
112178 malloc_failed:
112179   p->rc = SQLITE_NOMEM;
112180   return 1;
112181 }
112182 
112183 /*
112184 ** Query the database.  But instead of invoking a callback for each row,
112185 ** malloc() for space to hold the result and return the entire results
112186 ** at the conclusion of the call.
112187 **
112188 ** The result that is written to ***pazResult is held in memory obtained
112189 ** from malloc().  But the caller cannot free this memory directly.
112190 ** Instead, the entire table should be passed to sqlite3_free_table() when
112191 ** the calling procedure is finished using it.
112192 */
112193 SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
112194   sqlite3 *db,                /* The database on which the SQL executes */
112195   const char *zSql,           /* The SQL to be executed */
112196   char ***pazResult,          /* Write the result table here */
112197   int *pnRow,                 /* Write the number of rows in the result here */
112198   int *pnColumn,              /* Write the number of columns of result here */
112199   char **pzErrMsg             /* Write error messages here */
112200 ){
112201   int rc;
112202   TabResult res;
112203 
112204 #ifdef SQLITE_ENABLE_API_ARMOR
112205   if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
112206 #endif
112207   *pazResult = 0;
112208   if( pnColumn ) *pnColumn = 0;
112209   if( pnRow ) *pnRow = 0;
112210   if( pzErrMsg ) *pzErrMsg = 0;
112211   res.zErrMsg = 0;
112212   res.nRow = 0;
112213   res.nColumn = 0;
112214   res.nData = 1;
112215   res.nAlloc = 20;
112216   res.rc = SQLITE_OK;
112217   res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
112218   if( res.azResult==0 ){
112219      db->errCode = SQLITE_NOMEM;
112220      return SQLITE_NOMEM;
112221   }
112222   res.azResult[0] = 0;
112223   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
112224   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
112225   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
112226   if( (rc&0xff)==SQLITE_ABORT ){
112227     sqlite3_free_table(&res.azResult[1]);
112228     if( res.zErrMsg ){
112229       if( pzErrMsg ){
112230         sqlite3_free(*pzErrMsg);
112231         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
112232       }
112233       sqlite3_free(res.zErrMsg);
112234     }
112235     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
112236     return res.rc;
112237   }
112238   sqlite3_free(res.zErrMsg);
112239   if( rc!=SQLITE_OK ){
112240     sqlite3_free_table(&res.azResult[1]);
112241     return rc;
112242   }
112243   if( res.nAlloc>res.nData ){
112244     char **azNew;
112245     azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
112246     if( azNew==0 ){
112247       sqlite3_free_table(&res.azResult[1]);
112248       db->errCode = SQLITE_NOMEM;
112249       return SQLITE_NOMEM;
112250     }
112251     res.azResult = azNew;
112252   }
112253   *pazResult = &res.azResult[1];
112254   if( pnColumn ) *pnColumn = res.nColumn;
112255   if( pnRow ) *pnRow = res.nRow;
112256   return rc;
112257 }
112258 
112259 /*
112260 ** This routine frees the space the sqlite3_get_table() malloced.
112261 */
112262 SQLITE_API void SQLITE_STDCALL sqlite3_free_table(
112263   char **azResult            /* Result returned from sqlite3_get_table() */
112264 ){
112265   if( azResult ){
112266     int i, n;
112267     azResult--;
112268     assert( azResult!=0 );
112269     n = SQLITE_PTR_TO_INT(azResult[0]);
112270     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
112271     sqlite3_free(azResult);
112272   }
112273 }
112274 
112275 #endif /* SQLITE_OMIT_GET_TABLE */
112276 
112277 /************** End of table.c ***********************************************/
112278 /************** Begin file trigger.c *****************************************/
112279 /*
112280 **
112281 ** The author disclaims copyright to this source code.  In place of
112282 ** a legal notice, here is a blessing:
112283 **
112284 **    May you do good and not evil.
112285 **    May you find forgiveness for yourself and forgive others.
112286 **    May you share freely, never taking more than you give.
112287 **
112288 *************************************************************************
112289 ** This file contains the implementation for TRIGGERs
112290 */
112291 
112292 #ifndef SQLITE_OMIT_TRIGGER
112293 /*
112294 ** Delete a linked list of TriggerStep structures.
112295 */
112296 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
112297   while( pTriggerStep ){
112298     TriggerStep * pTmp = pTriggerStep;
112299     pTriggerStep = pTriggerStep->pNext;
112300 
112301     sqlite3ExprDelete(db, pTmp->pWhere);
112302     sqlite3ExprListDelete(db, pTmp->pExprList);
112303     sqlite3SelectDelete(db, pTmp->pSelect);
112304     sqlite3IdListDelete(db, pTmp->pIdList);
112305 
112306     sqlite3DbFree(db, pTmp);
112307   }
112308 }
112309 
112310 /*
112311 ** Given table pTab, return a list of all the triggers attached to
112312 ** the table. The list is connected by Trigger.pNext pointers.
112313 **
112314 ** All of the triggers on pTab that are in the same database as pTab
112315 ** are already attached to pTab->pTrigger.  But there might be additional
112316 ** triggers on pTab in the TEMP schema.  This routine prepends all
112317 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
112318 ** and returns the combined list.
112319 **
112320 ** To state it another way:  This routine returns a list of all triggers
112321 ** that fire off of pTab.  The list will include any TEMP triggers on
112322 ** pTab as well as the triggers lised in pTab->pTrigger.
112323 */
112324 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
112325   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
112326   Trigger *pList = 0;                  /* List of triggers to return */
112327 
112328   if( pParse->disableTriggers ){
112329     return 0;
112330   }
112331 
112332   if( pTmpSchema!=pTab->pSchema ){
112333     HashElem *p;
112334     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
112335     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
112336       Trigger *pTrig = (Trigger *)sqliteHashData(p);
112337       if( pTrig->pTabSchema==pTab->pSchema
112338        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
112339       ){
112340         pTrig->pNext = (pList ? pList : pTab->pTrigger);
112341         pList = pTrig;
112342       }
112343     }
112344   }
112345 
112346   return (pList ? pList : pTab->pTrigger);
112347 }
112348 
112349 /*
112350 ** This is called by the parser when it sees a CREATE TRIGGER statement
112351 ** up to the point of the BEGIN before the trigger actions.  A Trigger
112352 ** structure is generated based on the information available and stored
112353 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
112354 ** sqlite3FinishTrigger() function is called to complete the trigger
112355 ** construction process.
112356 */
112357 SQLITE_PRIVATE void sqlite3BeginTrigger(
112358   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
112359   Token *pName1,      /* The name of the trigger */
112360   Token *pName2,      /* The name of the trigger */
112361   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
112362   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
112363   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
112364   SrcList *pTableName,/* The name of the table/view the trigger applies to */
112365   Expr *pWhen,        /* WHEN clause */
112366   int isTemp,         /* True if the TEMPORARY keyword is present */
112367   int noErr           /* Suppress errors if the trigger already exists */
112368 ){
112369   Trigger *pTrigger = 0;  /* The new trigger */
112370   Table *pTab;            /* Table that the trigger fires off of */
112371   char *zName = 0;        /* Name of the trigger */
112372   sqlite3 *db = pParse->db;  /* The database connection */
112373   int iDb;                /* The database to store the trigger in */
112374   Token *pName;           /* The unqualified db name */
112375   DbFixer sFix;           /* State vector for the DB fixer */
112376   int iTabDb;             /* Index of the database holding pTab */
112377 
112378   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
112379   assert( pName2!=0 );
112380   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
112381   assert( op>0 && op<0xff );
112382   if( isTemp ){
112383     /* If TEMP was specified, then the trigger name may not be qualified. */
112384     if( pName2->n>0 ){
112385       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
112386       goto trigger_cleanup;
112387     }
112388     iDb = 1;
112389     pName = pName1;
112390   }else{
112391     /* Figure out the db that the trigger will be created in */
112392     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
112393     if( iDb<0 ){
112394       goto trigger_cleanup;
112395     }
112396   }
112397   if( !pTableName || db->mallocFailed ){
112398     goto trigger_cleanup;
112399   }
112400 
112401   /* A long-standing parser bug is that this syntax was allowed:
112402   **
112403   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
112404   **                                                 ^^^^^^^^
112405   **
112406   ** To maintain backwards compatibility, ignore the database
112407   ** name on pTableName if we are reparsing out of SQLITE_MASTER.
112408   */
112409   if( db->init.busy && iDb!=1 ){
112410     sqlite3DbFree(db, pTableName->a[0].zDatabase);
112411     pTableName->a[0].zDatabase = 0;
112412   }
112413 
112414   /* If the trigger name was unqualified, and the table is a temp table,
112415   ** then set iDb to 1 to create the trigger in the temporary database.
112416   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
112417   ** exist, the error is caught by the block below.
112418   */
112419   pTab = sqlite3SrcListLookup(pParse, pTableName);
112420   if( db->init.busy==0 && pName2->n==0 && pTab
112421         && pTab->pSchema==db->aDb[1].pSchema ){
112422     iDb = 1;
112423   }
112424 
112425   /* Ensure the table name matches database name and that the table exists */
112426   if( db->mallocFailed ) goto trigger_cleanup;
112427   assert( pTableName->nSrc==1 );
112428   sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
112429   if( sqlite3FixSrcList(&sFix, pTableName) ){
112430     goto trigger_cleanup;
112431   }
112432   pTab = sqlite3SrcListLookup(pParse, pTableName);
112433   if( !pTab ){
112434     /* The table does not exist. */
112435     if( db->init.iDb==1 ){
112436       /* Ticket #3810.
112437       ** Normally, whenever a table is dropped, all associated triggers are
112438       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
112439       ** and the table is dropped by a different database connection, the
112440       ** trigger is not visible to the database connection that does the
112441       ** drop so the trigger cannot be dropped.  This results in an
112442       ** "orphaned trigger" - a trigger whose associated table is missing.
112443       */
112444       db->init.orphanTrigger = 1;
112445     }
112446     goto trigger_cleanup;
112447   }
112448   if( IsVirtual(pTab) ){
112449     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
112450     goto trigger_cleanup;
112451   }
112452 
112453   /* Check that the trigger name is not reserved and that no trigger of the
112454   ** specified name exists */
112455   zName = sqlite3NameFromToken(db, pName);
112456   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
112457     goto trigger_cleanup;
112458   }
112459   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112460   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
112461     if( !noErr ){
112462       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
112463     }else{
112464       assert( !db->init.busy );
112465       sqlite3CodeVerifySchema(pParse, iDb);
112466     }
112467     goto trigger_cleanup;
112468   }
112469 
112470   /* Do not create a trigger on a system table */
112471   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
112472     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
112473     goto trigger_cleanup;
112474   }
112475 
112476   /* INSTEAD of triggers are only for views and views only support INSTEAD
112477   ** of triggers.
112478   */
112479   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
112480     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
112481         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
112482     goto trigger_cleanup;
112483   }
112484   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
112485     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
112486         " trigger on table: %S", pTableName, 0);
112487     goto trigger_cleanup;
112488   }
112489   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
112490 
112491 #ifndef SQLITE_OMIT_AUTHORIZATION
112492   {
112493     int code = SQLITE_CREATE_TRIGGER;
112494     const char *zDb = db->aDb[iTabDb].zName;
112495     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
112496     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
112497     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
112498       goto trigger_cleanup;
112499     }
112500     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
112501       goto trigger_cleanup;
112502     }
112503   }
112504 #endif
112505 
112506   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
112507   ** cannot appear on views.  So we might as well translate every
112508   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
112509   ** elsewhere.
112510   */
112511   if (tr_tm == TK_INSTEAD){
112512     tr_tm = TK_BEFORE;
112513   }
112514 
112515   /* Build the Trigger object */
112516   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
112517   if( pTrigger==0 ) goto trigger_cleanup;
112518   pTrigger->zName = zName;
112519   zName = 0;
112520   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
112521   pTrigger->pSchema = db->aDb[iDb].pSchema;
112522   pTrigger->pTabSchema = pTab->pSchema;
112523   pTrigger->op = (u8)op;
112524   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
112525   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
112526   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
112527   assert( pParse->pNewTrigger==0 );
112528   pParse->pNewTrigger = pTrigger;
112529 
112530 trigger_cleanup:
112531   sqlite3DbFree(db, zName);
112532   sqlite3SrcListDelete(db, pTableName);
112533   sqlite3IdListDelete(db, pColumns);
112534   sqlite3ExprDelete(db, pWhen);
112535   if( !pParse->pNewTrigger ){
112536     sqlite3DeleteTrigger(db, pTrigger);
112537   }else{
112538     assert( pParse->pNewTrigger==pTrigger );
112539   }
112540 }
112541 
112542 /*
112543 ** This routine is called after all of the trigger actions have been parsed
112544 ** in order to complete the process of building the trigger.
112545 */
112546 SQLITE_PRIVATE void sqlite3FinishTrigger(
112547   Parse *pParse,          /* Parser context */
112548   TriggerStep *pStepList, /* The triggered program */
112549   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
112550 ){
112551   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
112552   char *zName;                            /* Name of trigger */
112553   sqlite3 *db = pParse->db;               /* The database */
112554   DbFixer sFix;                           /* Fixer object */
112555   int iDb;                                /* Database containing the trigger */
112556   Token nameToken;                        /* Trigger name for error reporting */
112557 
112558   pParse->pNewTrigger = 0;
112559   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
112560   zName = pTrig->zName;
112561   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
112562   pTrig->step_list = pStepList;
112563   while( pStepList ){
112564     pStepList->pTrig = pTrig;
112565     pStepList = pStepList->pNext;
112566   }
112567   nameToken.z = pTrig->zName;
112568   nameToken.n = sqlite3Strlen30(nameToken.z);
112569   sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
112570   if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
112571    || sqlite3FixExpr(&sFix, pTrig->pWhen)
112572   ){
112573     goto triggerfinish_cleanup;
112574   }
112575 
112576   /* if we are not initializing,
112577   ** build the sqlite_master entry
112578   */
112579   if( !db->init.busy ){
112580     Vdbe *v;
112581     char *z;
112582 
112583     /* Make an entry in the sqlite_master table */
112584     v = sqlite3GetVdbe(pParse);
112585     if( v==0 ) goto triggerfinish_cleanup;
112586     sqlite3BeginWriteOperation(pParse, 0, iDb);
112587     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
112588     sqlite3NestedParse(pParse,
112589        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
112590        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
112591        pTrig->table, z);
112592     sqlite3DbFree(db, z);
112593     sqlite3ChangeCookie(pParse, iDb);
112594     sqlite3VdbeAddParseSchemaOp(v, iDb,
112595         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
112596   }
112597 
112598   if( db->init.busy ){
112599     Trigger *pLink = pTrig;
112600     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
112601     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112602     pTrig = sqlite3HashInsert(pHash, zName, pTrig);
112603     if( pTrig ){
112604       db->mallocFailed = 1;
112605     }else if( pLink->pSchema==pLink->pTabSchema ){
112606       Table *pTab;
112607       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
112608       assert( pTab!=0 );
112609       pLink->pNext = pTab->pTrigger;
112610       pTab->pTrigger = pLink;
112611     }
112612   }
112613 
112614 triggerfinish_cleanup:
112615   sqlite3DeleteTrigger(db, pTrig);
112616   assert( !pParse->pNewTrigger );
112617   sqlite3DeleteTriggerStep(db, pStepList);
112618 }
112619 
112620 /*
112621 ** Turn a SELECT statement (that the pSelect parameter points to) into
112622 ** a trigger step.  Return a pointer to a TriggerStep structure.
112623 **
112624 ** The parser calls this routine when it finds a SELECT statement in
112625 ** body of a TRIGGER.
112626 */
112627 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
112628   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
112629   if( pTriggerStep==0 ) {
112630     sqlite3SelectDelete(db, pSelect);
112631     return 0;
112632   }
112633   pTriggerStep->op = TK_SELECT;
112634   pTriggerStep->pSelect = pSelect;
112635   pTriggerStep->orconf = OE_Default;
112636   return pTriggerStep;
112637 }
112638 
112639 /*
112640 ** Allocate space to hold a new trigger step.  The allocated space
112641 ** holds both the TriggerStep object and the TriggerStep.target.z string.
112642 **
112643 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
112644 */
112645 static TriggerStep *triggerStepAllocate(
112646   sqlite3 *db,                /* Database connection */
112647   u8 op,                      /* Trigger opcode */
112648   Token *pName                /* The target name */
112649 ){
112650   TriggerStep *pTriggerStep;
112651 
112652   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
112653   if( pTriggerStep ){
112654     char *z = (char*)&pTriggerStep[1];
112655     memcpy(z, pName->z, pName->n);
112656     sqlite3Dequote(z);
112657     pTriggerStep->zTarget = z;
112658     pTriggerStep->op = op;
112659   }
112660   return pTriggerStep;
112661 }
112662 
112663 /*
112664 ** Build a trigger step out of an INSERT statement.  Return a pointer
112665 ** to the new trigger step.
112666 **
112667 ** The parser calls this routine when it sees an INSERT inside the
112668 ** body of a trigger.
112669 */
112670 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
112671   sqlite3 *db,        /* The database connection */
112672   Token *pTableName,  /* Name of the table into which we insert */
112673   IdList *pColumn,    /* List of columns in pTableName to insert into */
112674   Select *pSelect,    /* A SELECT statement that supplies values */
112675   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
112676 ){
112677   TriggerStep *pTriggerStep;
112678 
112679   assert(pSelect != 0 || db->mallocFailed);
112680 
112681   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
112682   if( pTriggerStep ){
112683     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
112684     pTriggerStep->pIdList = pColumn;
112685     pTriggerStep->orconf = orconf;
112686   }else{
112687     sqlite3IdListDelete(db, pColumn);
112688   }
112689   sqlite3SelectDelete(db, pSelect);
112690 
112691   return pTriggerStep;
112692 }
112693 
112694 /*
112695 ** Construct a trigger step that implements an UPDATE statement and return
112696 ** a pointer to that trigger step.  The parser calls this routine when it
112697 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
112698 */
112699 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
112700   sqlite3 *db,         /* The database connection */
112701   Token *pTableName,   /* Name of the table to be updated */
112702   ExprList *pEList,    /* The SET clause: list of column and new values */
112703   Expr *pWhere,        /* The WHERE clause */
112704   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
112705 ){
112706   TriggerStep *pTriggerStep;
112707 
112708   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
112709   if( pTriggerStep ){
112710     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
112711     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
112712     pTriggerStep->orconf = orconf;
112713   }
112714   sqlite3ExprListDelete(db, pEList);
112715   sqlite3ExprDelete(db, pWhere);
112716   return pTriggerStep;
112717 }
112718 
112719 /*
112720 ** Construct a trigger step that implements a DELETE statement and return
112721 ** a pointer to that trigger step.  The parser calls this routine when it
112722 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
112723 */
112724 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
112725   sqlite3 *db,            /* Database connection */
112726   Token *pTableName,      /* The table from which rows are deleted */
112727   Expr *pWhere            /* The WHERE clause */
112728 ){
112729   TriggerStep *pTriggerStep;
112730 
112731   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
112732   if( pTriggerStep ){
112733     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
112734     pTriggerStep->orconf = OE_Default;
112735   }
112736   sqlite3ExprDelete(db, pWhere);
112737   return pTriggerStep;
112738 }
112739 
112740 /*
112741 ** Recursively delete a Trigger structure
112742 */
112743 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
112744   if( pTrigger==0 ) return;
112745   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
112746   sqlite3DbFree(db, pTrigger->zName);
112747   sqlite3DbFree(db, pTrigger->table);
112748   sqlite3ExprDelete(db, pTrigger->pWhen);
112749   sqlite3IdListDelete(db, pTrigger->pColumns);
112750   sqlite3DbFree(db, pTrigger);
112751 }
112752 
112753 /*
112754 ** This function is called to drop a trigger from the database schema.
112755 **
112756 ** This may be called directly from the parser and therefore identifies
112757 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
112758 ** same job as this routine except it takes a pointer to the trigger
112759 ** instead of the trigger name.
112760 **/
112761 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
112762   Trigger *pTrigger = 0;
112763   int i;
112764   const char *zDb;
112765   const char *zName;
112766   sqlite3 *db = pParse->db;
112767 
112768   if( db->mallocFailed ) goto drop_trigger_cleanup;
112769   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
112770     goto drop_trigger_cleanup;
112771   }
112772 
112773   assert( pName->nSrc==1 );
112774   zDb = pName->a[0].zDatabase;
112775   zName = pName->a[0].zName;
112776   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
112777   for(i=OMIT_TEMPDB; i<db->nDb; i++){
112778     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
112779     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
112780     assert( sqlite3SchemaMutexHeld(db, j, 0) );
112781     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
112782     if( pTrigger ) break;
112783   }
112784   if( !pTrigger ){
112785     if( !noErr ){
112786       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
112787     }else{
112788       sqlite3CodeVerifyNamedSchema(pParse, zDb);
112789     }
112790     pParse->checkSchema = 1;
112791     goto drop_trigger_cleanup;
112792   }
112793   sqlite3DropTriggerPtr(pParse, pTrigger);
112794 
112795 drop_trigger_cleanup:
112796   sqlite3SrcListDelete(db, pName);
112797 }
112798 
112799 /*
112800 ** Return a pointer to the Table structure for the table that a trigger
112801 ** is set on.
112802 */
112803 static Table *tableOfTrigger(Trigger *pTrigger){
112804   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
112805 }
112806 
112807 
112808 /*
112809 ** Drop a trigger given a pointer to that trigger.
112810 */
112811 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
112812   Table   *pTable;
112813   Vdbe *v;
112814   sqlite3 *db = pParse->db;
112815   int iDb;
112816 
112817   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
112818   assert( iDb>=0 && iDb<db->nDb );
112819   pTable = tableOfTrigger(pTrigger);
112820   assert( pTable );
112821   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
112822 #ifndef SQLITE_OMIT_AUTHORIZATION
112823   {
112824     int code = SQLITE_DROP_TRIGGER;
112825     const char *zDb = db->aDb[iDb].zName;
112826     const char *zTab = SCHEMA_TABLE(iDb);
112827     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
112828     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
112829       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
112830       return;
112831     }
112832   }
112833 #endif
112834 
112835   /* Generate code to destroy the database record of the trigger.
112836   */
112837   assert( pTable!=0 );
112838   if( (v = sqlite3GetVdbe(pParse))!=0 ){
112839     int base;
112840     static const int iLn = VDBE_OFFSET_LINENO(2);
112841     static const VdbeOpList dropTrigger[] = {
112842       { OP_Rewind,     0, ADDR(9),  0},
112843       { OP_String8,    0, 1,        0}, /* 1 */
112844       { OP_Column,     0, 1,        2},
112845       { OP_Ne,         2, ADDR(8),  1},
112846       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
112847       { OP_Column,     0, 0,        2},
112848       { OP_Ne,         2, ADDR(8),  1},
112849       { OP_Delete,     0, 0,        0},
112850       { OP_Next,       0, ADDR(1),  0}, /* 8 */
112851     };
112852 
112853     sqlite3BeginWriteOperation(pParse, 0, iDb);
112854     sqlite3OpenMasterTable(pParse, iDb);
112855     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger, iLn);
112856     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
112857     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
112858     sqlite3ChangeCookie(pParse, iDb);
112859     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
112860     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
112861     if( pParse->nMem<3 ){
112862       pParse->nMem = 3;
112863     }
112864   }
112865 }
112866 
112867 /*
112868 ** Remove a trigger from the hash tables of the sqlite* pointer.
112869 */
112870 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
112871   Trigger *pTrigger;
112872   Hash *pHash;
112873 
112874   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112875   pHash = &(db->aDb[iDb].pSchema->trigHash);
112876   pTrigger = sqlite3HashInsert(pHash, zName, 0);
112877   if( ALWAYS(pTrigger) ){
112878     if( pTrigger->pSchema==pTrigger->pTabSchema ){
112879       Table *pTab = tableOfTrigger(pTrigger);
112880       Trigger **pp;
112881       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
112882       *pp = (*pp)->pNext;
112883     }
112884     sqlite3DeleteTrigger(db, pTrigger);
112885     db->flags |= SQLITE_InternChanges;
112886   }
112887 }
112888 
112889 /*
112890 ** pEList is the SET clause of an UPDATE statement.  Each entry
112891 ** in pEList is of the format <id>=<expr>.  If any of the entries
112892 ** in pEList have an <id> which matches an identifier in pIdList,
112893 ** then return TRUE.  If pIdList==NULL, then it is considered a
112894 ** wildcard that matches anything.  Likewise if pEList==NULL then
112895 ** it matches anything so always return true.  Return false only
112896 ** if there is no match.
112897 */
112898 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
112899   int e;
112900   if( pIdList==0 || NEVER(pEList==0) ) return 1;
112901   for(e=0; e<pEList->nExpr; e++){
112902     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
112903   }
112904   return 0;
112905 }
112906 
112907 /*
112908 ** Return a list of all triggers on table pTab if there exists at least
112909 ** one trigger that must be fired when an operation of type 'op' is
112910 ** performed on the table, and, if that operation is an UPDATE, if at
112911 ** least one of the columns in pChanges is being modified.
112912 */
112913 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
112914   Parse *pParse,          /* Parse context */
112915   Table *pTab,            /* The table the contains the triggers */
112916   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
112917   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
112918   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
112919 ){
112920   int mask = 0;
112921   Trigger *pList = 0;
112922   Trigger *p;
112923 
112924   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
112925     pList = sqlite3TriggerList(pParse, pTab);
112926   }
112927   assert( pList==0 || IsVirtual(pTab)==0 );
112928   for(p=pList; p; p=p->pNext){
112929     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
112930       mask |= p->tr_tm;
112931     }
112932   }
112933   if( pMask ){
112934     *pMask = mask;
112935   }
112936   return (mask ? pList : 0);
112937 }
112938 
112939 /*
112940 ** Convert the pStep->zTarget string into a SrcList and return a pointer
112941 ** to that SrcList.
112942 **
112943 ** This routine adds a specific database name, if needed, to the target when
112944 ** forming the SrcList.  This prevents a trigger in one database from
112945 ** referring to a target in another database.  An exception is when the
112946 ** trigger is in TEMP in which case it can refer to any other database it
112947 ** wants.
112948 */
112949 static SrcList *targetSrcList(
112950   Parse *pParse,       /* The parsing context */
112951   TriggerStep *pStep   /* The trigger containing the target token */
112952 ){
112953   sqlite3 *db = pParse->db;
112954   int iDb;             /* Index of the database to use */
112955   SrcList *pSrc;       /* SrcList to be returned */
112956 
112957   pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
112958   if( pSrc ){
112959     assert( pSrc->nSrc>0 );
112960     pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
112961     iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
112962     if( iDb==0 || iDb>=2 ){
112963       assert( iDb<db->nDb );
112964       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
112965     }
112966   }
112967   return pSrc;
112968 }
112969 
112970 /*
112971 ** Generate VDBE code for the statements inside the body of a single
112972 ** trigger.
112973 */
112974 static int codeTriggerProgram(
112975   Parse *pParse,            /* The parser context */
112976   TriggerStep *pStepList,   /* List of statements inside the trigger body */
112977   int orconf                /* Conflict algorithm. (OE_Abort, etc) */
112978 ){
112979   TriggerStep *pStep;
112980   Vdbe *v = pParse->pVdbe;
112981   sqlite3 *db = pParse->db;
112982 
112983   assert( pParse->pTriggerTab && pParse->pToplevel );
112984   assert( pStepList );
112985   assert( v!=0 );
112986   for(pStep=pStepList; pStep; pStep=pStep->pNext){
112987     /* Figure out the ON CONFLICT policy that will be used for this step
112988     ** of the trigger program. If the statement that caused this trigger
112989     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
112990     ** the ON CONFLICT policy that was specified as part of the trigger
112991     ** step statement. Example:
112992     **
112993     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
112994     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
112995     **   END;
112996     **
112997     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
112998     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
112999     */
113000     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
113001     assert( pParse->okConstFactor==0 );
113002 
113003     switch( pStep->op ){
113004       case TK_UPDATE: {
113005         sqlite3Update(pParse,
113006           targetSrcList(pParse, pStep),
113007           sqlite3ExprListDup(db, pStep->pExprList, 0),
113008           sqlite3ExprDup(db, pStep->pWhere, 0),
113009           pParse->eOrconf
113010         );
113011         break;
113012       }
113013       case TK_INSERT: {
113014         sqlite3Insert(pParse,
113015           targetSrcList(pParse, pStep),
113016           sqlite3SelectDup(db, pStep->pSelect, 0),
113017           sqlite3IdListDup(db, pStep->pIdList),
113018           pParse->eOrconf
113019         );
113020         break;
113021       }
113022       case TK_DELETE: {
113023         sqlite3DeleteFrom(pParse,
113024           targetSrcList(pParse, pStep),
113025           sqlite3ExprDup(db, pStep->pWhere, 0)
113026         );
113027         break;
113028       }
113029       default: assert( pStep->op==TK_SELECT ); {
113030         SelectDest sDest;
113031         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
113032         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
113033         sqlite3Select(pParse, pSelect, &sDest);
113034         sqlite3SelectDelete(db, pSelect);
113035         break;
113036       }
113037     }
113038     if( pStep->op!=TK_SELECT ){
113039       sqlite3VdbeAddOp0(v, OP_ResetCount);
113040     }
113041   }
113042 
113043   return 0;
113044 }
113045 
113046 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
113047 /*
113048 ** This function is used to add VdbeComment() annotations to a VDBE
113049 ** program. It is not used in production code, only for debugging.
113050 */
113051 static const char *onErrorText(int onError){
113052   switch( onError ){
113053     case OE_Abort:    return "abort";
113054     case OE_Rollback: return "rollback";
113055     case OE_Fail:     return "fail";
113056     case OE_Replace:  return "replace";
113057     case OE_Ignore:   return "ignore";
113058     case OE_Default:  return "default";
113059   }
113060   return "n/a";
113061 }
113062 #endif
113063 
113064 /*
113065 ** Parse context structure pFrom has just been used to create a sub-vdbe
113066 ** (trigger program). If an error has occurred, transfer error information
113067 ** from pFrom to pTo.
113068 */
113069 static void transferParseError(Parse *pTo, Parse *pFrom){
113070   assert( pFrom->zErrMsg==0 || pFrom->nErr );
113071   assert( pTo->zErrMsg==0 || pTo->nErr );
113072   if( pTo->nErr==0 ){
113073     pTo->zErrMsg = pFrom->zErrMsg;
113074     pTo->nErr = pFrom->nErr;
113075     pTo->rc = pFrom->rc;
113076   }else{
113077     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
113078   }
113079 }
113080 
113081 /*
113082 ** Create and populate a new TriggerPrg object with a sub-program
113083 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
113084 */
113085 static TriggerPrg *codeRowTrigger(
113086   Parse *pParse,       /* Current parse context */
113087   Trigger *pTrigger,   /* Trigger to code */
113088   Table *pTab,         /* The table pTrigger is attached to */
113089   int orconf           /* ON CONFLICT policy to code trigger program with */
113090 ){
113091   Parse *pTop = sqlite3ParseToplevel(pParse);
113092   sqlite3 *db = pParse->db;   /* Database handle */
113093   TriggerPrg *pPrg;           /* Value to return */
113094   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
113095   Vdbe *v;                    /* Temporary VM */
113096   NameContext sNC;            /* Name context for sub-vdbe */
113097   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
113098   Parse *pSubParse;           /* Parse context for sub-vdbe */
113099   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
113100 
113101   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
113102   assert( pTop->pVdbe );
113103 
113104   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
113105   ** are freed if an error occurs, link them into the Parse.pTriggerPrg
113106   ** list of the top-level Parse object sooner rather than later.  */
113107   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
113108   if( !pPrg ) return 0;
113109   pPrg->pNext = pTop->pTriggerPrg;
113110   pTop->pTriggerPrg = pPrg;
113111   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
113112   if( !pProgram ) return 0;
113113   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
113114   pPrg->pTrigger = pTrigger;
113115   pPrg->orconf = orconf;
113116   pPrg->aColmask[0] = 0xffffffff;
113117   pPrg->aColmask[1] = 0xffffffff;
113118 
113119   /* Allocate and populate a new Parse context to use for coding the
113120   ** trigger sub-program.  */
113121   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
113122   if( !pSubParse ) return 0;
113123   memset(&sNC, 0, sizeof(sNC));
113124   sNC.pParse = pSubParse;
113125   pSubParse->db = db;
113126   pSubParse->pTriggerTab = pTab;
113127   pSubParse->pToplevel = pTop;
113128   pSubParse->zAuthContext = pTrigger->zName;
113129   pSubParse->eTriggerOp = pTrigger->op;
113130   pSubParse->nQueryLoop = pParse->nQueryLoop;
113131 
113132   v = sqlite3GetVdbe(pSubParse);
113133   if( v ){
113134     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
113135       pTrigger->zName, onErrorText(orconf),
113136       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
113137         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
113138         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
113139         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
113140       pTab->zName
113141     ));
113142 #ifndef SQLITE_OMIT_TRACE
113143     sqlite3VdbeChangeP4(v, -1,
113144       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
113145     );
113146 #endif
113147 
113148     /* If one was specified, code the WHEN clause. If it evaluates to false
113149     ** (or NULL) the sub-vdbe is immediately halted by jumping to the
113150     ** OP_Halt inserted at the end of the program.  */
113151     if( pTrigger->pWhen ){
113152       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
113153       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
113154        && db->mallocFailed==0
113155       ){
113156         iEndTrigger = sqlite3VdbeMakeLabel(v);
113157         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
113158       }
113159       sqlite3ExprDelete(db, pWhen);
113160     }
113161 
113162     /* Code the trigger program into the sub-vdbe. */
113163     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
113164 
113165     /* Insert an OP_Halt at the end of the sub-program. */
113166     if( iEndTrigger ){
113167       sqlite3VdbeResolveLabel(v, iEndTrigger);
113168     }
113169     sqlite3VdbeAddOp0(v, OP_Halt);
113170     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
113171 
113172     transferParseError(pParse, pSubParse);
113173     if( db->mallocFailed==0 ){
113174       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
113175     }
113176     pProgram->nMem = pSubParse->nMem;
113177     pProgram->nCsr = pSubParse->nTab;
113178     pProgram->nOnce = pSubParse->nOnce;
113179     pProgram->token = (void *)pTrigger;
113180     pPrg->aColmask[0] = pSubParse->oldmask;
113181     pPrg->aColmask[1] = pSubParse->newmask;
113182     sqlite3VdbeDelete(v);
113183   }
113184 
113185   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
113186   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
113187   sqlite3ParserReset(pSubParse);
113188   sqlite3StackFree(db, pSubParse);
113189 
113190   return pPrg;
113191 }
113192 
113193 /*
113194 ** Return a pointer to a TriggerPrg object containing the sub-program for
113195 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
113196 ** TriggerPrg object exists, a new object is allocated and populated before
113197 ** being returned.
113198 */
113199 static TriggerPrg *getRowTrigger(
113200   Parse *pParse,       /* Current parse context */
113201   Trigger *pTrigger,   /* Trigger to code */
113202   Table *pTab,         /* The table trigger pTrigger is attached to */
113203   int orconf           /* ON CONFLICT algorithm. */
113204 ){
113205   Parse *pRoot = sqlite3ParseToplevel(pParse);
113206   TriggerPrg *pPrg;
113207 
113208   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
113209 
113210   /* It may be that this trigger has already been coded (or is in the
113211   ** process of being coded). If this is the case, then an entry with
113212   ** a matching TriggerPrg.pTrigger field will be present somewhere
113213   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
113214   for(pPrg=pRoot->pTriggerPrg;
113215       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
113216       pPrg=pPrg->pNext
113217   );
113218 
113219   /* If an existing TriggerPrg could not be located, create a new one. */
113220   if( !pPrg ){
113221     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
113222   }
113223 
113224   return pPrg;
113225 }
113226 
113227 /*
113228 ** Generate code for the trigger program associated with trigger p on
113229 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
113230 ** function are the same as those described in the header function for
113231 ** sqlite3CodeRowTrigger()
113232 */
113233 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
113234   Parse *pParse,       /* Parse context */
113235   Trigger *p,          /* Trigger to code */
113236   Table *pTab,         /* The table to code triggers from */
113237   int reg,             /* Reg array containing OLD.* and NEW.* values */
113238   int orconf,          /* ON CONFLICT policy */
113239   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
113240 ){
113241   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
113242   TriggerPrg *pPrg;
113243   pPrg = getRowTrigger(pParse, p, pTab, orconf);
113244   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
113245 
113246   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
113247   ** is a pointer to the sub-vdbe containing the trigger program.  */
113248   if( pPrg ){
113249     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
113250 
113251     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
113252     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
113253     VdbeComment(
113254         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
113255 
113256     /* Set the P5 operand of the OP_Program instruction to non-zero if
113257     ** recursive invocation of this trigger program is disallowed. Recursive
113258     ** invocation is disallowed if (a) the sub-program is really a trigger,
113259     ** not a foreign key action, and (b) the flag to enable recursive triggers
113260     ** is clear.  */
113261     sqlite3VdbeChangeP5(v, (u8)bRecursive);
113262   }
113263 }
113264 
113265 /*
113266 ** This is called to code the required FOR EACH ROW triggers for an operation
113267 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
113268 ** is given by the op parameter. The tr_tm parameter determines whether the
113269 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
113270 ** parameter pChanges is passed the list of columns being modified.
113271 **
113272 ** If there are no triggers that fire at the specified time for the specified
113273 ** operation on pTab, this function is a no-op.
113274 **
113275 ** The reg argument is the address of the first in an array of registers
113276 ** that contain the values substituted for the new.* and old.* references
113277 ** in the trigger program. If N is the number of columns in table pTab
113278 ** (a copy of pTab->nCol), then registers are populated as follows:
113279 **
113280 **   Register       Contains
113281 **   ------------------------------------------------------
113282 **   reg+0          OLD.rowid
113283 **   reg+1          OLD.* value of left-most column of pTab
113284 **   ...            ...
113285 **   reg+N          OLD.* value of right-most column of pTab
113286 **   reg+N+1        NEW.rowid
113287 **   reg+N+2        OLD.* value of left-most column of pTab
113288 **   ...            ...
113289 **   reg+N+N+1      NEW.* value of right-most column of pTab
113290 **
113291 ** For ON DELETE triggers, the registers containing the NEW.* values will
113292 ** never be accessed by the trigger program, so they are not allocated or
113293 ** populated by the caller (there is no data to populate them with anyway).
113294 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
113295 ** are never accessed, and so are not allocated by the caller. So, for an
113296 ** ON INSERT trigger, the value passed to this function as parameter reg
113297 ** is not a readable register, although registers (reg+N) through
113298 ** (reg+N+N+1) are.
113299 **
113300 ** Parameter orconf is the default conflict resolution algorithm for the
113301 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
113302 ** is the instruction that control should jump to if a trigger program
113303 ** raises an IGNORE exception.
113304 */
113305 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
113306   Parse *pParse,       /* Parse context */
113307   Trigger *pTrigger,   /* List of triggers on table pTab */
113308   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
113309   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
113310   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
113311   Table *pTab,         /* The table to code triggers from */
113312   int reg,             /* The first in an array of registers (see above) */
113313   int orconf,          /* ON CONFLICT policy */
113314   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
113315 ){
113316   Trigger *p;          /* Used to iterate through pTrigger list */
113317 
113318   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
113319   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
113320   assert( (op==TK_UPDATE)==(pChanges!=0) );
113321 
113322   for(p=pTrigger; p; p=p->pNext){
113323 
113324     /* Sanity checking:  The schema for the trigger and for the table are
113325     ** always defined.  The trigger must be in the same schema as the table
113326     ** or else it must be a TEMP trigger. */
113327     assert( p->pSchema!=0 );
113328     assert( p->pTabSchema!=0 );
113329     assert( p->pSchema==p->pTabSchema
113330          || p->pSchema==pParse->db->aDb[1].pSchema );
113331 
113332     /* Determine whether we should code this trigger */
113333     if( p->op==op
113334      && p->tr_tm==tr_tm
113335      && checkColumnOverlap(p->pColumns, pChanges)
113336     ){
113337       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
113338     }
113339   }
113340 }
113341 
113342 /*
113343 ** Triggers may access values stored in the old.* or new.* pseudo-table.
113344 ** This function returns a 32-bit bitmask indicating which columns of the
113345 ** old.* or new.* tables actually are used by triggers. This information
113346 ** may be used by the caller, for example, to avoid having to load the entire
113347 ** old.* record into memory when executing an UPDATE or DELETE command.
113348 **
113349 ** Bit 0 of the returned mask is set if the left-most column of the
113350 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
113351 ** the second leftmost column value is required, and so on. If there
113352 ** are more than 32 columns in the table, and at least one of the columns
113353 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
113354 **
113355 ** It is not possible to determine if the old.rowid or new.rowid column is
113356 ** accessed by triggers. The caller must always assume that it is.
113357 **
113358 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
113359 ** applies to the old.* table. If 1, the new.* table.
113360 **
113361 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
113362 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
113363 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
113364 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
113365 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
113366 */
113367 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
113368   Parse *pParse,       /* Parse context */
113369   Trigger *pTrigger,   /* List of triggers on table pTab */
113370   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
113371   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
113372   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
113373   Table *pTab,         /* The table to code triggers from */
113374   int orconf           /* Default ON CONFLICT policy for trigger steps */
113375 ){
113376   const int op = pChanges ? TK_UPDATE : TK_DELETE;
113377   u32 mask = 0;
113378   Trigger *p;
113379 
113380   assert( isNew==1 || isNew==0 );
113381   for(p=pTrigger; p; p=p->pNext){
113382     if( p->op==op && (tr_tm&p->tr_tm)
113383      && checkColumnOverlap(p->pColumns,pChanges)
113384     ){
113385       TriggerPrg *pPrg;
113386       pPrg = getRowTrigger(pParse, p, pTab, orconf);
113387       if( pPrg ){
113388         mask |= pPrg->aColmask[isNew];
113389       }
113390     }
113391   }
113392 
113393   return mask;
113394 }
113395 
113396 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
113397 
113398 /************** End of trigger.c *********************************************/
113399 /************** Begin file update.c ******************************************/
113400 /*
113401 ** 2001 September 15
113402 **
113403 ** The author disclaims copyright to this source code.  In place of
113404 ** a legal notice, here is a blessing:
113405 **
113406 **    May you do good and not evil.
113407 **    May you find forgiveness for yourself and forgive others.
113408 **    May you share freely, never taking more than you give.
113409 **
113410 *************************************************************************
113411 ** This file contains C code routines that are called by the parser
113412 ** to handle UPDATE statements.
113413 */
113414 
113415 #ifndef SQLITE_OMIT_VIRTUALTABLE
113416 /* Forward declaration */
113417 static void updateVirtualTable(
113418   Parse *pParse,       /* The parsing context */
113419   SrcList *pSrc,       /* The virtual table to be modified */
113420   Table *pTab,         /* The virtual table */
113421   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
113422   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
113423   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
113424   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
113425   int onError          /* ON CONFLICT strategy */
113426 );
113427 #endif /* SQLITE_OMIT_VIRTUALTABLE */
113428 
113429 /*
113430 ** The most recently coded instruction was an OP_Column to retrieve the
113431 ** i-th column of table pTab. This routine sets the P4 parameter of the
113432 ** OP_Column to the default value, if any.
113433 **
113434 ** The default value of a column is specified by a DEFAULT clause in the
113435 ** column definition. This was either supplied by the user when the table
113436 ** was created, or added later to the table definition by an ALTER TABLE
113437 ** command. If the latter, then the row-records in the table btree on disk
113438 ** may not contain a value for the column and the default value, taken
113439 ** from the P4 parameter of the OP_Column instruction, is returned instead.
113440 ** If the former, then all row-records are guaranteed to include a value
113441 ** for the column and the P4 value is not required.
113442 **
113443 ** Column definitions created by an ALTER TABLE command may only have
113444 ** literal default values specified: a number, null or a string. (If a more
113445 ** complicated default expression value was provided, it is evaluated
113446 ** when the ALTER TABLE is executed and one of the literal values written
113447 ** into the sqlite_master table.)
113448 **
113449 ** Therefore, the P4 parameter is only required if the default value for
113450 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
113451 ** function is capable of transforming these types of expressions into
113452 ** sqlite3_value objects.
113453 **
113454 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
113455 ** on register iReg. This is used when an equivalent integer value is
113456 ** stored in place of an 8-byte floating point value in order to save
113457 ** space.
113458 */
113459 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
113460   assert( pTab!=0 );
113461   if( !pTab->pSelect ){
113462     sqlite3_value *pValue = 0;
113463     u8 enc = ENC(sqlite3VdbeDb(v));
113464     Column *pCol = &pTab->aCol[i];
113465     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
113466     assert( i<pTab->nCol );
113467     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
113468                          pCol->affinity, &pValue);
113469     if( pValue ){
113470       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
113471     }
113472 #ifndef SQLITE_OMIT_FLOATING_POINT
113473     if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
113474       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
113475     }
113476 #endif
113477   }
113478 }
113479 
113480 /*
113481 ** Process an UPDATE statement.
113482 **
113483 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
113484 **          \_______/ \________/     \______/       \________________/
113485 *            onError   pTabList      pChanges             pWhere
113486 */
113487 SQLITE_PRIVATE void sqlite3Update(
113488   Parse *pParse,         /* The parser context */
113489   SrcList *pTabList,     /* The table in which we should change things */
113490   ExprList *pChanges,    /* Things to be changed */
113491   Expr *pWhere,          /* The WHERE clause.  May be null */
113492   int onError            /* How to handle constraint errors */
113493 ){
113494   int i, j;              /* Loop counters */
113495   Table *pTab;           /* The table to be updated */
113496   int addrTop = 0;       /* VDBE instruction address of the start of the loop */
113497   WhereInfo *pWInfo;     /* Information about the WHERE clause */
113498   Vdbe *v;               /* The virtual database engine */
113499   Index *pIdx;           /* For looping over indices */
113500   Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
113501   int nIdx;              /* Number of indices that need updating */
113502   int iBaseCur;          /* Base cursor number */
113503   int iDataCur;          /* Cursor for the canonical data btree */
113504   int iIdxCur;           /* Cursor for the first index */
113505   sqlite3 *db;           /* The database structure */
113506   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
113507   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
113508                          ** an expression for the i-th column of the table.
113509                          ** aXRef[i]==-1 if the i-th column is not changed. */
113510   u8 *aToOpen;           /* 1 for tables and indices to be opened */
113511   u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
113512   u8 chngRowid;          /* Rowid changed in a normal table */
113513   u8 chngKey;            /* Either chngPk or chngRowid */
113514   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
113515   AuthContext sContext;  /* The authorization context */
113516   NameContext sNC;       /* The name-context to resolve expressions in */
113517   int iDb;               /* Database containing the table being updated */
113518   int okOnePass;         /* True for one-pass algorithm without the FIFO */
113519   int hasFK;             /* True if foreign key processing is required */
113520   int labelBreak;        /* Jump here to break out of UPDATE loop */
113521   int labelContinue;     /* Jump here to continue next step of UPDATE loop */
113522 
113523 #ifndef SQLITE_OMIT_TRIGGER
113524   int isView;            /* True when updating a view (INSTEAD OF trigger) */
113525   Trigger *pTrigger;     /* List of triggers on pTab, if required */
113526   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
113527 #endif
113528   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
113529   int iEph = 0;          /* Ephemeral table holding all primary key values */
113530   int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
113531   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
113532 
113533   /* Register Allocations */
113534   int regRowCount = 0;   /* A count of rows changed */
113535   int regOldRowid;       /* The old rowid */
113536   int regNewRowid;       /* The new rowid */
113537   int regNew;            /* Content of the NEW.* table in triggers */
113538   int regOld = 0;        /* Content of OLD.* table in triggers */
113539   int regRowSet = 0;     /* Rowset of rows to be updated */
113540   int regKey = 0;        /* composite PRIMARY KEY value */
113541 
113542   memset(&sContext, 0, sizeof(sContext));
113543   db = pParse->db;
113544   if( pParse->nErr || db->mallocFailed ){
113545     goto update_cleanup;
113546   }
113547   assert( pTabList->nSrc==1 );
113548 
113549   /* Locate the table which we want to update.
113550   */
113551   pTab = sqlite3SrcListLookup(pParse, pTabList);
113552   if( pTab==0 ) goto update_cleanup;
113553   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
113554 
113555   /* Figure out if we have any triggers and if the table being
113556   ** updated is a view.
113557   */
113558 #ifndef SQLITE_OMIT_TRIGGER
113559   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
113560   isView = pTab->pSelect!=0;
113561   assert( pTrigger || tmask==0 );
113562 #else
113563 # define pTrigger 0
113564 # define isView 0
113565 # define tmask 0
113566 #endif
113567 #ifdef SQLITE_OMIT_VIEW
113568 # undef isView
113569 # define isView 0
113570 #endif
113571 
113572   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
113573     goto update_cleanup;
113574   }
113575   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
113576     goto update_cleanup;
113577   }
113578 
113579   /* Allocate a cursors for the main database table and for all indices.
113580   ** The index cursors might not be used, but if they are used they
113581   ** need to occur right after the database cursor.  So go ahead and
113582   ** allocate enough space, just in case.
113583   */
113584   pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
113585   iIdxCur = iDataCur+1;
113586   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
113587   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
113588     if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
113589       iDataCur = pParse->nTab;
113590       pTabList->a[0].iCursor = iDataCur;
113591     }
113592     pParse->nTab++;
113593   }
113594 
113595   /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
113596   ** Initialize aXRef[] and aToOpen[] to their default values.
113597   */
113598   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
113599   if( aXRef==0 ) goto update_cleanup;
113600   aRegIdx = aXRef+pTab->nCol;
113601   aToOpen = (u8*)(aRegIdx+nIdx);
113602   memset(aToOpen, 1, nIdx+1);
113603   aToOpen[nIdx+1] = 0;
113604   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
113605 
113606   /* Initialize the name-context */
113607   memset(&sNC, 0, sizeof(sNC));
113608   sNC.pParse = pParse;
113609   sNC.pSrcList = pTabList;
113610 
113611   /* Resolve the column names in all the expressions of the
113612   ** of the UPDATE statement.  Also find the column index
113613   ** for each column to be updated in the pChanges array.  For each
113614   ** column to be updated, make sure we have authorization to change
113615   ** that column.
113616   */
113617   chngRowid = chngPk = 0;
113618   for(i=0; i<pChanges->nExpr; i++){
113619     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
113620       goto update_cleanup;
113621     }
113622     for(j=0; j<pTab->nCol; j++){
113623       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
113624         if( j==pTab->iPKey ){
113625           chngRowid = 1;
113626           pRowidExpr = pChanges->a[i].pExpr;
113627         }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
113628           chngPk = 1;
113629         }
113630         aXRef[j] = i;
113631         break;
113632       }
113633     }
113634     if( j>=pTab->nCol ){
113635       if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
113636         j = -1;
113637         chngRowid = 1;
113638         pRowidExpr = pChanges->a[i].pExpr;
113639       }else{
113640         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
113641         pParse->checkSchema = 1;
113642         goto update_cleanup;
113643       }
113644     }
113645 #ifndef SQLITE_OMIT_AUTHORIZATION
113646     {
113647       int rc;
113648       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
113649                             j<0 ? "ROWID" : pTab->aCol[j].zName,
113650                             db->aDb[iDb].zName);
113651       if( rc==SQLITE_DENY ){
113652         goto update_cleanup;
113653       }else if( rc==SQLITE_IGNORE ){
113654         aXRef[j] = -1;
113655       }
113656     }
113657 #endif
113658   }
113659   assert( (chngRowid & chngPk)==0 );
113660   assert( chngRowid==0 || chngRowid==1 );
113661   assert( chngPk==0 || chngPk==1 );
113662   chngKey = chngRowid + chngPk;
113663 
113664   /* The SET expressions are not actually used inside the WHERE loop.
113665   ** So reset the colUsed mask
113666   */
113667   pTabList->a[0].colUsed = 0;
113668 
113669   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
113670 
113671   /* There is one entry in the aRegIdx[] array for each index on the table
113672   ** being updated.  Fill in aRegIdx[] with a register number that will hold
113673   ** the key for accessing each index.
113674   */
113675   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
113676     int reg;
113677     if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
113678       reg = ++pParse->nMem;
113679     }else{
113680       reg = 0;
113681       for(i=0; i<pIdx->nKeyCol; i++){
113682         if( aXRef[pIdx->aiColumn[i]]>=0 ){
113683           reg = ++pParse->nMem;
113684           break;
113685         }
113686       }
113687     }
113688     if( reg==0 ) aToOpen[j+1] = 0;
113689     aRegIdx[j] = reg;
113690   }
113691 
113692   /* Begin generating code. */
113693   v = sqlite3GetVdbe(pParse);
113694   if( v==0 ) goto update_cleanup;
113695   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
113696   sqlite3BeginWriteOperation(pParse, 1, iDb);
113697 
113698 #ifndef SQLITE_OMIT_VIRTUALTABLE
113699   /* Virtual tables must be handled separately */
113700   if( IsVirtual(pTab) ){
113701     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
113702                        pWhere, onError);
113703     pWhere = 0;
113704     pTabList = 0;
113705     goto update_cleanup;
113706   }
113707 #endif
113708 
113709   /* Allocate required registers. */
113710   regRowSet = ++pParse->nMem;
113711   regOldRowid = regNewRowid = ++pParse->nMem;
113712   if( chngPk || pTrigger || hasFK ){
113713     regOld = pParse->nMem + 1;
113714     pParse->nMem += pTab->nCol;
113715   }
113716   if( chngKey || pTrigger || hasFK ){
113717     regNewRowid = ++pParse->nMem;
113718   }
113719   regNew = pParse->nMem + 1;
113720   pParse->nMem += pTab->nCol;
113721 
113722   /* Start the view context. */
113723   if( isView ){
113724     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
113725   }
113726 
113727   /* If we are trying to update a view, realize that view into
113728   ** an ephemeral table.
113729   */
113730 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
113731   if( isView ){
113732     sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
113733   }
113734 #endif
113735 
113736   /* Resolve the column names in all the expressions in the
113737   ** WHERE clause.
113738   */
113739   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
113740     goto update_cleanup;
113741   }
113742 
113743   /* Begin the database scan
113744   */
113745   if( HasRowid(pTab) ){
113746     sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
113747     pWInfo = sqlite3WhereBegin(
113748         pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
113749     );
113750     if( pWInfo==0 ) goto update_cleanup;
113751     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
113752 
113753     /* Remember the rowid of every item to be updated.
113754     */
113755     sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
113756     if( !okOnePass ){
113757       sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
113758     }
113759 
113760     /* End the database scan loop.
113761     */
113762     sqlite3WhereEnd(pWInfo);
113763   }else{
113764     int iPk;         /* First of nPk memory cells holding PRIMARY KEY value */
113765     i16 nPk;         /* Number of components of the PRIMARY KEY */
113766     int addrOpen;    /* Address of the OpenEphemeral instruction */
113767 
113768     assert( pPk!=0 );
113769     nPk = pPk->nKeyCol;
113770     iPk = pParse->nMem+1;
113771     pParse->nMem += nPk;
113772     regKey = ++pParse->nMem;
113773     iEph = pParse->nTab++;
113774     sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
113775     addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
113776     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
113777     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
113778                                WHERE_ONEPASS_DESIRED, iIdxCur);
113779     if( pWInfo==0 ) goto update_cleanup;
113780     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
113781     for(i=0; i<nPk; i++){
113782       sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
113783                                       iPk+i);
113784     }
113785     if( okOnePass ){
113786       sqlite3VdbeChangeToNoop(v, addrOpen);
113787       nKey = nPk;
113788       regKey = iPk;
113789     }else{
113790       sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
113791                         sqlite3IndexAffinityStr(v, pPk), nPk);
113792       sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
113793     }
113794     sqlite3WhereEnd(pWInfo);
113795   }
113796 
113797   /* Initialize the count of updated rows
113798   */
113799   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
113800     regRowCount = ++pParse->nMem;
113801     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
113802   }
113803 
113804   labelBreak = sqlite3VdbeMakeLabel(v);
113805   if( !isView ){
113806     /*
113807     ** Open every index that needs updating.  Note that if any
113808     ** index could potentially invoke a REPLACE conflict resolution
113809     ** action, then we need to open all indices because we might need
113810     ** to be deleting some records.
113811     */
113812     if( onError==OE_Replace ){
113813       memset(aToOpen, 1, nIdx+1);
113814     }else{
113815       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
113816         if( pIdx->onError==OE_Replace ){
113817           memset(aToOpen, 1, nIdx+1);
113818           break;
113819         }
113820       }
113821     }
113822     if( okOnePass ){
113823       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
113824       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
113825     }
113826     sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
113827                                0, 0);
113828   }
113829 
113830   /* Top of the update loop */
113831   if( okOnePass ){
113832     if( aToOpen[iDataCur-iBaseCur] && !isView ){
113833       assert( pPk );
113834       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
113835       VdbeCoverageNeverTaken(v);
113836     }
113837     labelContinue = labelBreak;
113838     sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
113839     VdbeCoverageIf(v, pPk==0);
113840     VdbeCoverageIf(v, pPk!=0);
113841   }else if( pPk ){
113842     labelContinue = sqlite3VdbeMakeLabel(v);
113843     sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
113844     addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
113845     sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
113846     VdbeCoverage(v);
113847   }else{
113848     labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
113849                              regOldRowid);
113850     VdbeCoverage(v);
113851     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
113852     VdbeCoverage(v);
113853   }
113854 
113855   /* If the record number will change, set register regNewRowid to
113856   ** contain the new value. If the record number is not being modified,
113857   ** then regNewRowid is the same register as regOldRowid, which is
113858   ** already populated.  */
113859   assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
113860   if( chngRowid ){
113861     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
113862     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
113863   }
113864 
113865   /* Compute the old pre-UPDATE content of the row being changed, if that
113866   ** information is needed */
113867   if( chngPk || hasFK || pTrigger ){
113868     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
113869     oldmask |= sqlite3TriggerColmask(pParse,
113870         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
113871     );
113872     for(i=0; i<pTab->nCol; i++){
113873       if( oldmask==0xffffffff
113874        || (i<32 && (oldmask & MASKBIT32(i))!=0)
113875        || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
113876       ){
113877         testcase(  oldmask!=0xffffffff && i==31 );
113878         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
113879       }else{
113880         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
113881       }
113882     }
113883     if( chngRowid==0 && pPk==0 ){
113884       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
113885     }
113886   }
113887 
113888   /* Populate the array of registers beginning at regNew with the new
113889   ** row data. This array is used to check constants, create the new
113890   ** table and index records, and as the values for any new.* references
113891   ** made by triggers.
113892   **
113893   ** If there are one or more BEFORE triggers, then do not populate the
113894   ** registers associated with columns that are (a) not modified by
113895   ** this UPDATE statement and (b) not accessed by new.* references. The
113896   ** values for registers not modified by the UPDATE must be reloaded from
113897   ** the database after the BEFORE triggers are fired anyway (as the trigger
113898   ** may have modified them). So not loading those that are not going to
113899   ** be used eliminates some redundant opcodes.
113900   */
113901   newmask = sqlite3TriggerColmask(
113902       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
113903   );
113904   /*sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);*/
113905   for(i=0; i<pTab->nCol; i++){
113906     if( i==pTab->iPKey ){
113907       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
113908     }else{
113909       j = aXRef[i];
113910       if( j>=0 ){
113911         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
113912       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
113913         /* This branch loads the value of a column that will not be changed
113914         ** into a register. This is done if there are no BEFORE triggers, or
113915         ** if there are one or more BEFORE triggers that use this value via
113916         ** a new.* reference in a trigger program.
113917         */
113918         testcase( i==31 );
113919         testcase( i==32 );
113920         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
113921       }else{
113922         sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
113923       }
113924     }
113925   }
113926 
113927   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
113928   ** verified. One could argue that this is wrong.
113929   */
113930   if( tmask&TRIGGER_BEFORE ){
113931     sqlite3TableAffinity(v, pTab, regNew);
113932     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
113933         TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
113934 
113935     /* The row-trigger may have deleted the row being updated. In this
113936     ** case, jump to the next row. No updates or AFTER triggers are
113937     ** required. This behavior - what happens when the row being updated
113938     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
113939     ** documentation.
113940     */
113941     if( pPk ){
113942       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
113943       VdbeCoverage(v);
113944     }else{
113945       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
113946       VdbeCoverage(v);
113947     }
113948 
113949     /* If it did not delete it, the row-trigger may still have modified
113950     ** some of the columns of the row being updated. Load the values for
113951     ** all columns not modified by the update statement into their
113952     ** registers in case this has happened.
113953     */
113954     for(i=0; i<pTab->nCol; i++){
113955       if( aXRef[i]<0 && i!=pTab->iPKey ){
113956         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
113957       }
113958     }
113959   }
113960 
113961   if( !isView ){
113962     int j1 = 0;           /* Address of jump instruction */
113963     int bReplace = 0;     /* True if REPLACE conflict resolution might happen */
113964 
113965     /* Do constraint checks. */
113966     assert( regOldRowid>0 );
113967     sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
113968         regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
113969 
113970     /* Do FK constraint checks. */
113971     if( hasFK ){
113972       sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
113973     }
113974 
113975     /* Delete the index entries associated with the current record.  */
113976     if( bReplace || chngKey ){
113977       if( pPk ){
113978         j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
113979       }else{
113980         j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
113981       }
113982       VdbeCoverageNeverTaken(v);
113983     }
113984     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
113985 
113986     /* If changing the record number, delete the old record.  */
113987     if( hasFK || chngKey || pPk!=0 ){
113988       sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
113989     }
113990     if( bReplace || chngKey ){
113991       sqlite3VdbeJumpHere(v, j1);
113992     }
113993 
113994     if( hasFK ){
113995       sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
113996     }
113997 
113998     /* Insert the new index entries and the new record. */
113999     sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
114000                              regNewRowid, aRegIdx, 1, 0, 0);
114001 
114002     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
114003     ** handle rows (possibly in other tables) that refer via a foreign key
114004     ** to the row just updated. */
114005     if( hasFK ){
114006       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
114007     }
114008   }
114009 
114010   /* Increment the row counter
114011   */
114012   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
114013     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
114014   }
114015 
114016   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
114017       TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
114018 
114019   /* Repeat the above with the next record to be updated, until
114020   ** all record selected by the WHERE clause have been updated.
114021   */
114022   if( okOnePass ){
114023     /* Nothing to do at end-of-loop for a single-pass */
114024   }else if( pPk ){
114025     sqlite3VdbeResolveLabel(v, labelContinue);
114026     sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
114027   }else{
114028     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue);
114029   }
114030   sqlite3VdbeResolveLabel(v, labelBreak);
114031 
114032   /* Close all tables */
114033   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
114034     assert( aRegIdx );
114035     if( aToOpen[i+1] ){
114036       sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
114037     }
114038   }
114039   if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
114040 
114041   /* Update the sqlite_sequence table by storing the content of the
114042   ** maximum rowid counter values recorded while inserting into
114043   ** autoincrement tables.
114044   */
114045   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
114046     sqlite3AutoincrementEnd(pParse);
114047   }
114048 
114049   /*
114050   ** Return the number of rows that were changed. If this routine is
114051   ** generating code because of a call to sqlite3NestedParse(), do not
114052   ** invoke the callback function.
114053   */
114054   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
114055     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
114056     sqlite3VdbeSetNumCols(v, 1);
114057     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
114058   }
114059 
114060 update_cleanup:
114061   sqlite3AuthContextPop(&sContext);
114062   sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
114063   sqlite3SrcListDelete(db, pTabList);
114064   sqlite3ExprListDelete(db, pChanges);
114065   sqlite3ExprDelete(db, pWhere);
114066   return;
114067 }
114068 /* Make sure "isView" and other macros defined above are undefined. Otherwise
114069 ** they may interfere with compilation of other functions in this file
114070 ** (or in another file, if this file becomes part of the amalgamation).  */
114071 #ifdef isView
114072  #undef isView
114073 #endif
114074 #ifdef pTrigger
114075  #undef pTrigger
114076 #endif
114077 
114078 #ifndef SQLITE_OMIT_VIRTUALTABLE
114079 /*
114080 ** Generate code for an UPDATE of a virtual table.
114081 **
114082 ** The strategy is that we create an ephemeral table that contains
114083 ** for each row to be changed:
114084 **
114085 **   (A)  The original rowid of that row.
114086 **   (B)  The revised rowid for the row. (note1)
114087 **   (C)  The content of every column in the row.
114088 **
114089 ** Then we loop over this ephemeral table and for each row in
114090 ** the ephemeral table call VUpdate.
114091 **
114092 ** When finished, drop the ephemeral table.
114093 **
114094 ** (note1) Actually, if we know in advance that (A) is always the same
114095 ** as (B) we only store (A), then duplicate (A) when pulling
114096 ** it out of the ephemeral table before calling VUpdate.
114097 */
114098 static void updateVirtualTable(
114099   Parse *pParse,       /* The parsing context */
114100   SrcList *pSrc,       /* The virtual table to be modified */
114101   Table *pTab,         /* The virtual table */
114102   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
114103   Expr *pRowid,        /* Expression used to recompute the rowid */
114104   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
114105   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
114106   int onError          /* ON CONFLICT strategy */
114107 ){
114108   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
114109   ExprList *pEList = 0;     /* The result set of the SELECT statement */
114110   Select *pSelect = 0;      /* The SELECT statement */
114111   Expr *pExpr;              /* Temporary expression */
114112   int ephemTab;             /* Table holding the result of the SELECT */
114113   int i;                    /* Loop counter */
114114   int addr;                 /* Address of top of loop */
114115   int iReg;                 /* First register in set passed to OP_VUpdate */
114116   sqlite3 *db = pParse->db; /* Database connection */
114117   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
114118   SelectDest dest;
114119 
114120   /* Construct the SELECT statement that will find the new values for
114121   ** all updated rows.
114122   */
114123   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
114124   if( pRowid ){
114125     pEList = sqlite3ExprListAppend(pParse, pEList,
114126                                    sqlite3ExprDup(db, pRowid, 0));
114127   }
114128   assert( pTab->iPKey<0 );
114129   for(i=0; i<pTab->nCol; i++){
114130     if( aXRef[i]>=0 ){
114131       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
114132     }else{
114133       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
114134     }
114135     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
114136   }
114137   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
114138 
114139   /* Create the ephemeral table into which the update results will
114140   ** be stored.
114141   */
114142   assert( v );
114143   ephemTab = pParse->nTab++;
114144   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
114145   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
114146 
114147   /* fill the ephemeral table
114148   */
114149   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
114150   sqlite3Select(pParse, pSelect, &dest);
114151 
114152   /* Generate code to scan the ephemeral table and call VUpdate. */
114153   iReg = ++pParse->nMem;
114154   pParse->nMem += pTab->nCol+1;
114155   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); VdbeCoverage(v);
114156   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
114157   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
114158   for(i=0; i<pTab->nCol; i++){
114159     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
114160   }
114161   sqlite3VtabMakeWritable(pParse, pTab);
114162   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
114163   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
114164   sqlite3MayAbort(pParse);
114165   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
114166   sqlite3VdbeJumpHere(v, addr);
114167   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
114168 
114169   /* Cleanup */
114170   sqlite3SelectDelete(db, pSelect);
114171 }
114172 #endif /* SQLITE_OMIT_VIRTUALTABLE */
114173 
114174 /************** End of update.c **********************************************/
114175 /************** Begin file vacuum.c ******************************************/
114176 /*
114177 ** 2003 April 6
114178 **
114179 ** The author disclaims copyright to this source code.  In place of
114180 ** a legal notice, here is a blessing:
114181 **
114182 **    May you do good and not evil.
114183 **    May you find forgiveness for yourself and forgive others.
114184 **    May you share freely, never taking more than you give.
114185 **
114186 *************************************************************************
114187 ** This file contains code used to implement the VACUUM command.
114188 **
114189 ** Most of the code in this file may be omitted by defining the
114190 ** SQLITE_OMIT_VACUUM macro.
114191 */
114192 
114193 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
114194 /*
114195 ** Finalize a prepared statement.  If there was an error, store the
114196 ** text of the error message in *pzErrMsg.  Return the result code.
114197 */
114198 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
114199   int rc;
114200   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
114201   if( rc ){
114202     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
114203   }
114204   return rc;
114205 }
114206 
114207 /*
114208 ** Execute zSql on database db. Return an error code.
114209 */
114210 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
114211   sqlite3_stmt *pStmt;
114212   VVA_ONLY( int rc; )
114213   if( !zSql ){
114214     return SQLITE_NOMEM;
114215   }
114216   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
114217     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
114218     return sqlite3_errcode(db);
114219   }
114220   VVA_ONLY( rc = ) sqlite3_step(pStmt);
114221   assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
114222   return vacuumFinalize(db, pStmt, pzErrMsg);
114223 }
114224 
114225 /*
114226 ** Execute zSql on database db. The statement returns exactly
114227 ** one column. Execute this as SQL on the same database.
114228 */
114229 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
114230   sqlite3_stmt *pStmt;
114231   int rc;
114232 
114233   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
114234   if( rc!=SQLITE_OK ) return rc;
114235 
114236   while( SQLITE_ROW==sqlite3_step(pStmt) ){
114237     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
114238     if( rc!=SQLITE_OK ){
114239       vacuumFinalize(db, pStmt, pzErrMsg);
114240       return rc;
114241     }
114242   }
114243 
114244   return vacuumFinalize(db, pStmt, pzErrMsg);
114245 }
114246 
114247 /*
114248 ** The VACUUM command is used to clean up the database,
114249 ** collapse free space, etc.  It is modelled after the VACUUM command
114250 ** in PostgreSQL.  The VACUUM command works as follows:
114251 **
114252 **   (1)  Create a new transient database file
114253 **   (2)  Copy all content from the database being vacuumed into
114254 **        the new transient database file
114255 **   (3)  Copy content from the transient database back into the
114256 **        original database.
114257 **
114258 ** The transient database requires temporary disk space approximately
114259 ** equal to the size of the original database.  The copy operation of
114260 ** step (3) requires additional temporary disk space approximately equal
114261 ** to the size of the original database for the rollback journal.
114262 ** Hence, temporary disk space that is approximately 2x the size of the
114263 ** original database is required.  Every page of the database is written
114264 ** approximately 3 times:  Once for step (2) and twice for step (3).
114265 ** Two writes per page are required in step (3) because the original
114266 ** database content must be written into the rollback journal prior to
114267 ** overwriting the database with the vacuumed content.
114268 **
114269 ** Only 1x temporary space and only 1x writes would be required if
114270 ** the copy of step (3) were replaced by deleting the original database
114271 ** and renaming the transient database as the original.  But that will
114272 ** not work if other processes are attached to the original database.
114273 ** And a power loss in between deleting the original and renaming the
114274 ** transient would cause the database file to appear to be deleted
114275 ** following reboot.
114276 */
114277 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
114278   Vdbe *v = sqlite3GetVdbe(pParse);
114279   if( v ){
114280     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
114281     sqlite3VdbeUsesBtree(v, 0);
114282   }
114283   return;
114284 }
114285 
114286 /*
114287 ** This routine implements the OP_Vacuum opcode of the VDBE.
114288 */
114289 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
114290   int rc = SQLITE_OK;     /* Return code from service routines */
114291   Btree *pMain;           /* The database being vacuumed */
114292   Btree *pTemp;           /* The temporary database we vacuum into */
114293   char *zSql = 0;         /* SQL statements */
114294   int saved_flags;        /* Saved value of the db->flags */
114295   int saved_nChange;      /* Saved value of db->nChange */
114296   int saved_nTotalChange; /* Saved value of db->nTotalChange */
114297   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
114298   Db *pDb = 0;            /* Database to detach at end of vacuum */
114299   int isMemDb;            /* True if vacuuming a :memory: database */
114300   int nRes;               /* Bytes of reserved space at the end of each page */
114301   int nDb;                /* Number of attached databases */
114302 
114303   if( !db->autoCommit ){
114304     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
114305     return SQLITE_ERROR;
114306   }
114307   if( db->nVdbeActive>1 ){
114308     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
114309     return SQLITE_ERROR;
114310   }
114311 
114312   /* Save the current value of the database flags so that it can be
114313   ** restored before returning. Then set the writable-schema flag, and
114314   ** disable CHECK and foreign key constraints.  */
114315   saved_flags = db->flags;
114316   saved_nChange = db->nChange;
114317   saved_nTotalChange = db->nTotalChange;
114318   saved_xTrace = db->xTrace;
114319   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
114320   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
114321   db->xTrace = 0;
114322 
114323   pMain = db->aDb[0].pBt;
114324   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
114325 
114326   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
114327   ** can be set to 'off' for this file, as it is not recovered if a crash
114328   ** occurs anyway. The integrity of the database is maintained by a
114329   ** (possibly synchronous) transaction opened on the main database before
114330   ** sqlite3BtreeCopyFile() is called.
114331   **
114332   ** An optimisation would be to use a non-journaled pager.
114333   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
114334   ** that actually made the VACUUM run slower.  Very little journalling
114335   ** actually occurs when doing a vacuum since the vacuum_db is initially
114336   ** empty.  Only the journal header is written.  Apparently it takes more
114337   ** time to parse and run the PRAGMA to turn journalling off than it does
114338   ** to write the journal header file.
114339   */
114340   nDb = db->nDb;
114341   if( sqlite3TempInMemory(db) ){
114342     zSql = "ATTACH ':memory:' AS vacuum_db;";
114343   }else{
114344     zSql = "ATTACH '' AS vacuum_db;";
114345   }
114346   rc = execSql(db, pzErrMsg, zSql);
114347   if( db->nDb>nDb ){
114348     pDb = &db->aDb[db->nDb-1];
114349     assert( strcmp(pDb->zName,"vacuum_db")==0 );
114350   }
114351   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114352   pTemp = db->aDb[db->nDb-1].pBt;
114353 
114354   /* The call to execSql() to attach the temp database has left the file
114355   ** locked (as there was more than one active statement when the transaction
114356   ** to read the schema was concluded. Unlock it here so that this doesn't
114357   ** cause problems for the call to BtreeSetPageSize() below.  */
114358   sqlite3BtreeCommit(pTemp);
114359 
114360   nRes = sqlite3BtreeGetOptimalReserve(pMain);
114361 
114362   /* A VACUUM cannot change the pagesize of an encrypted database. */
114363 #ifdef SQLITE_HAS_CODEC
114364   if( db->nextPagesize ){
114365     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
114366     int nKey;
114367     char *zKey;
114368     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
114369     if( nKey ) db->nextPagesize = 0;
114370   }
114371 #endif
114372 
114373   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
114374   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114375 
114376   /* Begin a transaction and take an exclusive lock on the main database
114377   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
114378   ** to ensure that we do not try to change the page-size on a WAL database.
114379   */
114380   rc = execSql(db, pzErrMsg, "BEGIN;");
114381   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114382   rc = sqlite3BtreeBeginTrans(pMain, 2);
114383   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114384 
114385   /* Do not attempt to change the page size for a WAL database */
114386   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
114387                                                ==PAGER_JOURNALMODE_WAL ){
114388     db->nextPagesize = 0;
114389   }
114390 
114391   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
114392    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
114393    || NEVER(db->mallocFailed)
114394   ){
114395     rc = SQLITE_NOMEM;
114396     goto end_of_vacuum;
114397   }
114398 
114399 #ifndef SQLITE_OMIT_AUTOVACUUM
114400   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
114401                                            sqlite3BtreeGetAutoVacuum(pMain));
114402 #endif
114403 
114404   /* Query the schema of the main database. Create a mirror schema
114405   ** in the temporary database.
114406   */
114407   rc = execExecSql(db, pzErrMsg,
114408       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
114409       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
114410       "   AND coalesce(rootpage,1)>0"
114411   );
114412   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114413   rc = execExecSql(db, pzErrMsg,
114414       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
114415       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
114416   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114417   rc = execExecSql(db, pzErrMsg,
114418       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
114419       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
114420   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114421 
114422   /* Loop through the tables in the main database. For each, do
114423   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
114424   ** the contents to the temporary database.
114425   */
114426   assert( (db->flags & SQLITE_Vacuum)==0 );
114427   db->flags |= SQLITE_Vacuum;
114428   rc = execExecSql(db, pzErrMsg,
114429       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
114430       "|| ' SELECT * FROM main.' || quote(name) || ';'"
114431       "FROM main.sqlite_master "
114432       "WHERE type = 'table' AND name!='sqlite_sequence' "
114433       "  AND coalesce(rootpage,1)>0"
114434   );
114435   assert( (db->flags & SQLITE_Vacuum)!=0 );
114436   db->flags &= ~SQLITE_Vacuum;
114437   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114438 
114439   /* Copy over the sequence table
114440   */
114441   rc = execExecSql(db, pzErrMsg,
114442       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
114443       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
114444   );
114445   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114446   rc = execExecSql(db, pzErrMsg,
114447       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
114448       "|| ' SELECT * FROM main.' || quote(name) || ';' "
114449       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
114450   );
114451   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114452 
114453 
114454   /* Copy the triggers, views, and virtual tables from the main database
114455   ** over to the temporary database.  None of these objects has any
114456   ** associated storage, so all we have to do is copy their entries
114457   ** from the SQLITE_MASTER table.
114458   */
114459   rc = execSql(db, pzErrMsg,
114460       "INSERT INTO vacuum_db.sqlite_master "
114461       "  SELECT type, name, tbl_name, rootpage, sql"
114462       "    FROM main.sqlite_master"
114463       "   WHERE type='view' OR type='trigger'"
114464       "      OR (type='table' AND rootpage=0)"
114465   );
114466   if( rc ) goto end_of_vacuum;
114467 
114468   /* At this point, there is a write transaction open on both the
114469   ** vacuum database and the main database. Assuming no error occurs,
114470   ** both transactions are closed by this block - the main database
114471   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
114472   ** call to sqlite3BtreeCommit().
114473   */
114474   {
114475     u32 meta;
114476     int i;
114477 
114478     /* This array determines which meta meta values are preserved in the
114479     ** vacuum.  Even entries are the meta value number and odd entries
114480     ** are an increment to apply to the meta value after the vacuum.
114481     ** The increment is used to increase the schema cookie so that other
114482     ** connections to the same database will know to reread the schema.
114483     */
114484     static const unsigned char aCopy[] = {
114485        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
114486        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
114487        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
114488        BTREE_USER_VERSION,       0,  /* Preserve the user version */
114489        BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
114490     };
114491 
114492     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
114493     assert( 1==sqlite3BtreeIsInTrans(pMain) );
114494 
114495     /* Copy Btree meta values */
114496     for(i=0; i<ArraySize(aCopy); i+=2){
114497       /* GetMeta() and UpdateMeta() cannot fail in this context because
114498       ** we already have page 1 loaded into cache and marked dirty. */
114499       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
114500       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
114501       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
114502     }
114503 
114504     rc = sqlite3BtreeCopyFile(pMain, pTemp);
114505     if( rc!=SQLITE_OK ) goto end_of_vacuum;
114506     rc = sqlite3BtreeCommit(pTemp);
114507     if( rc!=SQLITE_OK ) goto end_of_vacuum;
114508 #ifndef SQLITE_OMIT_AUTOVACUUM
114509     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
114510 #endif
114511   }
114512 
114513   assert( rc==SQLITE_OK );
114514   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
114515 
114516 end_of_vacuum:
114517   /* Restore the original value of db->flags */
114518   db->flags = saved_flags;
114519   db->nChange = saved_nChange;
114520   db->nTotalChange = saved_nTotalChange;
114521   db->xTrace = saved_xTrace;
114522   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
114523 
114524   /* Currently there is an SQL level transaction open on the vacuum
114525   ** database. No locks are held on any other files (since the main file
114526   ** was committed at the btree level). So it safe to end the transaction
114527   ** by manually setting the autoCommit flag to true and detaching the
114528   ** vacuum database. The vacuum_db journal file is deleted when the pager
114529   ** is closed by the DETACH.
114530   */
114531   db->autoCommit = 1;
114532 
114533   if( pDb ){
114534     sqlite3BtreeClose(pDb->pBt);
114535     pDb->pBt = 0;
114536     pDb->pSchema = 0;
114537   }
114538 
114539   /* This both clears the schemas and reduces the size of the db->aDb[]
114540   ** array. */
114541   sqlite3ResetAllSchemasOfConnection(db);
114542 
114543   return rc;
114544 }
114545 
114546 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
114547 
114548 /************** End of vacuum.c **********************************************/
114549 /************** Begin file vtab.c ********************************************/
114550 /*
114551 ** 2006 June 10
114552 **
114553 ** The author disclaims copyright to this source code.  In place of
114554 ** a legal notice, here is a blessing:
114555 **
114556 **    May you do good and not evil.
114557 **    May you find forgiveness for yourself and forgive others.
114558 **    May you share freely, never taking more than you give.
114559 **
114560 *************************************************************************
114561 ** This file contains code used to help implement virtual tables.
114562 */
114563 #ifndef SQLITE_OMIT_VIRTUALTABLE
114564 
114565 /*
114566 ** Before a virtual table xCreate() or xConnect() method is invoked, the
114567 ** sqlite3.pVtabCtx member variable is set to point to an instance of
114568 ** this struct allocated on the stack. It is used by the implementation of
114569 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
114570 ** are invoked only from within xCreate and xConnect methods.
114571 */
114572 struct VtabCtx {
114573   VTable *pVTable;    /* The virtual table being constructed */
114574   Table *pTab;        /* The Table object to which the virtual table belongs */
114575   VtabCtx *pPrior;    /* Parent context (if any) */
114576   int bDeclared;      /* True after sqlite3_declare_vtab() is called */
114577 };
114578 
114579 /*
114580 ** The actual function that does the work of creating a new module.
114581 ** This function implements the sqlite3_create_module() and
114582 ** sqlite3_create_module_v2() interfaces.
114583 */
114584 static int createModule(
114585   sqlite3 *db,                    /* Database in which module is registered */
114586   const char *zName,              /* Name assigned to this module */
114587   const sqlite3_module *pModule,  /* The definition of the module */
114588   void *pAux,                     /* Context pointer for xCreate/xConnect */
114589   void (*xDestroy)(void *)        /* Module destructor function */
114590 ){
114591   int rc = SQLITE_OK;
114592   int nName;
114593 
114594   sqlite3_mutex_enter(db->mutex);
114595   nName = sqlite3Strlen30(zName);
114596   if( sqlite3HashFind(&db->aModule, zName) ){
114597     rc = SQLITE_MISUSE_BKPT;
114598   }else{
114599     Module *pMod;
114600     pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
114601     if( pMod ){
114602       Module *pDel;
114603       char *zCopy = (char *)(&pMod[1]);
114604       memcpy(zCopy, zName, nName+1);
114605       pMod->zName = zCopy;
114606       pMod->pModule = pModule;
114607       pMod->pAux = pAux;
114608       pMod->xDestroy = xDestroy;
114609       pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
114610       assert( pDel==0 || pDel==pMod );
114611       if( pDel ){
114612         db->mallocFailed = 1;
114613         sqlite3DbFree(db, pDel);
114614       }
114615     }
114616   }
114617   rc = sqlite3ApiExit(db, rc);
114618   if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
114619 
114620   sqlite3_mutex_leave(db->mutex);
114621   return rc;
114622 }
114623 
114624 
114625 /*
114626 ** External API function used to create a new virtual-table module.
114627 */
114628 SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
114629   sqlite3 *db,                    /* Database in which module is registered */
114630   const char *zName,              /* Name assigned to this module */
114631   const sqlite3_module *pModule,  /* The definition of the module */
114632   void *pAux                      /* Context pointer for xCreate/xConnect */
114633 ){
114634 #ifdef SQLITE_ENABLE_API_ARMOR
114635   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
114636 #endif
114637   return createModule(db, zName, pModule, pAux, 0);
114638 }
114639 
114640 /*
114641 ** External API function used to create a new virtual-table module.
114642 */
114643 SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
114644   sqlite3 *db,                    /* Database in which module is registered */
114645   const char *zName,              /* Name assigned to this module */
114646   const sqlite3_module *pModule,  /* The definition of the module */
114647   void *pAux,                     /* Context pointer for xCreate/xConnect */
114648   void (*xDestroy)(void *)        /* Module destructor function */
114649 ){
114650 #ifdef SQLITE_ENABLE_API_ARMOR
114651   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
114652 #endif
114653   return createModule(db, zName, pModule, pAux, xDestroy);
114654 }
114655 
114656 /*
114657 ** Lock the virtual table so that it cannot be disconnected.
114658 ** Locks nest.  Every lock should have a corresponding unlock.
114659 ** If an unlock is omitted, resources leaks will occur.
114660 **
114661 ** If a disconnect is attempted while a virtual table is locked,
114662 ** the disconnect is deferred until all locks have been removed.
114663 */
114664 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
114665   pVTab->nRef++;
114666 }
114667 
114668 
114669 /*
114670 ** pTab is a pointer to a Table structure representing a virtual-table.
114671 ** Return a pointer to the VTable object used by connection db to access
114672 ** this virtual-table, if one has been created, or NULL otherwise.
114673 */
114674 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
114675   VTable *pVtab;
114676   assert( IsVirtual(pTab) );
114677   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
114678   return pVtab;
114679 }
114680 
114681 /*
114682 ** Decrement the ref-count on a virtual table object. When the ref-count
114683 ** reaches zero, call the xDisconnect() method to delete the object.
114684 */
114685 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
114686   sqlite3 *db = pVTab->db;
114687 
114688   assert( db );
114689   assert( pVTab->nRef>0 );
114690   assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
114691 
114692   pVTab->nRef--;
114693   if( pVTab->nRef==0 ){
114694     sqlite3_vtab *p = pVTab->pVtab;
114695     if( p ){
114696       p->pModule->xDisconnect(p);
114697     }
114698     sqlite3DbFree(db, pVTab);
114699   }
114700 }
114701 
114702 /*
114703 ** Table p is a virtual table. This function moves all elements in the
114704 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
114705 ** database connections to be disconnected at the next opportunity.
114706 ** Except, if argument db is not NULL, then the entry associated with
114707 ** connection db is left in the p->pVTable list.
114708 */
114709 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
114710   VTable *pRet = 0;
114711   VTable *pVTable = p->pVTable;
114712   p->pVTable = 0;
114713 
114714   /* Assert that the mutex (if any) associated with the BtShared database
114715   ** that contains table p is held by the caller. See header comments
114716   ** above function sqlite3VtabUnlockList() for an explanation of why
114717   ** this makes it safe to access the sqlite3.pDisconnect list of any
114718   ** database connection that may have an entry in the p->pVTable list.
114719   */
114720   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
114721 
114722   while( pVTable ){
114723     sqlite3 *db2 = pVTable->db;
114724     VTable *pNext = pVTable->pNext;
114725     assert( db2 );
114726     if( db2==db ){
114727       pRet = pVTable;
114728       p->pVTable = pRet;
114729       pRet->pNext = 0;
114730     }else{
114731       pVTable->pNext = db2->pDisconnect;
114732       db2->pDisconnect = pVTable;
114733     }
114734     pVTable = pNext;
114735   }
114736 
114737   assert( !db || pRet );
114738   return pRet;
114739 }
114740 
114741 /*
114742 ** Table *p is a virtual table. This function removes the VTable object
114743 ** for table *p associated with database connection db from the linked
114744 ** list in p->pVTab. It also decrements the VTable ref count. This is
114745 ** used when closing database connection db to free all of its VTable
114746 ** objects without disturbing the rest of the Schema object (which may
114747 ** be being used by other shared-cache connections).
114748 */
114749 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
114750   VTable **ppVTab;
114751 
114752   assert( IsVirtual(p) );
114753   assert( sqlite3BtreeHoldsAllMutexes(db) );
114754   assert( sqlite3_mutex_held(db->mutex) );
114755 
114756   for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
114757     if( (*ppVTab)->db==db  ){
114758       VTable *pVTab = *ppVTab;
114759       *ppVTab = pVTab->pNext;
114760       sqlite3VtabUnlock(pVTab);
114761       break;
114762     }
114763   }
114764 }
114765 
114766 
114767 /*
114768 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
114769 **
114770 ** This function may only be called when the mutexes associated with all
114771 ** shared b-tree databases opened using connection db are held by the
114772 ** caller. This is done to protect the sqlite3.pDisconnect list. The
114773 ** sqlite3.pDisconnect list is accessed only as follows:
114774 **
114775 **   1) By this function. In this case, all BtShared mutexes and the mutex
114776 **      associated with the database handle itself must be held.
114777 **
114778 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
114779 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
114780 **      associated with the database the virtual table is stored in is held
114781 **      or, if the virtual table is stored in a non-sharable database, then
114782 **      the database handle mutex is held.
114783 **
114784 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
114785 ** by multiple threads. It is thread-safe.
114786 */
114787 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
114788   VTable *p = db->pDisconnect;
114789   db->pDisconnect = 0;
114790 
114791   assert( sqlite3BtreeHoldsAllMutexes(db) );
114792   assert( sqlite3_mutex_held(db->mutex) );
114793 
114794   if( p ){
114795     sqlite3ExpirePreparedStatements(db);
114796     do {
114797       VTable *pNext = p->pNext;
114798       sqlite3VtabUnlock(p);
114799       p = pNext;
114800     }while( p );
114801   }
114802 }
114803 
114804 /*
114805 ** Clear any and all virtual-table information from the Table record.
114806 ** This routine is called, for example, just before deleting the Table
114807 ** record.
114808 **
114809 ** Since it is a virtual-table, the Table structure contains a pointer
114810 ** to the head of a linked list of VTable structures. Each VTable
114811 ** structure is associated with a single sqlite3* user of the schema.
114812 ** The reference count of the VTable structure associated with database
114813 ** connection db is decremented immediately (which may lead to the
114814 ** structure being xDisconnected and free). Any other VTable structures
114815 ** in the list are moved to the sqlite3.pDisconnect list of the associated
114816 ** database connection.
114817 */
114818 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
114819   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
114820   if( p->azModuleArg ){
114821     int i;
114822     for(i=0; i<p->nModuleArg; i++){
114823       if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
114824     }
114825     sqlite3DbFree(db, p->azModuleArg);
114826   }
114827 }
114828 
114829 /*
114830 ** Add a new module argument to pTable->azModuleArg[].
114831 ** The string is not copied - the pointer is stored.  The
114832 ** string will be freed automatically when the table is
114833 ** deleted.
114834 */
114835 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
114836   int i = pTable->nModuleArg++;
114837   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
114838   char **azModuleArg;
114839   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
114840   if( azModuleArg==0 ){
114841     int j;
114842     for(j=0; j<i; j++){
114843       sqlite3DbFree(db, pTable->azModuleArg[j]);
114844     }
114845     sqlite3DbFree(db, zArg);
114846     sqlite3DbFree(db, pTable->azModuleArg);
114847     pTable->nModuleArg = 0;
114848   }else{
114849     azModuleArg[i] = zArg;
114850     azModuleArg[i+1] = 0;
114851   }
114852   pTable->azModuleArg = azModuleArg;
114853 }
114854 
114855 /*
114856 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
114857 ** statement.  The module name has been parsed, but the optional list
114858 ** of parameters that follow the module name are still pending.
114859 */
114860 SQLITE_PRIVATE void sqlite3VtabBeginParse(
114861   Parse *pParse,        /* Parsing context */
114862   Token *pName1,        /* Name of new table, or database name */
114863   Token *pName2,        /* Name of new table or NULL */
114864   Token *pModuleName,   /* Name of the module for the virtual table */
114865   int ifNotExists       /* No error if the table already exists */
114866 ){
114867   int iDb;              /* The database the table is being created in */
114868   Table *pTable;        /* The new virtual table */
114869   sqlite3 *db;          /* Database connection */
114870 
114871   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
114872   pTable = pParse->pNewTable;
114873   if( pTable==0 ) return;
114874   assert( 0==pTable->pIndex );
114875 
114876   db = pParse->db;
114877   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
114878   assert( iDb>=0 );
114879 
114880   pTable->tabFlags |= TF_Virtual;
114881   pTable->nModuleArg = 0;
114882   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
114883   addModuleArgument(db, pTable, 0);
114884   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
114885   assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
114886        || (pParse->sNameToken.z==pName1->z && pName2->z==0)
114887   );
114888   pParse->sNameToken.n = (int)(
114889       &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
114890   );
114891 
114892 #ifndef SQLITE_OMIT_AUTHORIZATION
114893   /* Creating a virtual table invokes the authorization callback twice.
114894   ** The first invocation, to obtain permission to INSERT a row into the
114895   ** sqlite_master table, has already been made by sqlite3StartTable().
114896   ** The second call, to obtain permission to create the table, is made now.
114897   */
114898   if( pTable->azModuleArg ){
114899     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
114900             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
114901   }
114902 #endif
114903 }
114904 
114905 /*
114906 ** This routine takes the module argument that has been accumulating
114907 ** in pParse->zArg[] and appends it to the list of arguments on the
114908 ** virtual table currently under construction in pParse->pTable.
114909 */
114910 static void addArgumentToVtab(Parse *pParse){
114911   if( pParse->sArg.z && pParse->pNewTable ){
114912     const char *z = (const char*)pParse->sArg.z;
114913     int n = pParse->sArg.n;
114914     sqlite3 *db = pParse->db;
114915     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
114916   }
114917 }
114918 
114919 /*
114920 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
114921 ** has been completely parsed.
114922 */
114923 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
114924   Table *pTab = pParse->pNewTable;  /* The table being constructed */
114925   sqlite3 *db = pParse->db;         /* The database connection */
114926 
114927   if( pTab==0 ) return;
114928   addArgumentToVtab(pParse);
114929   pParse->sArg.z = 0;
114930   if( pTab->nModuleArg<1 ) return;
114931 
114932   /* If the CREATE VIRTUAL TABLE statement is being entered for the
114933   ** first time (in other words if the virtual table is actually being
114934   ** created now instead of just being read out of sqlite_master) then
114935   ** do additional initialization work and store the statement text
114936   ** in the sqlite_master table.
114937   */
114938   if( !db->init.busy ){
114939     char *zStmt;
114940     char *zWhere;
114941     int iDb;
114942     int iReg;
114943     Vdbe *v;
114944 
114945     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
114946     if( pEnd ){
114947       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
114948     }
114949     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
114950 
114951     /* A slot for the record has already been allocated in the
114952     ** SQLITE_MASTER table.  We just need to update that slot with all
114953     ** the information we've collected.
114954     **
114955     ** The VM register number pParse->regRowid holds the rowid of an
114956     ** entry in the sqlite_master table tht was created for this vtab
114957     ** by sqlite3StartTable().
114958     */
114959     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
114960     sqlite3NestedParse(pParse,
114961       "UPDATE %Q.%s "
114962          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
114963        "WHERE rowid=#%d",
114964       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
114965       pTab->zName,
114966       pTab->zName,
114967       zStmt,
114968       pParse->regRowid
114969     );
114970     sqlite3DbFree(db, zStmt);
114971     v = sqlite3GetVdbe(pParse);
114972     sqlite3ChangeCookie(pParse, iDb);
114973 
114974     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
114975     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
114976     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
114977 
114978     iReg = ++pParse->nMem;
114979     sqlite3VdbeAddOp4(v, OP_String8, 0, iReg, 0, pTab->zName, 0);
114980     sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
114981   }
114982 
114983   /* If we are rereading the sqlite_master table create the in-memory
114984   ** record of the table. The xConnect() method is not called until
114985   ** the first time the virtual table is used in an SQL statement. This
114986   ** allows a schema that contains virtual tables to be loaded before
114987   ** the required virtual table implementations are registered.  */
114988   else {
114989     Table *pOld;
114990     Schema *pSchema = pTab->pSchema;
114991     const char *zName = pTab->zName;
114992     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
114993     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
114994     if( pOld ){
114995       db->mallocFailed = 1;
114996       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
114997       return;
114998     }
114999     pParse->pNewTable = 0;
115000   }
115001 }
115002 
115003 /*
115004 ** The parser calls this routine when it sees the first token
115005 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
115006 */
115007 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
115008   addArgumentToVtab(pParse);
115009   pParse->sArg.z = 0;
115010   pParse->sArg.n = 0;
115011 }
115012 
115013 /*
115014 ** The parser calls this routine for each token after the first token
115015 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
115016 */
115017 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
115018   Token *pArg = &pParse->sArg;
115019   if( pArg->z==0 ){
115020     pArg->z = p->z;
115021     pArg->n = p->n;
115022   }else{
115023     assert(pArg->z <= p->z);
115024     pArg->n = (int)(&p->z[p->n] - pArg->z);
115025   }
115026 }
115027 
115028 /*
115029 ** Invoke a virtual table constructor (either xCreate or xConnect). The
115030 ** pointer to the function to invoke is passed as the fourth parameter
115031 ** to this procedure.
115032 */
115033 static int vtabCallConstructor(
115034   sqlite3 *db,
115035   Table *pTab,
115036   Module *pMod,
115037   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
115038   char **pzErr
115039 ){
115040   VtabCtx sCtx;
115041   VTable *pVTable;
115042   int rc;
115043   const char *const*azArg = (const char *const*)pTab->azModuleArg;
115044   int nArg = pTab->nModuleArg;
115045   char *zErr = 0;
115046   char *zModuleName;
115047   int iDb;
115048   VtabCtx *pCtx;
115049 
115050   /* Check that the virtual-table is not already being initialized */
115051   for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
115052     if( pCtx->pTab==pTab ){
115053       *pzErr = sqlite3MPrintf(db,
115054           "vtable constructor called recursively: %s", pTab->zName
115055       );
115056       return SQLITE_LOCKED;
115057     }
115058   }
115059 
115060   zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
115061   if( !zModuleName ){
115062     return SQLITE_NOMEM;
115063   }
115064 
115065   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
115066   if( !pVTable ){
115067     sqlite3DbFree(db, zModuleName);
115068     return SQLITE_NOMEM;
115069   }
115070   pVTable->db = db;
115071   pVTable->pMod = pMod;
115072 
115073   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
115074   pTab->azModuleArg[1] = db->aDb[iDb].zName;
115075 
115076   /* Invoke the virtual table constructor */
115077   assert( &db->pVtabCtx );
115078   assert( xConstruct );
115079   sCtx.pTab = pTab;
115080   sCtx.pVTable = pVTable;
115081   sCtx.pPrior = db->pVtabCtx;
115082   sCtx.bDeclared = 0;
115083   db->pVtabCtx = &sCtx;
115084   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
115085   db->pVtabCtx = sCtx.pPrior;
115086   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
115087   assert( sCtx.pTab==pTab );
115088 
115089   if( SQLITE_OK!=rc ){
115090     if( zErr==0 ){
115091       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
115092     }else {
115093       *pzErr = sqlite3MPrintf(db, "%s", zErr);
115094       sqlite3_free(zErr);
115095     }
115096     sqlite3DbFree(db, pVTable);
115097   }else if( ALWAYS(pVTable->pVtab) ){
115098     /* Justification of ALWAYS():  A correct vtab constructor must allocate
115099     ** the sqlite3_vtab object if successful.  */
115100     memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
115101     pVTable->pVtab->pModule = pMod->pModule;
115102     pVTable->nRef = 1;
115103     if( sCtx.bDeclared==0 ){
115104       const char *zFormat = "vtable constructor did not declare schema: %s";
115105       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
115106       sqlite3VtabUnlock(pVTable);
115107       rc = SQLITE_ERROR;
115108     }else{
115109       int iCol;
115110       u8 oooHidden = 0;
115111       /* If everything went according to plan, link the new VTable structure
115112       ** into the linked list headed by pTab->pVTable. Then loop through the
115113       ** columns of the table to see if any of them contain the token "hidden".
115114       ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
115115       ** the type string.  */
115116       pVTable->pNext = pTab->pVTable;
115117       pTab->pVTable = pVTable;
115118 
115119       for(iCol=0; iCol<pTab->nCol; iCol++){
115120         char *zType = pTab->aCol[iCol].zType;
115121         int nType;
115122         int i = 0;
115123         if( !zType ){
115124           pTab->tabFlags |= oooHidden;
115125           continue;
115126         }
115127         nType = sqlite3Strlen30(zType);
115128         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
115129           for(i=0; i<nType; i++){
115130             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
115131              && (zType[i+7]=='\0' || zType[i+7]==' ')
115132             ){
115133               i++;
115134               break;
115135             }
115136           }
115137         }
115138         if( i<nType ){
115139           int j;
115140           int nDel = 6 + (zType[i+6] ? 1 : 0);
115141           for(j=i; (j+nDel)<=nType; j++){
115142             zType[j] = zType[j+nDel];
115143           }
115144           if( zType[i]=='\0' && i>0 ){
115145             assert(zType[i-1]==' ');
115146             zType[i-1] = '\0';
115147           }
115148           pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
115149           oooHidden = TF_OOOHidden;
115150         }else{
115151           pTab->tabFlags |= oooHidden;
115152         }
115153       }
115154     }
115155   }
115156 
115157   sqlite3DbFree(db, zModuleName);
115158   return rc;
115159 }
115160 
115161 /*
115162 ** This function is invoked by the parser to call the xConnect() method
115163 ** of the virtual table pTab. If an error occurs, an error code is returned
115164 ** and an error left in pParse.
115165 **
115166 ** This call is a no-op if table pTab is not a virtual table.
115167 */
115168 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
115169   sqlite3 *db = pParse->db;
115170   const char *zMod;
115171   Module *pMod;
115172   int rc;
115173 
115174   assert( pTab );
115175   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
115176     return SQLITE_OK;
115177   }
115178 
115179   /* Locate the required virtual table module */
115180   zMod = pTab->azModuleArg[0];
115181   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
115182 
115183   if( !pMod ){
115184     const char *zModule = pTab->azModuleArg[0];
115185     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
115186     rc = SQLITE_ERROR;
115187   }else{
115188     char *zErr = 0;
115189     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
115190     if( rc!=SQLITE_OK ){
115191       sqlite3ErrorMsg(pParse, "%s", zErr);
115192     }
115193     sqlite3DbFree(db, zErr);
115194   }
115195 
115196   return rc;
115197 }
115198 /*
115199 ** Grow the db->aVTrans[] array so that there is room for at least one
115200 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
115201 */
115202 static int growVTrans(sqlite3 *db){
115203   const int ARRAY_INCR = 5;
115204 
115205   /* Grow the sqlite3.aVTrans array if required */
115206   if( (db->nVTrans%ARRAY_INCR)==0 ){
115207     VTable **aVTrans;
115208     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
115209     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
115210     if( !aVTrans ){
115211       return SQLITE_NOMEM;
115212     }
115213     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
115214     db->aVTrans = aVTrans;
115215   }
115216 
115217   return SQLITE_OK;
115218 }
115219 
115220 /*
115221 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
115222 ** have already been reserved using growVTrans().
115223 */
115224 static void addToVTrans(sqlite3 *db, VTable *pVTab){
115225   /* Add pVtab to the end of sqlite3.aVTrans */
115226   db->aVTrans[db->nVTrans++] = pVTab;
115227   sqlite3VtabLock(pVTab);
115228 }
115229 
115230 /*
115231 ** This function is invoked by the vdbe to call the xCreate method
115232 ** of the virtual table named zTab in database iDb.
115233 **
115234 ** If an error occurs, *pzErr is set to point an an English language
115235 ** description of the error and an SQLITE_XXX error code is returned.
115236 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
115237 */
115238 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
115239   int rc = SQLITE_OK;
115240   Table *pTab;
115241   Module *pMod;
115242   const char *zMod;
115243 
115244   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
115245   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
115246 
115247   /* Locate the required virtual table module */
115248   zMod = pTab->azModuleArg[0];
115249   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
115250 
115251   /* If the module has been registered and includes a Create method,
115252   ** invoke it now. If the module has not been registered, return an
115253   ** error. Otherwise, do nothing.
115254   */
115255   if( !pMod ){
115256     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
115257     rc = SQLITE_ERROR;
115258   }else{
115259     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
115260   }
115261 
115262   /* Justification of ALWAYS():  The xConstructor method is required to
115263   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
115264   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
115265     rc = growVTrans(db);
115266     if( rc==SQLITE_OK ){
115267       addToVTrans(db, sqlite3GetVTable(db, pTab));
115268     }
115269   }
115270 
115271   return rc;
115272 }
115273 
115274 /*
115275 ** This function is used to set the schema of a virtual table.  It is only
115276 ** valid to call this function from within the xCreate() or xConnect() of a
115277 ** virtual table module.
115278 */
115279 SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
115280   VtabCtx *pCtx;
115281   Parse *pParse;
115282   int rc = SQLITE_OK;
115283   Table *pTab;
115284   char *zErr = 0;
115285 
115286 #ifdef SQLITE_ENABLE_API_ARMOR
115287   if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
115288     return SQLITE_MISUSE_BKPT;
115289   }
115290 #endif
115291   sqlite3_mutex_enter(db->mutex);
115292   pCtx = db->pVtabCtx;
115293   if( !pCtx || pCtx->bDeclared ){
115294     sqlite3Error(db, SQLITE_MISUSE);
115295     sqlite3_mutex_leave(db->mutex);
115296     return SQLITE_MISUSE_BKPT;
115297   }
115298   pTab = pCtx->pTab;
115299   assert( (pTab->tabFlags & TF_Virtual)!=0 );
115300 
115301   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
115302   if( pParse==0 ){
115303     rc = SQLITE_NOMEM;
115304   }else{
115305     pParse->declareVtab = 1;
115306     pParse->db = db;
115307     pParse->nQueryLoop = 1;
115308 
115309     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
115310      && pParse->pNewTable
115311      && !db->mallocFailed
115312      && !pParse->pNewTable->pSelect
115313      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
115314     ){
115315       if( !pTab->aCol ){
115316         pTab->aCol = pParse->pNewTable->aCol;
115317         pTab->nCol = pParse->pNewTable->nCol;
115318         pParse->pNewTable->nCol = 0;
115319         pParse->pNewTable->aCol = 0;
115320       }
115321       pCtx->bDeclared = 1;
115322     }else{
115323       sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
115324       sqlite3DbFree(db, zErr);
115325       rc = SQLITE_ERROR;
115326     }
115327     pParse->declareVtab = 0;
115328 
115329     if( pParse->pVdbe ){
115330       sqlite3VdbeFinalize(pParse->pVdbe);
115331     }
115332     sqlite3DeleteTable(db, pParse->pNewTable);
115333     sqlite3ParserReset(pParse);
115334     sqlite3StackFree(db, pParse);
115335   }
115336 
115337   assert( (rc&0xff)==rc );
115338   rc = sqlite3ApiExit(db, rc);
115339   sqlite3_mutex_leave(db->mutex);
115340   return rc;
115341 }
115342 
115343 /*
115344 ** This function is invoked by the vdbe to call the xDestroy method
115345 ** of the virtual table named zTab in database iDb. This occurs
115346 ** when a DROP TABLE is mentioned.
115347 **
115348 ** This call is a no-op if zTab is not a virtual table.
115349 */
115350 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
115351   int rc = SQLITE_OK;
115352   Table *pTab;
115353 
115354   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
115355   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
115356     VTable *p;
115357     for(p=pTab->pVTable; p; p=p->pNext){
115358       assert( p->pVtab );
115359       if( p->pVtab->nRef>0 ){
115360         return SQLITE_LOCKED;
115361       }
115362     }
115363     p = vtabDisconnectAll(db, pTab);
115364     rc = p->pMod->pModule->xDestroy(p->pVtab);
115365     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
115366     if( rc==SQLITE_OK ){
115367       assert( pTab->pVTable==p && p->pNext==0 );
115368       p->pVtab = 0;
115369       pTab->pVTable = 0;
115370       sqlite3VtabUnlock(p);
115371     }
115372   }
115373 
115374   return rc;
115375 }
115376 
115377 /*
115378 ** This function invokes either the xRollback or xCommit method
115379 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
115380 ** called is identified by the second argument, "offset", which is
115381 ** the offset of the method to call in the sqlite3_module structure.
115382 **
115383 ** The array is cleared after invoking the callbacks.
115384 */
115385 static void callFinaliser(sqlite3 *db, int offset){
115386   int i;
115387   if( db->aVTrans ){
115388     for(i=0; i<db->nVTrans; i++){
115389       VTable *pVTab = db->aVTrans[i];
115390       sqlite3_vtab *p = pVTab->pVtab;
115391       if( p ){
115392         int (*x)(sqlite3_vtab *);
115393         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
115394         if( x ) x(p);
115395       }
115396       pVTab->iSavepoint = 0;
115397       sqlite3VtabUnlock(pVTab);
115398     }
115399     sqlite3DbFree(db, db->aVTrans);
115400     db->nVTrans = 0;
115401     db->aVTrans = 0;
115402   }
115403 }
115404 
115405 /*
115406 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
115407 ** array. Return the error code for the first error that occurs, or
115408 ** SQLITE_OK if all xSync operations are successful.
115409 **
115410 ** If an error message is available, leave it in p->zErrMsg.
115411 */
115412 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
115413   int i;
115414   int rc = SQLITE_OK;
115415   VTable **aVTrans = db->aVTrans;
115416 
115417   db->aVTrans = 0;
115418   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
115419     int (*x)(sqlite3_vtab *);
115420     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
115421     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
115422       rc = x(pVtab);
115423       sqlite3VtabImportErrmsg(p, pVtab);
115424     }
115425   }
115426   db->aVTrans = aVTrans;
115427   return rc;
115428 }
115429 
115430 /*
115431 ** Invoke the xRollback method of all virtual tables in the
115432 ** sqlite3.aVTrans array. Then clear the array itself.
115433 */
115434 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
115435   callFinaliser(db, offsetof(sqlite3_module,xRollback));
115436   return SQLITE_OK;
115437 }
115438 
115439 /*
115440 ** Invoke the xCommit method of all virtual tables in the
115441 ** sqlite3.aVTrans array. Then clear the array itself.
115442 */
115443 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
115444   callFinaliser(db, offsetof(sqlite3_module,xCommit));
115445   return SQLITE_OK;
115446 }
115447 
115448 /*
115449 ** If the virtual table pVtab supports the transaction interface
115450 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
115451 ** not currently open, invoke the xBegin method now.
115452 **
115453 ** If the xBegin call is successful, place the sqlite3_vtab pointer
115454 ** in the sqlite3.aVTrans array.
115455 */
115456 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
115457   int rc = SQLITE_OK;
115458   const sqlite3_module *pModule;
115459 
115460   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
115461   ** than zero, then this function is being called from within a
115462   ** virtual module xSync() callback. It is illegal to write to
115463   ** virtual module tables in this case, so return SQLITE_LOCKED.
115464   */
115465   if( sqlite3VtabInSync(db) ){
115466     return SQLITE_LOCKED;
115467   }
115468   if( !pVTab ){
115469     return SQLITE_OK;
115470   }
115471   pModule = pVTab->pVtab->pModule;
115472 
115473   if( pModule->xBegin ){
115474     int i;
115475 
115476     /* If pVtab is already in the aVTrans array, return early */
115477     for(i=0; i<db->nVTrans; i++){
115478       if( db->aVTrans[i]==pVTab ){
115479         return SQLITE_OK;
115480       }
115481     }
115482 
115483     /* Invoke the xBegin method. If successful, add the vtab to the
115484     ** sqlite3.aVTrans[] array. */
115485     rc = growVTrans(db);
115486     if( rc==SQLITE_OK ){
115487       rc = pModule->xBegin(pVTab->pVtab);
115488       if( rc==SQLITE_OK ){
115489         addToVTrans(db, pVTab);
115490       }
115491     }
115492   }
115493   return rc;
115494 }
115495 
115496 /*
115497 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
115498 ** virtual tables that currently have an open transaction. Pass iSavepoint
115499 ** as the second argument to the virtual table method invoked.
115500 **
115501 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
115502 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
115503 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
115504 ** an open transaction is invoked.
115505 **
115506 ** If any virtual table method returns an error code other than SQLITE_OK,
115507 ** processing is abandoned and the error returned to the caller of this
115508 ** function immediately. If all calls to virtual table methods are successful,
115509 ** SQLITE_OK is returned.
115510 */
115511 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
115512   int rc = SQLITE_OK;
115513 
115514   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
115515   assert( iSavepoint>=-1 );
115516   if( db->aVTrans ){
115517     int i;
115518     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
115519       VTable *pVTab = db->aVTrans[i];
115520       const sqlite3_module *pMod = pVTab->pMod->pModule;
115521       if( pVTab->pVtab && pMod->iVersion>=2 ){
115522         int (*xMethod)(sqlite3_vtab *, int);
115523         switch( op ){
115524           case SAVEPOINT_BEGIN:
115525             xMethod = pMod->xSavepoint;
115526             pVTab->iSavepoint = iSavepoint+1;
115527             break;
115528           case SAVEPOINT_ROLLBACK:
115529             xMethod = pMod->xRollbackTo;
115530             break;
115531           default:
115532             xMethod = pMod->xRelease;
115533             break;
115534         }
115535         if( xMethod && pVTab->iSavepoint>iSavepoint ){
115536           rc = xMethod(pVTab->pVtab, iSavepoint);
115537         }
115538       }
115539     }
115540   }
115541   return rc;
115542 }
115543 
115544 /*
115545 ** The first parameter (pDef) is a function implementation.  The
115546 ** second parameter (pExpr) is the first argument to this function.
115547 ** If pExpr is a column in a virtual table, then let the virtual
115548 ** table implementation have an opportunity to overload the function.
115549 **
115550 ** This routine is used to allow virtual table implementations to
115551 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
115552 **
115553 ** Return either the pDef argument (indicating no change) or a
115554 ** new FuncDef structure that is marked as ephemeral using the
115555 ** SQLITE_FUNC_EPHEM flag.
115556 */
115557 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
115558   sqlite3 *db,    /* Database connection for reporting malloc problems */
115559   FuncDef *pDef,  /* Function to possibly overload */
115560   int nArg,       /* Number of arguments to the function */
115561   Expr *pExpr     /* First argument to the function */
115562 ){
115563   Table *pTab;
115564   sqlite3_vtab *pVtab;
115565   sqlite3_module *pMod;
115566   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
115567   void *pArg = 0;
115568   FuncDef *pNew;
115569   int rc = 0;
115570   char *zLowerName;
115571   unsigned char *z;
115572 
115573 
115574   /* Check to see the left operand is a column in a virtual table */
115575   if( NEVER(pExpr==0) ) return pDef;
115576   if( pExpr->op!=TK_COLUMN ) return pDef;
115577   pTab = pExpr->pTab;
115578   if( NEVER(pTab==0) ) return pDef;
115579   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
115580   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
115581   assert( pVtab!=0 );
115582   assert( pVtab->pModule!=0 );
115583   pMod = (sqlite3_module *)pVtab->pModule;
115584   if( pMod->xFindFunction==0 ) return pDef;
115585 
115586   /* Call the xFindFunction method on the virtual table implementation
115587   ** to see if the implementation wants to overload this function
115588   */
115589   zLowerName = sqlite3DbStrDup(db, pDef->zName);
115590   if( zLowerName ){
115591     for(z=(unsigned char*)zLowerName; *z; z++){
115592       *z = sqlite3UpperToLower[*z];
115593     }
115594     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
115595     sqlite3DbFree(db, zLowerName);
115596   }
115597   if( rc==0 ){
115598     return pDef;
115599   }
115600 
115601   /* Create a new ephemeral function definition for the overloaded
115602   ** function */
115603   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
115604                              + sqlite3Strlen30(pDef->zName) + 1);
115605   if( pNew==0 ){
115606     return pDef;
115607   }
115608   *pNew = *pDef;
115609   pNew->zName = (char *)&pNew[1];
115610   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
115611   pNew->xFunc = xFunc;
115612   pNew->pUserData = pArg;
115613   pNew->funcFlags |= SQLITE_FUNC_EPHEM;
115614   return pNew;
115615 }
115616 
115617 /*
115618 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
115619 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
115620 ** array if it is missing.  If pTab is already in the array, this routine
115621 ** is a no-op.
115622 */
115623 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
115624   Parse *pToplevel = sqlite3ParseToplevel(pParse);
115625   int i, n;
115626   Table **apVtabLock;
115627 
115628   assert( IsVirtual(pTab) );
115629   for(i=0; i<pToplevel->nVtabLock; i++){
115630     if( pTab==pToplevel->apVtabLock[i] ) return;
115631   }
115632   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
115633   apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
115634   if( apVtabLock ){
115635     pToplevel->apVtabLock = apVtabLock;
115636     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
115637   }else{
115638     pToplevel->db->mallocFailed = 1;
115639   }
115640 }
115641 
115642 /*
115643 ** Return the ON CONFLICT resolution mode in effect for the virtual
115644 ** table update operation currently in progress.
115645 **
115646 ** The results of this routine are undefined unless it is called from
115647 ** within an xUpdate method.
115648 */
115649 SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *db){
115650   static const unsigned char aMap[] = {
115651     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
115652   };
115653 #ifdef SQLITE_ENABLE_API_ARMOR
115654   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
115655 #endif
115656   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
115657   assert( OE_Ignore==4 && OE_Replace==5 );
115658   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
115659   return (int)aMap[db->vtabOnConflict-1];
115660 }
115661 
115662 /*
115663 ** Call from within the xCreate() or xConnect() methods to provide
115664 ** the SQLite core with additional information about the behavior
115665 ** of the virtual table being implemented.
115666 */
115667 SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3 *db, int op, ...){
115668   va_list ap;
115669   int rc = SQLITE_OK;
115670 
115671 #ifdef SQLITE_ENABLE_API_ARMOR
115672   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
115673 #endif
115674   sqlite3_mutex_enter(db->mutex);
115675   va_start(ap, op);
115676   switch( op ){
115677     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
115678       VtabCtx *p = db->pVtabCtx;
115679       if( !p ){
115680         rc = SQLITE_MISUSE_BKPT;
115681       }else{
115682         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
115683         p->pVTable->bConstraint = (u8)va_arg(ap, int);
115684       }
115685       break;
115686     }
115687     default:
115688       rc = SQLITE_MISUSE_BKPT;
115689       break;
115690   }
115691   va_end(ap);
115692 
115693   if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
115694   sqlite3_mutex_leave(db->mutex);
115695   return rc;
115696 }
115697 
115698 #endif /* SQLITE_OMIT_VIRTUALTABLE */
115699 
115700 /************** End of vtab.c ************************************************/
115701 /************** Begin file where.c *******************************************/
115702 /*
115703 ** 2001 September 15
115704 **
115705 ** The author disclaims copyright to this source code.  In place of
115706 ** a legal notice, here is a blessing:
115707 **
115708 **    May you do good and not evil.
115709 **    May you find forgiveness for yourself and forgive others.
115710 **    May you share freely, never taking more than you give.
115711 **
115712 *************************************************************************
115713 ** This module contains C code that generates VDBE code used to process
115714 ** the WHERE clause of SQL statements.  This module is responsible for
115715 ** generating the code that loops through a table looking for applicable
115716 ** rows.  Indices are selected and used to speed the search when doing
115717 ** so is applicable.  Because this module is responsible for selecting
115718 ** indices, you might also think of this module as the "query optimizer".
115719 */
115720 /************** Include whereInt.h in the middle of where.c ******************/
115721 /************** Begin file whereInt.h ****************************************/
115722 /*
115723 ** 2013-11-12
115724 **
115725 ** The author disclaims copyright to this source code.  In place of
115726 ** a legal notice, here is a blessing:
115727 **
115728 **    May you do good and not evil.
115729 **    May you find forgiveness for yourself and forgive others.
115730 **    May you share freely, never taking more than you give.
115731 **
115732 *************************************************************************
115733 **
115734 ** This file contains structure and macro definitions for the query
115735 ** planner logic in "where.c".  These definitions are broken out into
115736 ** a separate source file for easier editing.
115737 */
115738 
115739 /*
115740 ** Trace output macros
115741 */
115742 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
115743 /***/ int sqlite3WhereTrace = 0;
115744 #endif
115745 #if defined(SQLITE_DEBUG) \
115746     && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
115747 # define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
115748 # define WHERETRACE_ENABLED 1
115749 #else
115750 # define WHERETRACE(K,X)
115751 #endif
115752 
115753 /* Forward references
115754 */
115755 typedef struct WhereClause WhereClause;
115756 typedef struct WhereMaskSet WhereMaskSet;
115757 typedef struct WhereOrInfo WhereOrInfo;
115758 typedef struct WhereAndInfo WhereAndInfo;
115759 typedef struct WhereLevel WhereLevel;
115760 typedef struct WhereLoop WhereLoop;
115761 typedef struct WherePath WherePath;
115762 typedef struct WhereTerm WhereTerm;
115763 typedef struct WhereLoopBuilder WhereLoopBuilder;
115764 typedef struct WhereScan WhereScan;
115765 typedef struct WhereOrCost WhereOrCost;
115766 typedef struct WhereOrSet WhereOrSet;
115767 
115768 /*
115769 ** This object contains information needed to implement a single nested
115770 ** loop in WHERE clause.
115771 **
115772 ** Contrast this object with WhereLoop.  This object describes the
115773 ** implementation of the loop.  WhereLoop describes the algorithm.
115774 ** This object contains a pointer to the WhereLoop algorithm as one of
115775 ** its elements.
115776 **
115777 ** The WhereInfo object contains a single instance of this object for
115778 ** each term in the FROM clause (which is to say, for each of the
115779 ** nested loops as implemented).  The order of WhereLevel objects determines
115780 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
115781 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
115782 */
115783 struct WhereLevel {
115784   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
115785   int iTabCur;          /* The VDBE cursor used to access the table */
115786   int iIdxCur;          /* The VDBE cursor used to access pIdx */
115787   int addrBrk;          /* Jump here to break out of the loop */
115788   int addrNxt;          /* Jump here to start the next IN combination */
115789   int addrSkip;         /* Jump here for next iteration of skip-scan */
115790   int addrCont;         /* Jump here to continue with the next loop cycle */
115791   int addrFirst;        /* First instruction of interior of the loop */
115792   int addrBody;         /* Beginning of the body of this loop */
115793   int iLikeRepCntr;     /* LIKE range processing counter register */
115794   int addrLikeRep;      /* LIKE range processing address */
115795   u8 iFrom;             /* Which entry in the FROM clause */
115796   u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
115797   int p1, p2;           /* Operands of the opcode used to ends the loop */
115798   union {               /* Information that depends on pWLoop->wsFlags */
115799     struct {
115800       int nIn;              /* Number of entries in aInLoop[] */
115801       struct InLoop {
115802         int iCur;              /* The VDBE cursor used by this IN operator */
115803         int addrInTop;         /* Top of the IN loop */
115804         u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
115805       } *aInLoop;           /* Information about each nested IN operator */
115806     } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
115807     Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
115808   } u;
115809   struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
115810   Bitmask notReady;          /* FROM entries not usable at this level */
115811 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
115812   int addrVisit;        /* Address at which row is visited */
115813 #endif
115814 };
115815 
115816 /*
115817 ** Each instance of this object represents an algorithm for evaluating one
115818 ** term of a join.  Every term of the FROM clause will have at least
115819 ** one corresponding WhereLoop object (unless INDEXED BY constraints
115820 ** prevent a query solution - which is an error) and many terms of the
115821 ** FROM clause will have multiple WhereLoop objects, each describing a
115822 ** potential way of implementing that FROM-clause term, together with
115823 ** dependencies and cost estimates for using the chosen algorithm.
115824 **
115825 ** Query planning consists of building up a collection of these WhereLoop
115826 ** objects, then computing a particular sequence of WhereLoop objects, with
115827 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
115828 ** and that minimize the overall cost.
115829 */
115830 struct WhereLoop {
115831   Bitmask prereq;       /* Bitmask of other loops that must run first */
115832   Bitmask maskSelf;     /* Bitmask identifying table iTab */
115833 #ifdef SQLITE_DEBUG
115834   char cId;             /* Symbolic ID of this loop for debugging use */
115835 #endif
115836   u8 iTab;              /* Position in FROM clause of table for this loop */
115837   u8 iSortIdx;          /* Sorting index number.  0==None */
115838   LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
115839   LogEst rRun;          /* Cost of running each loop */
115840   LogEst nOut;          /* Estimated number of output rows */
115841   union {
115842     struct {               /* Information for internal btree tables */
115843       u16 nEq;               /* Number of equality constraints */
115844       Index *pIndex;         /* Index used, or NULL */
115845     } btree;
115846     struct {               /* Information for virtual tables */
115847       int idxNum;            /* Index number */
115848       u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
115849       i8 isOrdered;          /* True if satisfies ORDER BY */
115850       u16 omitMask;          /* Terms that may be omitted */
115851       char *idxStr;          /* Index identifier string */
115852     } vtab;
115853   } u;
115854   u32 wsFlags;          /* WHERE_* flags describing the plan */
115855   u16 nLTerm;           /* Number of entries in aLTerm[] */
115856   u16 nSkip;            /* Number of NULL aLTerm[] entries */
115857   /**** whereLoopXfer() copies fields above ***********************/
115858 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
115859   u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
115860   WhereTerm **aLTerm;   /* WhereTerms used */
115861   WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
115862   WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */
115863 };
115864 
115865 /* This object holds the prerequisites and the cost of running a
115866 ** subquery on one operand of an OR operator in the WHERE clause.
115867 ** See WhereOrSet for additional information
115868 */
115869 struct WhereOrCost {
115870   Bitmask prereq;     /* Prerequisites */
115871   LogEst rRun;        /* Cost of running this subquery */
115872   LogEst nOut;        /* Number of outputs for this subquery */
115873 };
115874 
115875 /* The WhereOrSet object holds a set of possible WhereOrCosts that
115876 ** correspond to the subquery(s) of OR-clause processing.  Only the
115877 ** best N_OR_COST elements are retained.
115878 */
115879 #define N_OR_COST 3
115880 struct WhereOrSet {
115881   u16 n;                      /* Number of valid a[] entries */
115882   WhereOrCost a[N_OR_COST];   /* Set of best costs */
115883 };
115884 
115885 
115886 /* Forward declaration of methods */
115887 static int whereLoopResize(sqlite3*, WhereLoop*, int);
115888 
115889 /*
115890 ** Each instance of this object holds a sequence of WhereLoop objects
115891 ** that implement some or all of a query plan.
115892 **
115893 ** Think of each WhereLoop object as a node in a graph with arcs
115894 ** showing dependencies and costs for travelling between nodes.  (That is
115895 ** not a completely accurate description because WhereLoop costs are a
115896 ** vector, not a scalar, and because dependencies are many-to-one, not
115897 ** one-to-one as are graph nodes.  But it is a useful visualization aid.)
115898 ** Then a WherePath object is a path through the graph that visits some
115899 ** or all of the WhereLoop objects once.
115900 **
115901 ** The "solver" works by creating the N best WherePath objects of length
115902 ** 1.  Then using those as a basis to compute the N best WherePath objects
115903 ** of length 2.  And so forth until the length of WherePaths equals the
115904 ** number of nodes in the FROM clause.  The best (lowest cost) WherePath
115905 ** at the end is the chosen query plan.
115906 */
115907 struct WherePath {
115908   Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
115909   Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
115910   LogEst nRow;          /* Estimated number of rows generated by this path */
115911   LogEst rCost;         /* Total cost of this path */
115912   LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
115913   i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
115914   WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
115915 };
115916 
115917 /*
115918 ** The query generator uses an array of instances of this structure to
115919 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
115920 ** clause subexpression is separated from the others by AND operators,
115921 ** usually, or sometimes subexpressions separated by OR.
115922 **
115923 ** All WhereTerms are collected into a single WhereClause structure.
115924 ** The following identity holds:
115925 **
115926 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
115927 **
115928 ** When a term is of the form:
115929 **
115930 **              X <op> <expr>
115931 **
115932 ** where X is a column name and <op> is one of certain operators,
115933 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
115934 ** cursor number and column number for X.  WhereTerm.eOperator records
115935 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
115936 ** use of a bitmask encoding for the operator allows us to search
115937 ** quickly for terms that match any of several different operators.
115938 **
115939 ** A WhereTerm might also be two or more subterms connected by OR:
115940 **
115941 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
115942 **
115943 ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
115944 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
115945 ** is collected about the OR clause.
115946 **
115947 ** If a term in the WHERE clause does not match either of the two previous
115948 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
115949 ** to the original subexpression content and wtFlags is set up appropriately
115950 ** but no other fields in the WhereTerm object are meaningful.
115951 **
115952 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
115953 ** but they do so indirectly.  A single WhereMaskSet structure translates
115954 ** cursor number into bits and the translated bit is stored in the prereq
115955 ** fields.  The translation is used in order to maximize the number of
115956 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
115957 ** spread out over the non-negative integers.  For example, the cursor
115958 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
115959 ** translates these sparse cursor numbers into consecutive integers
115960 ** beginning with 0 in order to make the best possible use of the available
115961 ** bits in the Bitmask.  So, in the example above, the cursor numbers
115962 ** would be mapped into integers 0 through 7.
115963 **
115964 ** The number of terms in a join is limited by the number of bits
115965 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
115966 ** is only able to process joins with 64 or fewer tables.
115967 */
115968 struct WhereTerm {
115969   Expr *pExpr;            /* Pointer to the subexpression that is this term */
115970   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
115971   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
115972   union {
115973     int leftColumn;         /* Column number of X in "X <op> <expr>" */
115974     WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
115975     WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
115976   } u;
115977   LogEst truthProb;       /* Probability of truth for this expression */
115978   u16 eOperator;          /* A WO_xx value describing <op> */
115979   u16 wtFlags;            /* TERM_xxx bit flags.  See below */
115980   u8 nChild;              /* Number of children that must disable us */
115981   WhereClause *pWC;       /* The clause this term is part of */
115982   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
115983   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
115984 };
115985 
115986 /*
115987 ** Allowed values of WhereTerm.wtFlags
115988 */
115989 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
115990 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
115991 #define TERM_CODED      0x04   /* This term is already coded */
115992 #define TERM_COPIED     0x08   /* Has a child */
115993 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
115994 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
115995 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
115996 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115997 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
115998 #else
115999 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
116000 #endif
116001 #define TERM_LIKEOPT    0x100  /* Virtual terms from the LIKE optimization */
116002 #define TERM_LIKECOND   0x200  /* Conditionally this LIKE operator term */
116003 #define TERM_LIKE       0x400  /* The original LIKE operator */
116004 
116005 /*
116006 ** An instance of the WhereScan object is used as an iterator for locating
116007 ** terms in the WHERE clause that are useful to the query planner.
116008 */
116009 struct WhereScan {
116010   WhereClause *pOrigWC;      /* Original, innermost WhereClause */
116011   WhereClause *pWC;          /* WhereClause currently being scanned */
116012   char *zCollName;           /* Required collating sequence, if not NULL */
116013   char idxaff;               /* Must match this affinity, if zCollName!=NULL */
116014   unsigned char nEquiv;      /* Number of entries in aEquiv[] */
116015   unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
116016   u32 opMask;                /* Acceptable operators */
116017   int k;                     /* Resume scanning at this->pWC->a[this->k] */
116018   int aEquiv[22];            /* Cursor,Column pairs for equivalence classes */
116019 };
116020 
116021 /*
116022 ** An instance of the following structure holds all information about a
116023 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
116024 **
116025 ** Explanation of pOuter:  For a WHERE clause of the form
116026 **
116027 **           a AND ((b AND c) OR (d AND e)) AND f
116028 **
116029 ** There are separate WhereClause objects for the whole clause and for
116030 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
116031 ** subclauses points to the WhereClause object for the whole clause.
116032 */
116033 struct WhereClause {
116034   WhereInfo *pWInfo;       /* WHERE clause processing context */
116035   WhereClause *pOuter;     /* Outer conjunction */
116036   u8 op;                   /* Split operator.  TK_AND or TK_OR */
116037   int nTerm;               /* Number of terms */
116038   int nSlot;               /* Number of entries in a[] */
116039   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
116040 #if defined(SQLITE_SMALL_STACK)
116041   WhereTerm aStatic[1];    /* Initial static space for a[] */
116042 #else
116043   WhereTerm aStatic[8];    /* Initial static space for a[] */
116044 #endif
116045 };
116046 
116047 /*
116048 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
116049 ** a dynamically allocated instance of the following structure.
116050 */
116051 struct WhereOrInfo {
116052   WhereClause wc;          /* Decomposition into subterms */
116053   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
116054 };
116055 
116056 /*
116057 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
116058 ** a dynamically allocated instance of the following structure.
116059 */
116060 struct WhereAndInfo {
116061   WhereClause wc;          /* The subexpression broken out */
116062 };
116063 
116064 /*
116065 ** An instance of the following structure keeps track of a mapping
116066 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
116067 **
116068 ** The VDBE cursor numbers are small integers contained in
116069 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
116070 ** clause, the cursor numbers might not begin with 0 and they might
116071 ** contain gaps in the numbering sequence.  But we want to make maximum
116072 ** use of the bits in our bitmasks.  This structure provides a mapping
116073 ** from the sparse cursor numbers into consecutive integers beginning
116074 ** with 0.
116075 **
116076 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
116077 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
116078 **
116079 ** For example, if the WHERE clause expression used these VDBE
116080 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
116081 ** would map those cursor numbers into bits 0 through 5.
116082 **
116083 ** Note that the mapping is not necessarily ordered.  In the example
116084 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
116085 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
116086 ** does not really matter.  What is important is that sparse cursor
116087 ** numbers all get mapped into bit numbers that begin with 0 and contain
116088 ** no gaps.
116089 */
116090 struct WhereMaskSet {
116091   int n;                        /* Number of assigned cursor values */
116092   int ix[BMS];                  /* Cursor assigned to each bit */
116093 };
116094 
116095 /*
116096 ** This object is a convenience wrapper holding all information needed
116097 ** to construct WhereLoop objects for a particular query.
116098 */
116099 struct WhereLoopBuilder {
116100   WhereInfo *pWInfo;        /* Information about this WHERE */
116101   WhereClause *pWC;         /* WHERE clause terms */
116102   ExprList *pOrderBy;       /* ORDER BY clause */
116103   WhereLoop *pNew;          /* Template WhereLoop */
116104   WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
116105 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
116106   UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
116107   int nRecValid;            /* Number of valid fields currently in pRec */
116108 #endif
116109 };
116110 
116111 /*
116112 ** The WHERE clause processing routine has two halves.  The
116113 ** first part does the start of the WHERE loop and the second
116114 ** half does the tail of the WHERE loop.  An instance of
116115 ** this structure is returned by the first half and passed
116116 ** into the second half to give some continuity.
116117 **
116118 ** An instance of this object holds the complete state of the query
116119 ** planner.
116120 */
116121 struct WhereInfo {
116122   Parse *pParse;            /* Parsing and code generating context */
116123   SrcList *pTabList;        /* List of tables in the join */
116124   ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
116125   ExprList *pResultSet;     /* Result set. DISTINCT operates on these */
116126   WhereLoop *pLoops;        /* List of all WhereLoop objects */
116127   Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
116128   LogEst nRowOut;           /* Estimated number of output rows */
116129   u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
116130   i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
116131   u8 sorted;                /* True if really sorted (not just grouped) */
116132   u8 okOnePass;             /* Ok to use one-pass algorithm for UPDATE/DELETE */
116133   u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
116134   u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
116135   u8 nLevel;                /* Number of nested loop */
116136   int iTop;                 /* The very beginning of the WHERE loop */
116137   int iContinue;            /* Jump here to continue with next record */
116138   int iBreak;               /* Jump here to break out of the loop */
116139   int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
116140   int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
116141   WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
116142   WhereClause sWC;          /* Decomposition of the WHERE clause */
116143   WhereLevel a[1];          /* Information about each nest loop in WHERE */
116144 };
116145 
116146 /*
116147 ** Bitmasks for the operators on WhereTerm objects.  These are all
116148 ** operators that are of interest to the query planner.  An
116149 ** OR-ed combination of these values can be used when searching for
116150 ** particular WhereTerms within a WhereClause.
116151 */
116152 #define WO_IN     0x001
116153 #define WO_EQ     0x002
116154 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
116155 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
116156 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
116157 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
116158 #define WO_MATCH  0x040
116159 #define WO_ISNULL 0x080
116160 #define WO_OR     0x100       /* Two or more OR-connected terms */
116161 #define WO_AND    0x200       /* Two or more AND-connected terms */
116162 #define WO_EQUIV  0x400       /* Of the form A==B, both columns */
116163 #define WO_NOOP   0x800       /* This term does not restrict search space */
116164 
116165 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
116166 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
116167 
116168 /*
116169 ** These are definitions of bits in the WhereLoop.wsFlags field.
116170 ** The particular combination of bits in each WhereLoop help to
116171 ** determine the algorithm that WhereLoop represents.
116172 */
116173 #define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
116174 #define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
116175 #define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
116176 #define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
116177 #define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
116178 #define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
116179 #define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
116180 #define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
116181 #define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
116182 #define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
116183 #define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
116184 #define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
116185 #define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
116186 #define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
116187 #define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
116188 #define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
116189 #define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
116190 #define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
116191 #define WHERE_PARTIALIDX   0x00020000  /* The automatic index is partial */
116192 
116193 /************** End of whereInt.h ********************************************/
116194 /************** Continuing where we left off in where.c **********************/
116195 
116196 /*
116197 ** Return the estimated number of output rows from a WHERE clause
116198 */
116199 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
116200   return sqlite3LogEstToInt(pWInfo->nRowOut);
116201 }
116202 
116203 /*
116204 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
116205 ** WHERE clause returns outputs for DISTINCT processing.
116206 */
116207 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
116208   return pWInfo->eDistinct;
116209 }
116210 
116211 /*
116212 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
116213 ** Return FALSE if the output needs to be sorted.
116214 */
116215 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
116216   return pWInfo->nOBSat;
116217 }
116218 
116219 /*
116220 ** Return the VDBE address or label to jump to in order to continue
116221 ** immediately with the next row of a WHERE clause.
116222 */
116223 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
116224   assert( pWInfo->iContinue!=0 );
116225   return pWInfo->iContinue;
116226 }
116227 
116228 /*
116229 ** Return the VDBE address or label to jump to in order to break
116230 ** out of a WHERE loop.
116231 */
116232 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
116233   return pWInfo->iBreak;
116234 }
116235 
116236 /*
116237 ** Return TRUE if an UPDATE or DELETE statement can operate directly on
116238 ** the rowids returned by a WHERE clause.  Return FALSE if doing an
116239 ** UPDATE or DELETE might change subsequent WHERE clause results.
116240 **
116241 ** If the ONEPASS optimization is used (if this routine returns true)
116242 ** then also write the indices of open cursors used by ONEPASS
116243 ** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
116244 ** table and iaCur[1] gets the cursor used by an auxiliary index.
116245 ** Either value may be -1, indicating that cursor is not used.
116246 ** Any cursors returned will have been opened for writing.
116247 **
116248 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
116249 ** unable to use the ONEPASS optimization.
116250 */
116251 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
116252   memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
116253   return pWInfo->okOnePass;
116254 }
116255 
116256 /*
116257 ** Move the content of pSrc into pDest
116258 */
116259 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
116260   pDest->n = pSrc->n;
116261   memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
116262 }
116263 
116264 /*
116265 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
116266 **
116267 ** The new entry might overwrite an existing entry, or it might be
116268 ** appended, or it might be discarded.  Do whatever is the right thing
116269 ** so that pSet keeps the N_OR_COST best entries seen so far.
116270 */
116271 static int whereOrInsert(
116272   WhereOrSet *pSet,      /* The WhereOrSet to be updated */
116273   Bitmask prereq,        /* Prerequisites of the new entry */
116274   LogEst rRun,           /* Run-cost of the new entry */
116275   LogEst nOut            /* Number of outputs for the new entry */
116276 ){
116277   u16 i;
116278   WhereOrCost *p;
116279   for(i=pSet->n, p=pSet->a; i>0; i--, p++){
116280     if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
116281       goto whereOrInsert_done;
116282     }
116283     if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
116284       return 0;
116285     }
116286   }
116287   if( pSet->n<N_OR_COST ){
116288     p = &pSet->a[pSet->n++];
116289     p->nOut = nOut;
116290   }else{
116291     p = pSet->a;
116292     for(i=1; i<pSet->n; i++){
116293       if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
116294     }
116295     if( p->rRun<=rRun ) return 0;
116296   }
116297 whereOrInsert_done:
116298   p->prereq = prereq;
116299   p->rRun = rRun;
116300   if( p->nOut>nOut ) p->nOut = nOut;
116301   return 1;
116302 }
116303 
116304 /*
116305 ** Initialize a preallocated WhereClause structure.
116306 */
116307 static void whereClauseInit(
116308   WhereClause *pWC,        /* The WhereClause to be initialized */
116309   WhereInfo *pWInfo        /* The WHERE processing context */
116310 ){
116311   pWC->pWInfo = pWInfo;
116312   pWC->pOuter = 0;
116313   pWC->nTerm = 0;
116314   pWC->nSlot = ArraySize(pWC->aStatic);
116315   pWC->a = pWC->aStatic;
116316 }
116317 
116318 /* Forward reference */
116319 static void whereClauseClear(WhereClause*);
116320 
116321 /*
116322 ** Deallocate all memory associated with a WhereOrInfo object.
116323 */
116324 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
116325   whereClauseClear(&p->wc);
116326   sqlite3DbFree(db, p);
116327 }
116328 
116329 /*
116330 ** Deallocate all memory associated with a WhereAndInfo object.
116331 */
116332 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
116333   whereClauseClear(&p->wc);
116334   sqlite3DbFree(db, p);
116335 }
116336 
116337 /*
116338 ** Deallocate a WhereClause structure.  The WhereClause structure
116339 ** itself is not freed.  This routine is the inverse of whereClauseInit().
116340 */
116341 static void whereClauseClear(WhereClause *pWC){
116342   int i;
116343   WhereTerm *a;
116344   sqlite3 *db = pWC->pWInfo->pParse->db;
116345   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
116346     if( a->wtFlags & TERM_DYNAMIC ){
116347       sqlite3ExprDelete(db, a->pExpr);
116348     }
116349     if( a->wtFlags & TERM_ORINFO ){
116350       whereOrInfoDelete(db, a->u.pOrInfo);
116351     }else if( a->wtFlags & TERM_ANDINFO ){
116352       whereAndInfoDelete(db, a->u.pAndInfo);
116353     }
116354   }
116355   if( pWC->a!=pWC->aStatic ){
116356     sqlite3DbFree(db, pWC->a);
116357   }
116358 }
116359 
116360 /*
116361 ** Add a single new WhereTerm entry to the WhereClause object pWC.
116362 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
116363 ** The index in pWC->a[] of the new WhereTerm is returned on success.
116364 ** 0 is returned if the new WhereTerm could not be added due to a memory
116365 ** allocation error.  The memory allocation failure will be recorded in
116366 ** the db->mallocFailed flag so that higher-level functions can detect it.
116367 **
116368 ** This routine will increase the size of the pWC->a[] array as necessary.
116369 **
116370 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
116371 ** for freeing the expression p is assumed by the WhereClause object pWC.
116372 ** This is true even if this routine fails to allocate a new WhereTerm.
116373 **
116374 ** WARNING:  This routine might reallocate the space used to store
116375 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
116376 ** calling this routine.  Such pointers may be reinitialized by referencing
116377 ** the pWC->a[] array.
116378 */
116379 static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
116380   WhereTerm *pTerm;
116381   int idx;
116382   testcase( wtFlags & TERM_VIRTUAL );
116383   if( pWC->nTerm>=pWC->nSlot ){
116384     WhereTerm *pOld = pWC->a;
116385     sqlite3 *db = pWC->pWInfo->pParse->db;
116386     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
116387     if( pWC->a==0 ){
116388       if( wtFlags & TERM_DYNAMIC ){
116389         sqlite3ExprDelete(db, p);
116390       }
116391       pWC->a = pOld;
116392       return 0;
116393     }
116394     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
116395     if( pOld!=pWC->aStatic ){
116396       sqlite3DbFree(db, pOld);
116397     }
116398     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
116399     memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
116400   }
116401   pTerm = &pWC->a[idx = pWC->nTerm++];
116402   if( p && ExprHasProperty(p, EP_Unlikely) ){
116403     pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
116404   }else{
116405     pTerm->truthProb = 1;
116406   }
116407   pTerm->pExpr = sqlite3ExprSkipCollate(p);
116408   pTerm->wtFlags = wtFlags;
116409   pTerm->pWC = pWC;
116410   pTerm->iParent = -1;
116411   return idx;
116412 }
116413 
116414 /*
116415 ** This routine identifies subexpressions in the WHERE clause where
116416 ** each subexpression is separated by the AND operator or some other
116417 ** operator specified in the op parameter.  The WhereClause structure
116418 ** is filled with pointers to subexpressions.  For example:
116419 **
116420 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
116421 **           \________/     \_______________/     \________________/
116422 **            slot[0]            slot[1]               slot[2]
116423 **
116424 ** The original WHERE clause in pExpr is unaltered.  All this routine
116425 ** does is make slot[] entries point to substructure within pExpr.
116426 **
116427 ** In the previous sentence and in the diagram, "slot[]" refers to
116428 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
116429 ** all terms of the WHERE clause.
116430 */
116431 static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
116432   Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
116433   pWC->op = op;
116434   if( pE2==0 ) return;
116435   if( pE2->op!=op ){
116436     whereClauseInsert(pWC, pExpr, 0);
116437   }else{
116438     whereSplit(pWC, pE2->pLeft, op);
116439     whereSplit(pWC, pE2->pRight, op);
116440   }
116441 }
116442 
116443 /*
116444 ** Initialize a WhereMaskSet object
116445 */
116446 #define initMaskSet(P)  (P)->n=0
116447 
116448 /*
116449 ** Return the bitmask for the given cursor number.  Return 0 if
116450 ** iCursor is not in the set.
116451 */
116452 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
116453   int i;
116454   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
116455   for(i=0; i<pMaskSet->n; i++){
116456     if( pMaskSet->ix[i]==iCursor ){
116457       return MASKBIT(i);
116458     }
116459   }
116460   return 0;
116461 }
116462 
116463 /*
116464 ** Create a new mask for cursor iCursor.
116465 **
116466 ** There is one cursor per table in the FROM clause.  The number of
116467 ** tables in the FROM clause is limited by a test early in the
116468 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
116469 ** array will never overflow.
116470 */
116471 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
116472   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
116473   pMaskSet->ix[pMaskSet->n++] = iCursor;
116474 }
116475 
116476 /*
116477 ** These routines walk (recursively) an expression tree and generate
116478 ** a bitmask indicating which tables are used in that expression
116479 ** tree.
116480 */
116481 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
116482 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
116483 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
116484   Bitmask mask = 0;
116485   if( p==0 ) return 0;
116486   if( p->op==TK_COLUMN ){
116487     mask = getMask(pMaskSet, p->iTable);
116488     return mask;
116489   }
116490   mask = exprTableUsage(pMaskSet, p->pRight);
116491   mask |= exprTableUsage(pMaskSet, p->pLeft);
116492   if( ExprHasProperty(p, EP_xIsSelect) ){
116493     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
116494   }else{
116495     mask |= exprListTableUsage(pMaskSet, p->x.pList);
116496   }
116497   return mask;
116498 }
116499 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
116500   int i;
116501   Bitmask mask = 0;
116502   if( pList ){
116503     for(i=0; i<pList->nExpr; i++){
116504       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
116505     }
116506   }
116507   return mask;
116508 }
116509 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
116510   Bitmask mask = 0;
116511   while( pS ){
116512     SrcList *pSrc = pS->pSrc;
116513     mask |= exprListTableUsage(pMaskSet, pS->pEList);
116514     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
116515     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
116516     mask |= exprTableUsage(pMaskSet, pS->pWhere);
116517     mask |= exprTableUsage(pMaskSet, pS->pHaving);
116518     if( ALWAYS(pSrc!=0) ){
116519       int i;
116520       for(i=0; i<pSrc->nSrc; i++){
116521         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
116522         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
116523       }
116524     }
116525     pS = pS->pPrior;
116526   }
116527   return mask;
116528 }
116529 
116530 /*
116531 ** Return TRUE if the given operator is one of the operators that is
116532 ** allowed for an indexable WHERE clause term.  The allowed operators are
116533 ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
116534 */
116535 static int allowedOp(int op){
116536   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
116537   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
116538   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
116539   assert( TK_GE==TK_EQ+4 );
116540   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
116541 }
116542 
116543 /*
116544 ** Commute a comparison operator.  Expressions of the form "X op Y"
116545 ** are converted into "Y op X".
116546 **
116547 ** If left/right precedence rules come into play when determining the
116548 ** collating sequence, then COLLATE operators are adjusted to ensure
116549 ** that the collating sequence does not change.  For example:
116550 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
116551 ** the left hand side of a comparison overrides any collation sequence
116552 ** attached to the right. For the same reason the EP_Collate flag
116553 ** is not commuted.
116554 */
116555 static void exprCommute(Parse *pParse, Expr *pExpr){
116556   u16 expRight = (pExpr->pRight->flags & EP_Collate);
116557   u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
116558   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
116559   if( expRight==expLeft ){
116560     /* Either X and Y both have COLLATE operator or neither do */
116561     if( expRight ){
116562       /* Both X and Y have COLLATE operators.  Make sure X is always
116563       ** used by clearing the EP_Collate flag from Y. */
116564       pExpr->pRight->flags &= ~EP_Collate;
116565     }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
116566       /* Neither X nor Y have COLLATE operators, but X has a non-default
116567       ** collating sequence.  So add the EP_Collate marker on X to cause
116568       ** it to be searched first. */
116569       pExpr->pLeft->flags |= EP_Collate;
116570     }
116571   }
116572   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
116573   if( pExpr->op>=TK_GT ){
116574     assert( TK_LT==TK_GT+2 );
116575     assert( TK_GE==TK_LE+2 );
116576     assert( TK_GT>TK_EQ );
116577     assert( TK_GT<TK_LE );
116578     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
116579     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
116580   }
116581 }
116582 
116583 /*
116584 ** Translate from TK_xx operator to WO_xx bitmask.
116585 */
116586 static u16 operatorMask(int op){
116587   u16 c;
116588   assert( allowedOp(op) );
116589   if( op==TK_IN ){
116590     c = WO_IN;
116591   }else if( op==TK_ISNULL ){
116592     c = WO_ISNULL;
116593   }else{
116594     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
116595     c = (u16)(WO_EQ<<(op-TK_EQ));
116596   }
116597   assert( op!=TK_ISNULL || c==WO_ISNULL );
116598   assert( op!=TK_IN || c==WO_IN );
116599   assert( op!=TK_EQ || c==WO_EQ );
116600   assert( op!=TK_LT || c==WO_LT );
116601   assert( op!=TK_LE || c==WO_LE );
116602   assert( op!=TK_GT || c==WO_GT );
116603   assert( op!=TK_GE || c==WO_GE );
116604   return c;
116605 }
116606 
116607 /*
116608 ** Advance to the next WhereTerm that matches according to the criteria
116609 ** established when the pScan object was initialized by whereScanInit().
116610 ** Return NULL if there are no more matching WhereTerms.
116611 */
116612 static WhereTerm *whereScanNext(WhereScan *pScan){
116613   int iCur;            /* The cursor on the LHS of the term */
116614   int iColumn;         /* The column on the LHS of the term.  -1 for IPK */
116615   Expr *pX;            /* An expression being tested */
116616   WhereClause *pWC;    /* Shorthand for pScan->pWC */
116617   WhereTerm *pTerm;    /* The term being tested */
116618   int k = pScan->k;    /* Where to start scanning */
116619 
116620   while( pScan->iEquiv<=pScan->nEquiv ){
116621     iCur = pScan->aEquiv[pScan->iEquiv-2];
116622     iColumn = pScan->aEquiv[pScan->iEquiv-1];
116623     while( (pWC = pScan->pWC)!=0 ){
116624       for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
116625         if( pTerm->leftCursor==iCur
116626          && pTerm->u.leftColumn==iColumn
116627          && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
116628         ){
116629           if( (pTerm->eOperator & WO_EQUIV)!=0
116630            && pScan->nEquiv<ArraySize(pScan->aEquiv)
116631           ){
116632             int j;
116633             pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
116634             assert( pX->op==TK_COLUMN );
116635             for(j=0; j<pScan->nEquiv; j+=2){
116636               if( pScan->aEquiv[j]==pX->iTable
116637                && pScan->aEquiv[j+1]==pX->iColumn ){
116638                   break;
116639               }
116640             }
116641             if( j==pScan->nEquiv ){
116642               pScan->aEquiv[j] = pX->iTable;
116643               pScan->aEquiv[j+1] = pX->iColumn;
116644               pScan->nEquiv += 2;
116645             }
116646           }
116647           if( (pTerm->eOperator & pScan->opMask)!=0 ){
116648             /* Verify the affinity and collating sequence match */
116649             if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
116650               CollSeq *pColl;
116651               Parse *pParse = pWC->pWInfo->pParse;
116652               pX = pTerm->pExpr;
116653               if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
116654                 continue;
116655               }
116656               assert(pX->pLeft);
116657               pColl = sqlite3BinaryCompareCollSeq(pParse,
116658                                                   pX->pLeft, pX->pRight);
116659               if( pColl==0 ) pColl = pParse->db->pDfltColl;
116660               if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
116661                 continue;
116662               }
116663             }
116664             if( (pTerm->eOperator & WO_EQ)!=0
116665              && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
116666              && pX->iTable==pScan->aEquiv[0]
116667              && pX->iColumn==pScan->aEquiv[1]
116668             ){
116669               continue;
116670             }
116671             pScan->k = k+1;
116672             return pTerm;
116673           }
116674         }
116675       }
116676       pScan->pWC = pScan->pWC->pOuter;
116677       k = 0;
116678     }
116679     pScan->pWC = pScan->pOrigWC;
116680     k = 0;
116681     pScan->iEquiv += 2;
116682   }
116683   return 0;
116684 }
116685 
116686 /*
116687 ** Initialize a WHERE clause scanner object.  Return a pointer to the
116688 ** first match.  Return NULL if there are no matches.
116689 **
116690 ** The scanner will be searching the WHERE clause pWC.  It will look
116691 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
116692 ** iCur.  The <op> must be one of the operators described by opMask.
116693 **
116694 ** If the search is for X and the WHERE clause contains terms of the
116695 ** form X=Y then this routine might also return terms of the form
116696 ** "Y <op> <expr>".  The number of levels of transitivity is limited,
116697 ** but is enough to handle most commonly occurring SQL statements.
116698 **
116699 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
116700 ** index pIdx.
116701 */
116702 static WhereTerm *whereScanInit(
116703   WhereScan *pScan,       /* The WhereScan object being initialized */
116704   WhereClause *pWC,       /* The WHERE clause to be scanned */
116705   int iCur,               /* Cursor to scan for */
116706   int iColumn,            /* Column to scan for */
116707   u32 opMask,             /* Operator(s) to scan for */
116708   Index *pIdx             /* Must be compatible with this index */
116709 ){
116710   int j;
116711 
116712   /* memset(pScan, 0, sizeof(*pScan)); */
116713   pScan->pOrigWC = pWC;
116714   pScan->pWC = pWC;
116715   if( pIdx && iColumn>=0 ){
116716     pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
116717     for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
116718       if( NEVER(j>pIdx->nColumn) ) return 0;
116719     }
116720     pScan->zCollName = pIdx->azColl[j];
116721   }else{
116722     pScan->idxaff = 0;
116723     pScan->zCollName = 0;
116724   }
116725   pScan->opMask = opMask;
116726   pScan->k = 0;
116727   pScan->aEquiv[0] = iCur;
116728   pScan->aEquiv[1] = iColumn;
116729   pScan->nEquiv = 2;
116730   pScan->iEquiv = 2;
116731   return whereScanNext(pScan);
116732 }
116733 
116734 /*
116735 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
116736 ** where X is a reference to the iColumn of table iCur and <op> is one of
116737 ** the WO_xx operator codes specified by the op parameter.
116738 ** Return a pointer to the term.  Return 0 if not found.
116739 **
116740 ** The term returned might by Y=<expr> if there is another constraint in
116741 ** the WHERE clause that specifies that X=Y.  Any such constraints will be
116742 ** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
116743 ** aEquiv[] array holds X and all its equivalents, with each SQL variable
116744 ** taking up two slots in aEquiv[].  The first slot is for the cursor number
116745 ** and the second is for the column number.  There are 22 slots in aEquiv[]
116746 ** so that means we can look for X plus up to 10 other equivalent values.
116747 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
116748 ** and ... and A9=A10 and A10=<expr>.
116749 **
116750 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
116751 ** then try for the one with no dependencies on <expr> - in other words where
116752 ** <expr> is a constant expression of some kind.  Only return entries of
116753 ** the form "X <op> Y" where Y is a column in another table if no terms of
116754 ** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
116755 ** exist, try to return a term that does not use WO_EQUIV.
116756 */
116757 static WhereTerm *findTerm(
116758   WhereClause *pWC,     /* The WHERE clause to be searched */
116759   int iCur,             /* Cursor number of LHS */
116760   int iColumn,          /* Column number of LHS */
116761   Bitmask notReady,     /* RHS must not overlap with this mask */
116762   u32 op,               /* Mask of WO_xx values describing operator */
116763   Index *pIdx           /* Must be compatible with this index, if not NULL */
116764 ){
116765   WhereTerm *pResult = 0;
116766   WhereTerm *p;
116767   WhereScan scan;
116768 
116769   p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
116770   while( p ){
116771     if( (p->prereqRight & notReady)==0 ){
116772       if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
116773         return p;
116774       }
116775       if( pResult==0 ) pResult = p;
116776     }
116777     p = whereScanNext(&scan);
116778   }
116779   return pResult;
116780 }
116781 
116782 /* Forward reference */
116783 static void exprAnalyze(SrcList*, WhereClause*, int);
116784 
116785 /*
116786 ** Call exprAnalyze on all terms in a WHERE clause.
116787 */
116788 static void exprAnalyzeAll(
116789   SrcList *pTabList,       /* the FROM clause */
116790   WhereClause *pWC         /* the WHERE clause to be analyzed */
116791 ){
116792   int i;
116793   for(i=pWC->nTerm-1; i>=0; i--){
116794     exprAnalyze(pTabList, pWC, i);
116795   }
116796 }
116797 
116798 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
116799 /*
116800 ** Check to see if the given expression is a LIKE or GLOB operator that
116801 ** can be optimized using inequality constraints.  Return TRUE if it is
116802 ** so and false if not.
116803 **
116804 ** In order for the operator to be optimizible, the RHS must be a string
116805 ** literal that does not begin with a wildcard.  The LHS must be a column
116806 ** that may only be NULL, a string, or a BLOB, never a number. (This means
116807 ** that virtual tables cannot participate in the LIKE optimization.)  If the
116808 ** collating sequence for the column on the LHS must be appropriate for
116809 ** the operator.
116810 */
116811 static int isLikeOrGlob(
116812   Parse *pParse,    /* Parsing and code generating context */
116813   Expr *pExpr,      /* Test this expression */
116814   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
116815   int *pisComplete, /* True if the only wildcard is % in the last character */
116816   int *pnoCase      /* True if uppercase is equivalent to lowercase */
116817 ){
116818   const char *z = 0;         /* String on RHS of LIKE operator */
116819   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
116820   ExprList *pList;           /* List of operands to the LIKE operator */
116821   int c;                     /* One character in z[] */
116822   int cnt;                   /* Number of non-wildcard prefix characters */
116823   char wc[3];                /* Wildcard characters */
116824   sqlite3 *db = pParse->db;  /* Database connection */
116825   sqlite3_value *pVal = 0;
116826   int op;                    /* Opcode of pRight */
116827 
116828   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
116829     return 0;
116830   }
116831 #ifdef SQLITE_EBCDIC
116832   if( *pnoCase ) return 0;
116833 #endif
116834   pList = pExpr->x.pList;
116835   pLeft = pList->a[1].pExpr;
116836   if( pLeft->op!=TK_COLUMN
116837    || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
116838    || IsVirtual(pLeft->pTab)  /* Value might be numeric */
116839   ){
116840     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
116841     ** be the name of an indexed column with TEXT affinity. */
116842     return 0;
116843   }
116844   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
116845 
116846   pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
116847   op = pRight->op;
116848   if( op==TK_VARIABLE ){
116849     Vdbe *pReprepare = pParse->pReprepare;
116850     int iCol = pRight->iColumn;
116851     pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
116852     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
116853       z = (char *)sqlite3_value_text(pVal);
116854     }
116855     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
116856     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
116857   }else if( op==TK_STRING ){
116858     z = pRight->u.zToken;
116859   }
116860   if( z ){
116861     cnt = 0;
116862     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
116863       cnt++;
116864     }
116865     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
116866       Expr *pPrefix;
116867       *pisComplete = c==wc[0] && z[cnt+1]==0;
116868       pPrefix = sqlite3Expr(db, TK_STRING, z);
116869       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
116870       *ppPrefix = pPrefix;
116871       if( op==TK_VARIABLE ){
116872         Vdbe *v = pParse->pVdbe;
116873         sqlite3VdbeSetVarmask(v, pRight->iColumn);
116874         if( *pisComplete && pRight->u.zToken[1] ){
116875           /* If the rhs of the LIKE expression is a variable, and the current
116876           ** value of the variable means there is no need to invoke the LIKE
116877           ** function, then no OP_Variable will be added to the program.
116878           ** This causes problems for the sqlite3_bind_parameter_name()
116879           ** API. To work around them, add a dummy OP_Variable here.
116880           */
116881           int r1 = sqlite3GetTempReg(pParse);
116882           sqlite3ExprCodeTarget(pParse, pRight, r1);
116883           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
116884           sqlite3ReleaseTempReg(pParse, r1);
116885         }
116886       }
116887     }else{
116888       z = 0;
116889     }
116890   }
116891 
116892   sqlite3ValueFree(pVal);
116893   return (z!=0);
116894 }
116895 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
116896 
116897 
116898 #ifndef SQLITE_OMIT_VIRTUALTABLE
116899 /*
116900 ** Check to see if the given expression is of the form
116901 **
116902 **         column MATCH expr
116903 **
116904 ** If it is then return TRUE.  If not, return FALSE.
116905 */
116906 static int isMatchOfColumn(
116907   Expr *pExpr      /* Test this expression */
116908 ){
116909   ExprList *pList;
116910 
116911   if( pExpr->op!=TK_FUNCTION ){
116912     return 0;
116913   }
116914   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
116915     return 0;
116916   }
116917   pList = pExpr->x.pList;
116918   if( pList->nExpr!=2 ){
116919     return 0;
116920   }
116921   if( pList->a[1].pExpr->op != TK_COLUMN ){
116922     return 0;
116923   }
116924   return 1;
116925 }
116926 #endif /* SQLITE_OMIT_VIRTUALTABLE */
116927 
116928 /*
116929 ** If the pBase expression originated in the ON or USING clause of
116930 ** a join, then transfer the appropriate markings over to derived.
116931 */
116932 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
116933   if( pDerived ){
116934     pDerived->flags |= pBase->flags & EP_FromJoin;
116935     pDerived->iRightJoinTable = pBase->iRightJoinTable;
116936   }
116937 }
116938 
116939 /*
116940 ** Mark term iChild as being a child of term iParent
116941 */
116942 static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
116943   pWC->a[iChild].iParent = iParent;
116944   pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
116945   pWC->a[iParent].nChild++;
116946 }
116947 
116948 /*
116949 ** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not
116950 ** a conjunction, then return just pTerm when N==0.  If N is exceeds
116951 ** the number of available subterms, return NULL.
116952 */
116953 static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
116954   if( pTerm->eOperator!=WO_AND ){
116955     return N==0 ? pTerm : 0;
116956   }
116957   if( N<pTerm->u.pAndInfo->wc.nTerm ){
116958     return &pTerm->u.pAndInfo->wc.a[N];
116959   }
116960   return 0;
116961 }
116962 
116963 /*
116964 ** Subterms pOne and pTwo are contained within WHERE clause pWC.  The
116965 ** two subterms are in disjunction - they are OR-ed together.
116966 **
116967 ** If these two terms are both of the form:  "A op B" with the same
116968 ** A and B values but different operators and if the operators are
116969 ** compatible (if one is = and the other is <, for example) then
116970 ** add a new virtual AND term to pWC that is the combination of the
116971 ** two.
116972 **
116973 ** Some examples:
116974 **
116975 **    x<y OR x=y    -->     x<=y
116976 **    x=y OR x=y    -->     x=y
116977 **    x<=y OR x<y   -->     x<=y
116978 **
116979 ** The following is NOT generated:
116980 **
116981 **    x<y OR x>y    -->     x!=y
116982 */
116983 static void whereCombineDisjuncts(
116984   SrcList *pSrc,         /* the FROM clause */
116985   WhereClause *pWC,      /* The complete WHERE clause */
116986   WhereTerm *pOne,       /* First disjunct */
116987   WhereTerm *pTwo        /* Second disjunct */
116988 ){
116989   u16 eOp = pOne->eOperator | pTwo->eOperator;
116990   sqlite3 *db;           /* Database connection (for malloc) */
116991   Expr *pNew;            /* New virtual expression */
116992   int op;                /* Operator for the combined expression */
116993   int idxNew;            /* Index in pWC of the next virtual term */
116994 
116995   if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
116996   if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
116997   if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
116998    && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
116999   assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
117000   assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
117001   if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
117002   if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
117003   /* If we reach this point, it means the two subterms can be combined */
117004   if( (eOp & (eOp-1))!=0 ){
117005     if( eOp & (WO_LT|WO_LE) ){
117006       eOp = WO_LE;
117007     }else{
117008       assert( eOp & (WO_GT|WO_GE) );
117009       eOp = WO_GE;
117010     }
117011   }
117012   db = pWC->pWInfo->pParse->db;
117013   pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
117014   if( pNew==0 ) return;
117015   for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
117016   pNew->op = op;
117017   idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
117018   exprAnalyze(pSrc, pWC, idxNew);
117019 }
117020 
117021 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
117022 /*
117023 ** Analyze a term that consists of two or more OR-connected
117024 ** subterms.  So in:
117025 **
117026 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
117027 **                          ^^^^^^^^^^^^^^^^^^^^
117028 **
117029 ** This routine analyzes terms such as the middle term in the above example.
117030 ** A WhereOrTerm object is computed and attached to the term under
117031 ** analysis, regardless of the outcome of the analysis.  Hence:
117032 **
117033 **     WhereTerm.wtFlags   |=  TERM_ORINFO
117034 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
117035 **
117036 ** The term being analyzed must have two or more of OR-connected subterms.
117037 ** A single subterm might be a set of AND-connected sub-subterms.
117038 ** Examples of terms under analysis:
117039 **
117040 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
117041 **     (B)     x=expr1 OR expr2=x OR x=expr3
117042 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
117043 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
117044 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
117045 **     (F)     x>A OR (x=A AND y>=B)
117046 **
117047 ** CASE 1:
117048 **
117049 ** If all subterms are of the form T.C=expr for some single column of C and
117050 ** a single table T (as shown in example B above) then create a new virtual
117051 ** term that is an equivalent IN expression.  In other words, if the term
117052 ** being analyzed is:
117053 **
117054 **      x = expr1  OR  expr2 = x  OR  x = expr3
117055 **
117056 ** then create a new virtual term like this:
117057 **
117058 **      x IN (expr1,expr2,expr3)
117059 **
117060 ** CASE 2:
117061 **
117062 ** If there are exactly two disjuncts one side has x>A and the other side
117063 ** has x=A (for the same x and A) then add a new virtual conjunct term to the
117064 ** WHERE clause of the form "x>=A".  Example:
117065 **
117066 **      x>A OR (x=A AND y>B)    adds:    x>=A
117067 **
117068 ** The added conjunct can sometimes be helpful in query planning.
117069 **
117070 ** CASE 3:
117071 **
117072 ** If all subterms are indexable by a single table T, then set
117073 **
117074 **     WhereTerm.eOperator              =  WO_OR
117075 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
117076 **
117077 ** A subterm is "indexable" if it is of the form
117078 ** "T.C <op> <expr>" where C is any column of table T and
117079 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
117080 ** A subterm is also indexable if it is an AND of two or more
117081 ** subsubterms at least one of which is indexable.  Indexable AND
117082 ** subterms have their eOperator set to WO_AND and they have
117083 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
117084 **
117085 ** From another point of view, "indexable" means that the subterm could
117086 ** potentially be used with an index if an appropriate index exists.
117087 ** This analysis does not consider whether or not the index exists; that
117088 ** is decided elsewhere.  This analysis only looks at whether subterms
117089 ** appropriate for indexing exist.
117090 **
117091 ** All examples A through E above satisfy case 2.  But if a term
117092 ** also satisfies case 1 (such as B) we know that the optimizer will
117093 ** always prefer case 1, so in that case we pretend that case 2 is not
117094 ** satisfied.
117095 **
117096 ** It might be the case that multiple tables are indexable.  For example,
117097 ** (E) above is indexable on tables P, Q, and R.
117098 **
117099 ** Terms that satisfy case 2 are candidates for lookup by using
117100 ** separate indices to find rowids for each subterm and composing
117101 ** the union of all rowids using a RowSet object.  This is similar
117102 ** to "bitmap indices" in other database engines.
117103 **
117104 ** OTHERWISE:
117105 **
117106 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
117107 ** zero.  This term is not useful for search.
117108 */
117109 static void exprAnalyzeOrTerm(
117110   SrcList *pSrc,            /* the FROM clause */
117111   WhereClause *pWC,         /* the complete WHERE clause */
117112   int idxTerm               /* Index of the OR-term to be analyzed */
117113 ){
117114   WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
117115   Parse *pParse = pWInfo->pParse;         /* Parser context */
117116   sqlite3 *db = pParse->db;               /* Database connection */
117117   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
117118   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
117119   int i;                                  /* Loop counters */
117120   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
117121   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
117122   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
117123   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
117124   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
117125 
117126   /*
117127   ** Break the OR clause into its separate subterms.  The subterms are
117128   ** stored in a WhereClause structure containing within the WhereOrInfo
117129   ** object that is attached to the original OR clause term.
117130   */
117131   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
117132   assert( pExpr->op==TK_OR );
117133   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
117134   if( pOrInfo==0 ) return;
117135   pTerm->wtFlags |= TERM_ORINFO;
117136   pOrWc = &pOrInfo->wc;
117137   whereClauseInit(pOrWc, pWInfo);
117138   whereSplit(pOrWc, pExpr, TK_OR);
117139   exprAnalyzeAll(pSrc, pOrWc);
117140   if( db->mallocFailed ) return;
117141   assert( pOrWc->nTerm>=2 );
117142 
117143   /*
117144   ** Compute the set of tables that might satisfy cases 1 or 2.
117145   */
117146   indexable = ~(Bitmask)0;
117147   chngToIN = ~(Bitmask)0;
117148   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
117149     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
117150       WhereAndInfo *pAndInfo;
117151       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
117152       chngToIN = 0;
117153       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
117154       if( pAndInfo ){
117155         WhereClause *pAndWC;
117156         WhereTerm *pAndTerm;
117157         int j;
117158         Bitmask b = 0;
117159         pOrTerm->u.pAndInfo = pAndInfo;
117160         pOrTerm->wtFlags |= TERM_ANDINFO;
117161         pOrTerm->eOperator = WO_AND;
117162         pAndWC = &pAndInfo->wc;
117163         whereClauseInit(pAndWC, pWC->pWInfo);
117164         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
117165         exprAnalyzeAll(pSrc, pAndWC);
117166         pAndWC->pOuter = pWC;
117167         testcase( db->mallocFailed );
117168         if( !db->mallocFailed ){
117169           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
117170             assert( pAndTerm->pExpr );
117171             if( allowedOp(pAndTerm->pExpr->op) ){
117172               b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
117173             }
117174           }
117175         }
117176         indexable &= b;
117177       }
117178     }else if( pOrTerm->wtFlags & TERM_COPIED ){
117179       /* Skip this term for now.  We revisit it when we process the
117180       ** corresponding TERM_VIRTUAL term */
117181     }else{
117182       Bitmask b;
117183       b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
117184       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
117185         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
117186         b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
117187       }
117188       indexable &= b;
117189       if( (pOrTerm->eOperator & WO_EQ)==0 ){
117190         chngToIN = 0;
117191       }else{
117192         chngToIN &= b;
117193       }
117194     }
117195   }
117196 
117197   /*
117198   ** Record the set of tables that satisfy case 3.  The set might be
117199   ** empty.
117200   */
117201   pOrInfo->indexable = indexable;
117202   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
117203 
117204   /* For a two-way OR, attempt to implementation case 2.
117205   */
117206   if( indexable && pOrWc->nTerm==2 ){
117207     int iOne = 0;
117208     WhereTerm *pOne;
117209     while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
117210       int iTwo = 0;
117211       WhereTerm *pTwo;
117212       while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
117213         whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
117214       }
117215     }
117216   }
117217 
117218   /*
117219   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
117220   ** we have to do some additional checking to see if case 1 really
117221   ** is satisfied.
117222   **
117223   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
117224   ** that there is no possibility of transforming the OR clause into an
117225   ** IN operator because one or more terms in the OR clause contain
117226   ** something other than == on a column in the single table.  The 1-bit
117227   ** case means that every term of the OR clause is of the form
117228   ** "table.column=expr" for some single table.  The one bit that is set
117229   ** will correspond to the common table.  We still need to check to make
117230   ** sure the same column is used on all terms.  The 2-bit case is when
117231   ** the all terms are of the form "table1.column=table2.column".  It
117232   ** might be possible to form an IN operator with either table1.column
117233   ** or table2.column as the LHS if either is common to every term of
117234   ** the OR clause.
117235   **
117236   ** Note that terms of the form "table.column1=table.column2" (the
117237   ** same table on both sizes of the ==) cannot be optimized.
117238   */
117239   if( chngToIN ){
117240     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
117241     int iColumn = -1;         /* Column index on lhs of IN operator */
117242     int iCursor = -1;         /* Table cursor common to all terms */
117243     int j = 0;                /* Loop counter */
117244 
117245     /* Search for a table and column that appears on one side or the
117246     ** other of the == operator in every subterm.  That table and column
117247     ** will be recorded in iCursor and iColumn.  There might not be any
117248     ** such table and column.  Set okToChngToIN if an appropriate table
117249     ** and column is found but leave okToChngToIN false if not found.
117250     */
117251     for(j=0; j<2 && !okToChngToIN; j++){
117252       pOrTerm = pOrWc->a;
117253       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
117254         assert( pOrTerm->eOperator & WO_EQ );
117255         pOrTerm->wtFlags &= ~TERM_OR_OK;
117256         if( pOrTerm->leftCursor==iCursor ){
117257           /* This is the 2-bit case and we are on the second iteration and
117258           ** current term is from the first iteration.  So skip this term. */
117259           assert( j==1 );
117260           continue;
117261         }
117262         if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
117263           /* This term must be of the form t1.a==t2.b where t2 is in the
117264           ** chngToIN set but t1 is not.  This term will be either preceded
117265           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
117266           ** and use its inversion. */
117267           testcase( pOrTerm->wtFlags & TERM_COPIED );
117268           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
117269           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
117270           continue;
117271         }
117272         iColumn = pOrTerm->u.leftColumn;
117273         iCursor = pOrTerm->leftCursor;
117274         break;
117275       }
117276       if( i<0 ){
117277         /* No candidate table+column was found.  This can only occur
117278         ** on the second iteration */
117279         assert( j==1 );
117280         assert( IsPowerOfTwo(chngToIN) );
117281         assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
117282         break;
117283       }
117284       testcase( j==1 );
117285 
117286       /* We have found a candidate table and column.  Check to see if that
117287       ** table and column is common to every term in the OR clause */
117288       okToChngToIN = 1;
117289       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
117290         assert( pOrTerm->eOperator & WO_EQ );
117291         if( pOrTerm->leftCursor!=iCursor ){
117292           pOrTerm->wtFlags &= ~TERM_OR_OK;
117293         }else if( pOrTerm->u.leftColumn!=iColumn ){
117294           okToChngToIN = 0;
117295         }else{
117296           int affLeft, affRight;
117297           /* If the right-hand side is also a column, then the affinities
117298           ** of both right and left sides must be such that no type
117299           ** conversions are required on the right.  (Ticket #2249)
117300           */
117301           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
117302           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
117303           if( affRight!=0 && affRight!=affLeft ){
117304             okToChngToIN = 0;
117305           }else{
117306             pOrTerm->wtFlags |= TERM_OR_OK;
117307           }
117308         }
117309       }
117310     }
117311 
117312     /* At this point, okToChngToIN is true if original pTerm satisfies
117313     ** case 1.  In that case, construct a new virtual term that is
117314     ** pTerm converted into an IN operator.
117315     */
117316     if( okToChngToIN ){
117317       Expr *pDup;            /* A transient duplicate expression */
117318       ExprList *pList = 0;   /* The RHS of the IN operator */
117319       Expr *pLeft = 0;       /* The LHS of the IN operator */
117320       Expr *pNew;            /* The complete IN operator */
117321 
117322       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
117323         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
117324         assert( pOrTerm->eOperator & WO_EQ );
117325         assert( pOrTerm->leftCursor==iCursor );
117326         assert( pOrTerm->u.leftColumn==iColumn );
117327         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
117328         pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
117329         pLeft = pOrTerm->pExpr->pLeft;
117330       }
117331       assert( pLeft!=0 );
117332       pDup = sqlite3ExprDup(db, pLeft, 0);
117333       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
117334       if( pNew ){
117335         int idxNew;
117336         transferJoinMarkings(pNew, pExpr);
117337         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
117338         pNew->x.pList = pList;
117339         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
117340         testcase( idxNew==0 );
117341         exprAnalyze(pSrc, pWC, idxNew);
117342         pTerm = &pWC->a[idxTerm];
117343         markTermAsChild(pWC, idxNew, idxTerm);
117344       }else{
117345         sqlite3ExprListDelete(db, pList);
117346       }
117347       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 3 */
117348     }
117349   }
117350 }
117351 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
117352 
117353 /*
117354 ** The input to this routine is an WhereTerm structure with only the
117355 ** "pExpr" field filled in.  The job of this routine is to analyze the
117356 ** subexpression and populate all the other fields of the WhereTerm
117357 ** structure.
117358 **
117359 ** If the expression is of the form "<expr> <op> X" it gets commuted
117360 ** to the standard form of "X <op> <expr>".
117361 **
117362 ** If the expression is of the form "X <op> Y" where both X and Y are
117363 ** columns, then the original expression is unchanged and a new virtual
117364 ** term of the form "Y <op> X" is added to the WHERE clause and
117365 ** analyzed separately.  The original term is marked with TERM_COPIED
117366 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
117367 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
117368 ** is a commuted copy of a prior term.)  The original term has nChild=1
117369 ** and the copy has idxParent set to the index of the original term.
117370 */
117371 static void exprAnalyze(
117372   SrcList *pSrc,            /* the FROM clause */
117373   WhereClause *pWC,         /* the WHERE clause */
117374   int idxTerm               /* Index of the term to be analyzed */
117375 ){
117376   WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
117377   WhereTerm *pTerm;                /* The term to be analyzed */
117378   WhereMaskSet *pMaskSet;          /* Set of table index masks */
117379   Expr *pExpr;                     /* The expression to be analyzed */
117380   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
117381   Bitmask prereqAll;               /* Prerequesites of pExpr */
117382   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
117383   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
117384   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
117385   int noCase = 0;                  /* uppercase equivalent to lowercase */
117386   int op;                          /* Top-level operator.  pExpr->op */
117387   Parse *pParse = pWInfo->pParse;  /* Parsing context */
117388   sqlite3 *db = pParse->db;        /* Database connection */
117389 
117390   if( db->mallocFailed ){
117391     return;
117392   }
117393   pTerm = &pWC->a[idxTerm];
117394   pMaskSet = &pWInfo->sMaskSet;
117395   pExpr = pTerm->pExpr;
117396   assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
117397   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
117398   op = pExpr->op;
117399   if( op==TK_IN ){
117400     assert( pExpr->pRight==0 );
117401     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
117402       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
117403     }else{
117404       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
117405     }
117406   }else if( op==TK_ISNULL ){
117407     pTerm->prereqRight = 0;
117408   }else{
117409     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
117410   }
117411   prereqAll = exprTableUsage(pMaskSet, pExpr);
117412   if( ExprHasProperty(pExpr, EP_FromJoin) ){
117413     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
117414     prereqAll |= x;
117415     extraRight = x-1;  /* ON clause terms may not be used with an index
117416                        ** on left table of a LEFT JOIN.  Ticket #3015 */
117417   }
117418   pTerm->prereqAll = prereqAll;
117419   pTerm->leftCursor = -1;
117420   pTerm->iParent = -1;
117421   pTerm->eOperator = 0;
117422   if( allowedOp(op) ){
117423     Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
117424     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
117425     u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
117426     if( pLeft->op==TK_COLUMN ){
117427       pTerm->leftCursor = pLeft->iTable;
117428       pTerm->u.leftColumn = pLeft->iColumn;
117429       pTerm->eOperator = operatorMask(op) & opMask;
117430     }
117431     if( pRight && pRight->op==TK_COLUMN ){
117432       WhereTerm *pNew;
117433       Expr *pDup;
117434       u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
117435       if( pTerm->leftCursor>=0 ){
117436         int idxNew;
117437         pDup = sqlite3ExprDup(db, pExpr, 0);
117438         if( db->mallocFailed ){
117439           sqlite3ExprDelete(db, pDup);
117440           return;
117441         }
117442         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
117443         if( idxNew==0 ) return;
117444         pNew = &pWC->a[idxNew];
117445         markTermAsChild(pWC, idxNew, idxTerm);
117446         pTerm = &pWC->a[idxTerm];
117447         pTerm->wtFlags |= TERM_COPIED;
117448         if( pExpr->op==TK_EQ
117449          && !ExprHasProperty(pExpr, EP_FromJoin)
117450          && OptimizationEnabled(db, SQLITE_Transitive)
117451         ){
117452           pTerm->eOperator |= WO_EQUIV;
117453           eExtraOp = WO_EQUIV;
117454         }
117455       }else{
117456         pDup = pExpr;
117457         pNew = pTerm;
117458       }
117459       exprCommute(pParse, pDup);
117460       pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
117461       pNew->leftCursor = pLeft->iTable;
117462       pNew->u.leftColumn = pLeft->iColumn;
117463       testcase( (prereqLeft | extraRight) != prereqLeft );
117464       pNew->prereqRight = prereqLeft | extraRight;
117465       pNew->prereqAll = prereqAll;
117466       pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
117467     }
117468   }
117469 
117470 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
117471   /* If a term is the BETWEEN operator, create two new virtual terms
117472   ** that define the range that the BETWEEN implements.  For example:
117473   **
117474   **      a BETWEEN b AND c
117475   **
117476   ** is converted into:
117477   **
117478   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
117479   **
117480   ** The two new terms are added onto the end of the WhereClause object.
117481   ** The new terms are "dynamic" and are children of the original BETWEEN
117482   ** term.  That means that if the BETWEEN term is coded, the children are
117483   ** skipped.  Or, if the children are satisfied by an index, the original
117484   ** BETWEEN term is skipped.
117485   */
117486   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
117487     ExprList *pList = pExpr->x.pList;
117488     int i;
117489     static const u8 ops[] = {TK_GE, TK_LE};
117490     assert( pList!=0 );
117491     assert( pList->nExpr==2 );
117492     for(i=0; i<2; i++){
117493       Expr *pNewExpr;
117494       int idxNew;
117495       pNewExpr = sqlite3PExpr(pParse, ops[i],
117496                              sqlite3ExprDup(db, pExpr->pLeft, 0),
117497                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
117498       transferJoinMarkings(pNewExpr, pExpr);
117499       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
117500       testcase( idxNew==0 );
117501       exprAnalyze(pSrc, pWC, idxNew);
117502       pTerm = &pWC->a[idxTerm];
117503       markTermAsChild(pWC, idxNew, idxTerm);
117504     }
117505   }
117506 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
117507 
117508 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
117509   /* Analyze a term that is composed of two or more subterms connected by
117510   ** an OR operator.
117511   */
117512   else if( pExpr->op==TK_OR ){
117513     assert( pWC->op==TK_AND );
117514     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
117515     pTerm = &pWC->a[idxTerm];
117516   }
117517 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
117518 
117519 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
117520   /* Add constraints to reduce the search space on a LIKE or GLOB
117521   ** operator.
117522   **
117523   ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
117524   **
117525   **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
117526   **
117527   ** The last character of the prefix "abc" is incremented to form the
117528   ** termination condition "abd".  If case is not significant (the default
117529   ** for LIKE) then the lower-bound is made all uppercase and the upper-
117530   ** bound is made all lowercase so that the bounds also work when comparing
117531   ** BLOBs.
117532   */
117533   if( pWC->op==TK_AND
117534    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
117535   ){
117536     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
117537     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
117538     Expr *pNewExpr1;
117539     Expr *pNewExpr2;
117540     int idxNew1;
117541     int idxNew2;
117542     const char *zCollSeqName;     /* Name of collating sequence */
117543     const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
117544 
117545     pLeft = pExpr->x.pList->a[1].pExpr;
117546     pStr2 = sqlite3ExprDup(db, pStr1, 0);
117547 
117548     /* Convert the lower bound to upper-case and the upper bound to
117549     ** lower-case (upper-case is less than lower-case in ASCII) so that
117550     ** the range constraints also work for BLOBs
117551     */
117552     if( noCase && !pParse->db->mallocFailed ){
117553       int i;
117554       char c;
117555       pTerm->wtFlags |= TERM_LIKE;
117556       for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
117557         pStr1->u.zToken[i] = sqlite3Toupper(c);
117558         pStr2->u.zToken[i] = sqlite3Tolower(c);
117559       }
117560     }
117561 
117562     if( !db->mallocFailed ){
117563       u8 c, *pC;       /* Last character before the first wildcard */
117564       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
117565       c = *pC;
117566       if( noCase ){
117567         /* The point is to increment the last character before the first
117568         ** wildcard.  But if we increment '@', that will push it into the
117569         ** alphabetic range where case conversions will mess up the
117570         ** inequality.  To avoid this, make sure to also run the full
117571         ** LIKE on all candidate expressions by clearing the isComplete flag
117572         */
117573         if( c=='A'-1 ) isComplete = 0;
117574         c = sqlite3UpperToLower[c];
117575       }
117576       *pC = c + 1;
117577     }
117578     zCollSeqName = noCase ? "NOCASE" : "BINARY";
117579     pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
117580     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
117581            sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
117582            pStr1, 0);
117583     transferJoinMarkings(pNewExpr1, pExpr);
117584     idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
117585     testcase( idxNew1==0 );
117586     exprAnalyze(pSrc, pWC, idxNew1);
117587     pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
117588     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
117589            sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
117590            pStr2, 0);
117591     transferJoinMarkings(pNewExpr2, pExpr);
117592     idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
117593     testcase( idxNew2==0 );
117594     exprAnalyze(pSrc, pWC, idxNew2);
117595     pTerm = &pWC->a[idxTerm];
117596     if( isComplete ){
117597       markTermAsChild(pWC, idxNew1, idxTerm);
117598       markTermAsChild(pWC, idxNew2, idxTerm);
117599     }
117600   }
117601 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
117602 
117603 #ifndef SQLITE_OMIT_VIRTUALTABLE
117604   /* Add a WO_MATCH auxiliary term to the constraint set if the
117605   ** current expression is of the form:  column MATCH expr.
117606   ** This information is used by the xBestIndex methods of
117607   ** virtual tables.  The native query optimizer does not attempt
117608   ** to do anything with MATCH functions.
117609   */
117610   if( isMatchOfColumn(pExpr) ){
117611     int idxNew;
117612     Expr *pRight, *pLeft;
117613     WhereTerm *pNewTerm;
117614     Bitmask prereqColumn, prereqExpr;
117615 
117616     pRight = pExpr->x.pList->a[0].pExpr;
117617     pLeft = pExpr->x.pList->a[1].pExpr;
117618     prereqExpr = exprTableUsage(pMaskSet, pRight);
117619     prereqColumn = exprTableUsage(pMaskSet, pLeft);
117620     if( (prereqExpr & prereqColumn)==0 ){
117621       Expr *pNewExpr;
117622       pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
117623                               0, sqlite3ExprDup(db, pRight, 0), 0);
117624       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
117625       testcase( idxNew==0 );
117626       pNewTerm = &pWC->a[idxNew];
117627       pNewTerm->prereqRight = prereqExpr;
117628       pNewTerm->leftCursor = pLeft->iTable;
117629       pNewTerm->u.leftColumn = pLeft->iColumn;
117630       pNewTerm->eOperator = WO_MATCH;
117631       markTermAsChild(pWC, idxNew, idxTerm);
117632       pTerm = &pWC->a[idxTerm];
117633       pTerm->wtFlags |= TERM_COPIED;
117634       pNewTerm->prereqAll = pTerm->prereqAll;
117635     }
117636   }
117637 #endif /* SQLITE_OMIT_VIRTUALTABLE */
117638 
117639 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
117640   /* When sqlite_stat3 histogram data is available an operator of the
117641   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
117642   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
117643   ** virtual term of that form.
117644   **
117645   ** Note that the virtual term must be tagged with TERM_VNULL.  This
117646   ** TERM_VNULL tag will suppress the not-null check at the beginning
117647   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
117648   ** the start of the loop will prevent any results from being returned.
117649   */
117650   if( pExpr->op==TK_NOTNULL
117651    && pExpr->pLeft->op==TK_COLUMN
117652    && pExpr->pLeft->iColumn>=0
117653    && OptimizationEnabled(db, SQLITE_Stat34)
117654   ){
117655     Expr *pNewExpr;
117656     Expr *pLeft = pExpr->pLeft;
117657     int idxNew;
117658     WhereTerm *pNewTerm;
117659 
117660     pNewExpr = sqlite3PExpr(pParse, TK_GT,
117661                             sqlite3ExprDup(db, pLeft, 0),
117662                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
117663 
117664     idxNew = whereClauseInsert(pWC, pNewExpr,
117665                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
117666     if( idxNew ){
117667       pNewTerm = &pWC->a[idxNew];
117668       pNewTerm->prereqRight = 0;
117669       pNewTerm->leftCursor = pLeft->iTable;
117670       pNewTerm->u.leftColumn = pLeft->iColumn;
117671       pNewTerm->eOperator = WO_GT;
117672       markTermAsChild(pWC, idxNew, idxTerm);
117673       pTerm = &pWC->a[idxTerm];
117674       pTerm->wtFlags |= TERM_COPIED;
117675       pNewTerm->prereqAll = pTerm->prereqAll;
117676     }
117677   }
117678 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
117679 
117680   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
117681   ** an index for tables to the left of the join.
117682   */
117683   pTerm->prereqRight |= extraRight;
117684 }
117685 
117686 /*
117687 ** This function searches pList for an entry that matches the iCol-th column
117688 ** of index pIdx.
117689 **
117690 ** If such an expression is found, its index in pList->a[] is returned. If
117691 ** no expression is found, -1 is returned.
117692 */
117693 static int findIndexCol(
117694   Parse *pParse,                  /* Parse context */
117695   ExprList *pList,                /* Expression list to search */
117696   int iBase,                      /* Cursor for table associated with pIdx */
117697   Index *pIdx,                    /* Index to match column of */
117698   int iCol                        /* Column of index to match */
117699 ){
117700   int i;
117701   const char *zColl = pIdx->azColl[iCol];
117702 
117703   for(i=0; i<pList->nExpr; i++){
117704     Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
117705     if( p->op==TK_COLUMN
117706      && p->iColumn==pIdx->aiColumn[iCol]
117707      && p->iTable==iBase
117708     ){
117709       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
117710       if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
117711         return i;
117712       }
117713     }
117714   }
117715 
117716   return -1;
117717 }
117718 
117719 /*
117720 ** Return true if the DISTINCT expression-list passed as the third argument
117721 ** is redundant.
117722 **
117723 ** A DISTINCT list is redundant if the database contains some subset of
117724 ** columns that are unique and non-null.
117725 */
117726 static int isDistinctRedundant(
117727   Parse *pParse,            /* Parsing context */
117728   SrcList *pTabList,        /* The FROM clause */
117729   WhereClause *pWC,         /* The WHERE clause */
117730   ExprList *pDistinct       /* The result set that needs to be DISTINCT */
117731 ){
117732   Table *pTab;
117733   Index *pIdx;
117734   int i;
117735   int iBase;
117736 
117737   /* If there is more than one table or sub-select in the FROM clause of
117738   ** this query, then it will not be possible to show that the DISTINCT
117739   ** clause is redundant. */
117740   if( pTabList->nSrc!=1 ) return 0;
117741   iBase = pTabList->a[0].iCursor;
117742   pTab = pTabList->a[0].pTab;
117743 
117744   /* If any of the expressions is an IPK column on table iBase, then return
117745   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
117746   ** current SELECT is a correlated sub-query.
117747   */
117748   for(i=0; i<pDistinct->nExpr; i++){
117749     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
117750     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
117751   }
117752 
117753   /* Loop through all indices on the table, checking each to see if it makes
117754   ** the DISTINCT qualifier redundant. It does so if:
117755   **
117756   **   1. The index is itself UNIQUE, and
117757   **
117758   **   2. All of the columns in the index are either part of the pDistinct
117759   **      list, or else the WHERE clause contains a term of the form "col=X",
117760   **      where X is a constant value. The collation sequences of the
117761   **      comparison and select-list expressions must match those of the index.
117762   **
117763   **   3. All of those index columns for which the WHERE clause does not
117764   **      contain a "col=X" term are subject to a NOT NULL constraint.
117765   */
117766   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
117767     if( !IsUniqueIndex(pIdx) ) continue;
117768     for(i=0; i<pIdx->nKeyCol; i++){
117769       i16 iCol = pIdx->aiColumn[i];
117770       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
117771         int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
117772         if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
117773           break;
117774         }
117775       }
117776     }
117777     if( i==pIdx->nKeyCol ){
117778       /* This index implies that the DISTINCT qualifier is redundant. */
117779       return 1;
117780     }
117781   }
117782 
117783   return 0;
117784 }
117785 
117786 
117787 /*
117788 ** Estimate the logarithm of the input value to base 2.
117789 */
117790 static LogEst estLog(LogEst N){
117791   return N<=10 ? 0 : sqlite3LogEst(N) - 33;
117792 }
117793 
117794 /*
117795 ** Two routines for printing the content of an sqlite3_index_info
117796 ** structure.  Used for testing and debugging only.  If neither
117797 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
117798 ** are no-ops.
117799 */
117800 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
117801 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
117802   int i;
117803   if( !sqlite3WhereTrace ) return;
117804   for(i=0; i<p->nConstraint; i++){
117805     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
117806        i,
117807        p->aConstraint[i].iColumn,
117808        p->aConstraint[i].iTermOffset,
117809        p->aConstraint[i].op,
117810        p->aConstraint[i].usable);
117811   }
117812   for(i=0; i<p->nOrderBy; i++){
117813     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
117814        i,
117815        p->aOrderBy[i].iColumn,
117816        p->aOrderBy[i].desc);
117817   }
117818 }
117819 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
117820   int i;
117821   if( !sqlite3WhereTrace ) return;
117822   for(i=0; i<p->nConstraint; i++){
117823     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
117824        i,
117825        p->aConstraintUsage[i].argvIndex,
117826        p->aConstraintUsage[i].omit);
117827   }
117828   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
117829   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
117830   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
117831   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
117832   sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
117833 }
117834 #else
117835 #define TRACE_IDX_INPUTS(A)
117836 #define TRACE_IDX_OUTPUTS(A)
117837 #endif
117838 
117839 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
117840 /*
117841 ** Return TRUE if the WHERE clause term pTerm is of a form where it
117842 ** could be used with an index to access pSrc, assuming an appropriate
117843 ** index existed.
117844 */
117845 static int termCanDriveIndex(
117846   WhereTerm *pTerm,              /* WHERE clause term to check */
117847   struct SrcList_item *pSrc,     /* Table we are trying to access */
117848   Bitmask notReady               /* Tables in outer loops of the join */
117849 ){
117850   char aff;
117851   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
117852   if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
117853   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
117854   if( pTerm->u.leftColumn<0 ) return 0;
117855   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
117856   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
117857   return 1;
117858 }
117859 #endif
117860 
117861 
117862 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
117863 /*
117864 ** Generate code to construct the Index object for an automatic index
117865 ** and to set up the WhereLevel object pLevel so that the code generator
117866 ** makes use of the automatic index.
117867 */
117868 static void constructAutomaticIndex(
117869   Parse *pParse,              /* The parsing context */
117870   WhereClause *pWC,           /* The WHERE clause */
117871   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
117872   Bitmask notReady,           /* Mask of cursors that are not available */
117873   WhereLevel *pLevel          /* Write new index here */
117874 ){
117875   int nKeyCol;                /* Number of columns in the constructed index */
117876   WhereTerm *pTerm;           /* A single term of the WHERE clause */
117877   WhereTerm *pWCEnd;          /* End of pWC->a[] */
117878   Index *pIdx;                /* Object describing the transient index */
117879   Vdbe *v;                    /* Prepared statement under construction */
117880   int addrInit;               /* Address of the initialization bypass jump */
117881   Table *pTable;              /* The table being indexed */
117882   int addrTop;                /* Top of the index fill loop */
117883   int regRecord;              /* Register holding an index record */
117884   int n;                      /* Column counter */
117885   int i;                      /* Loop counter */
117886   int mxBitCol;               /* Maximum column in pSrc->colUsed */
117887   CollSeq *pColl;             /* Collating sequence to on a column */
117888   WhereLoop *pLoop;           /* The Loop object */
117889   char *zNotUsed;             /* Extra space on the end of pIdx */
117890   Bitmask idxCols;            /* Bitmap of columns used for indexing */
117891   Bitmask extraCols;          /* Bitmap of additional columns */
117892   u8 sentWarning = 0;         /* True if a warnning has been issued */
117893   Expr *pPartial = 0;         /* Partial Index Expression */
117894   int iContinue = 0;          /* Jump here to skip excluded rows */
117895 
117896   /* Generate code to skip over the creation and initialization of the
117897   ** transient index on 2nd and subsequent iterations of the loop. */
117898   v = pParse->pVdbe;
117899   assert( v!=0 );
117900   addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
117901 
117902   /* Count the number of columns that will be added to the index
117903   ** and used to match WHERE clause constraints */
117904   nKeyCol = 0;
117905   pTable = pSrc->pTab;
117906   pWCEnd = &pWC->a[pWC->nTerm];
117907   pLoop = pLevel->pWLoop;
117908   idxCols = 0;
117909   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
117910     Expr *pExpr = pTerm->pExpr;
117911     assert( !ExprHasProperty(pExpr, EP_FromJoin)    /* prereq always non-zero */
117912          || pExpr->iRightJoinTable!=pSrc->iCursor   /*   for the right-hand   */
117913          || pLoop->prereq!=0 );                     /*   table of a LEFT JOIN */
117914     if( pLoop->prereq==0
117915      && (pTerm->wtFlags & TERM_VIRTUAL)==0
117916      && !ExprHasProperty(pExpr, EP_FromJoin)
117917      && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
117918       pPartial = sqlite3ExprAnd(pParse->db, pPartial,
117919                                 sqlite3ExprDup(pParse->db, pExpr, 0));
117920     }
117921     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
117922       int iCol = pTerm->u.leftColumn;
117923       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
117924       testcase( iCol==BMS );
117925       testcase( iCol==BMS-1 );
117926       if( !sentWarning ){
117927         sqlite3_log(SQLITE_WARNING_AUTOINDEX,
117928             "automatic index on %s(%s)", pTable->zName,
117929             pTable->aCol[iCol].zName);
117930         sentWarning = 1;
117931       }
117932       if( (idxCols & cMask)==0 ){
117933         if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
117934           goto end_auto_index_create;
117935         }
117936         pLoop->aLTerm[nKeyCol++] = pTerm;
117937         idxCols |= cMask;
117938       }
117939     }
117940   }
117941   assert( nKeyCol>0 );
117942   pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
117943   pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
117944                      | WHERE_AUTO_INDEX;
117945 
117946   /* Count the number of additional columns needed to create a
117947   ** covering index.  A "covering index" is an index that contains all
117948   ** columns that are needed by the query.  With a covering index, the
117949   ** original table never needs to be accessed.  Automatic indices must
117950   ** be a covering index because the index will not be updated if the
117951   ** original table changes and the index and table cannot both be used
117952   ** if they go out of sync.
117953   */
117954   extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
117955   mxBitCol = MIN(BMS-1,pTable->nCol);
117956   testcase( pTable->nCol==BMS-1 );
117957   testcase( pTable->nCol==BMS-2 );
117958   for(i=0; i<mxBitCol; i++){
117959     if( extraCols & MASKBIT(i) ) nKeyCol++;
117960   }
117961   if( pSrc->colUsed & MASKBIT(BMS-1) ){
117962     nKeyCol += pTable->nCol - BMS + 1;
117963   }
117964 
117965   /* Construct the Index object to describe this index */
117966   pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
117967   if( pIdx==0 ) goto end_auto_index_create;
117968   pLoop->u.btree.pIndex = pIdx;
117969   pIdx->zName = "auto-index";
117970   pIdx->pTable = pTable;
117971   n = 0;
117972   idxCols = 0;
117973   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
117974     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
117975       int iCol = pTerm->u.leftColumn;
117976       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
117977       testcase( iCol==BMS-1 );
117978       testcase( iCol==BMS );
117979       if( (idxCols & cMask)==0 ){
117980         Expr *pX = pTerm->pExpr;
117981         idxCols |= cMask;
117982         pIdx->aiColumn[n] = pTerm->u.leftColumn;
117983         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
117984         pIdx->azColl[n] = pColl ? pColl->zName : "BINARY";
117985         n++;
117986       }
117987     }
117988   }
117989   assert( (u32)n==pLoop->u.btree.nEq );
117990 
117991   /* Add additional columns needed to make the automatic index into
117992   ** a covering index */
117993   for(i=0; i<mxBitCol; i++){
117994     if( extraCols & MASKBIT(i) ){
117995       pIdx->aiColumn[n] = i;
117996       pIdx->azColl[n] = "BINARY";
117997       n++;
117998     }
117999   }
118000   if( pSrc->colUsed & MASKBIT(BMS-1) ){
118001     for(i=BMS-1; i<pTable->nCol; i++){
118002       pIdx->aiColumn[n] = i;
118003       pIdx->azColl[n] = "BINARY";
118004       n++;
118005     }
118006   }
118007   assert( n==nKeyCol );
118008   pIdx->aiColumn[n] = -1;
118009   pIdx->azColl[n] = "BINARY";
118010 
118011   /* Create the automatic index */
118012   assert( pLevel->iIdxCur>=0 );
118013   pLevel->iIdxCur = pParse->nTab++;
118014   sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
118015   sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
118016   VdbeComment((v, "for %s", pTable->zName));
118017 
118018   /* Fill the automatic index with content */
118019   sqlite3ExprCachePush(pParse);
118020   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
118021   if( pPartial ){
118022     iContinue = sqlite3VdbeMakeLabel(v);
118023     sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
118024     pLoop->wsFlags |= WHERE_PARTIALIDX;
118025   }
118026   regRecord = sqlite3GetTempReg(pParse);
118027   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
118028   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
118029   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
118030   if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
118031   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
118032   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
118033   sqlite3VdbeJumpHere(v, addrTop);
118034   sqlite3ReleaseTempReg(pParse, regRecord);
118035   sqlite3ExprCachePop(pParse);
118036 
118037   /* Jump here when skipping the initialization */
118038   sqlite3VdbeJumpHere(v, addrInit);
118039 
118040 end_auto_index_create:
118041   sqlite3ExprDelete(pParse->db, pPartial);
118042 }
118043 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
118044 
118045 #ifndef SQLITE_OMIT_VIRTUALTABLE
118046 /*
118047 ** Allocate and populate an sqlite3_index_info structure. It is the
118048 ** responsibility of the caller to eventually release the structure
118049 ** by passing the pointer returned by this function to sqlite3_free().
118050 */
118051 static sqlite3_index_info *allocateIndexInfo(
118052   Parse *pParse,
118053   WhereClause *pWC,
118054   struct SrcList_item *pSrc,
118055   ExprList *pOrderBy
118056 ){
118057   int i, j;
118058   int nTerm;
118059   struct sqlite3_index_constraint *pIdxCons;
118060   struct sqlite3_index_orderby *pIdxOrderBy;
118061   struct sqlite3_index_constraint_usage *pUsage;
118062   WhereTerm *pTerm;
118063   int nOrderBy;
118064   sqlite3_index_info *pIdxInfo;
118065 
118066   /* Count the number of possible WHERE clause constraints referring
118067   ** to this virtual table */
118068   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
118069     if( pTerm->leftCursor != pSrc->iCursor ) continue;
118070     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
118071     testcase( pTerm->eOperator & WO_IN );
118072     testcase( pTerm->eOperator & WO_ISNULL );
118073     testcase( pTerm->eOperator & WO_ALL );
118074     if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
118075     if( pTerm->wtFlags & TERM_VNULL ) continue;
118076     nTerm++;
118077   }
118078 
118079   /* If the ORDER BY clause contains only columns in the current
118080   ** virtual table then allocate space for the aOrderBy part of
118081   ** the sqlite3_index_info structure.
118082   */
118083   nOrderBy = 0;
118084   if( pOrderBy ){
118085     int n = pOrderBy->nExpr;
118086     for(i=0; i<n; i++){
118087       Expr *pExpr = pOrderBy->a[i].pExpr;
118088       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
118089     }
118090     if( i==n){
118091       nOrderBy = n;
118092     }
118093   }
118094 
118095   /* Allocate the sqlite3_index_info structure
118096   */
118097   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
118098                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
118099                            + sizeof(*pIdxOrderBy)*nOrderBy );
118100   if( pIdxInfo==0 ){
118101     sqlite3ErrorMsg(pParse, "out of memory");
118102     return 0;
118103   }
118104 
118105   /* Initialize the structure.  The sqlite3_index_info structure contains
118106   ** many fields that are declared "const" to prevent xBestIndex from
118107   ** changing them.  We have to do some funky casting in order to
118108   ** initialize those fields.
118109   */
118110   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
118111   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
118112   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
118113   *(int*)&pIdxInfo->nConstraint = nTerm;
118114   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
118115   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
118116   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
118117   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
118118                                                                    pUsage;
118119 
118120   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
118121     u8 op;
118122     if( pTerm->leftCursor != pSrc->iCursor ) continue;
118123     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
118124     testcase( pTerm->eOperator & WO_IN );
118125     testcase( pTerm->eOperator & WO_ISNULL );
118126     testcase( pTerm->eOperator & WO_ALL );
118127     if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
118128     if( pTerm->wtFlags & TERM_VNULL ) continue;
118129     pIdxCons[j].iColumn = pTerm->u.leftColumn;
118130     pIdxCons[j].iTermOffset = i;
118131     op = (u8)pTerm->eOperator & WO_ALL;
118132     if( op==WO_IN ) op = WO_EQ;
118133     pIdxCons[j].op = op;
118134     /* The direct assignment in the previous line is possible only because
118135     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
118136     ** following asserts verify this fact. */
118137     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
118138     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
118139     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
118140     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
118141     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
118142     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
118143     assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
118144     j++;
118145   }
118146   for(i=0; i<nOrderBy; i++){
118147     Expr *pExpr = pOrderBy->a[i].pExpr;
118148     pIdxOrderBy[i].iColumn = pExpr->iColumn;
118149     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
118150   }
118151 
118152   return pIdxInfo;
118153 }
118154 
118155 /*
118156 ** The table object reference passed as the second argument to this function
118157 ** must represent a virtual table. This function invokes the xBestIndex()
118158 ** method of the virtual table with the sqlite3_index_info object that
118159 ** comes in as the 3rd argument to this function.
118160 **
118161 ** If an error occurs, pParse is populated with an error message and a
118162 ** non-zero value is returned. Otherwise, 0 is returned and the output
118163 ** part of the sqlite3_index_info structure is left populated.
118164 **
118165 ** Whether or not an error is returned, it is the responsibility of the
118166 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
118167 ** that this is required.
118168 */
118169 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
118170   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
118171   int i;
118172   int rc;
118173 
118174   TRACE_IDX_INPUTS(p);
118175   rc = pVtab->pModule->xBestIndex(pVtab, p);
118176   TRACE_IDX_OUTPUTS(p);
118177 
118178   if( rc!=SQLITE_OK ){
118179     if( rc==SQLITE_NOMEM ){
118180       pParse->db->mallocFailed = 1;
118181     }else if( !pVtab->zErrMsg ){
118182       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
118183     }else{
118184       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
118185     }
118186   }
118187   sqlite3_free(pVtab->zErrMsg);
118188   pVtab->zErrMsg = 0;
118189 
118190   for(i=0; i<p->nConstraint; i++){
118191     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
118192       sqlite3ErrorMsg(pParse,
118193           "table %s: xBestIndex returned an invalid plan", pTab->zName);
118194     }
118195   }
118196 
118197   return pParse->nErr;
118198 }
118199 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
118200 
118201 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118202 /*
118203 ** Estimate the location of a particular key among all keys in an
118204 ** index.  Store the results in aStat as follows:
118205 **
118206 **    aStat[0]      Est. number of rows less than pRec
118207 **    aStat[1]      Est. number of rows equal to pRec
118208 **
118209 ** Return the index of the sample that is the smallest sample that
118210 ** is greater than or equal to pRec. Note that this index is not an index
118211 ** into the aSample[] array - it is an index into a virtual set of samples
118212 ** based on the contents of aSample[] and the number of fields in record
118213 ** pRec.
118214 */
118215 static int whereKeyStats(
118216   Parse *pParse,              /* Database connection */
118217   Index *pIdx,                /* Index to consider domain of */
118218   UnpackedRecord *pRec,       /* Vector of values to consider */
118219   int roundUp,                /* Round up if true.  Round down if false */
118220   tRowcnt *aStat              /* OUT: stats written here */
118221 ){
118222   IndexSample *aSample = pIdx->aSample;
118223   int iCol;                   /* Index of required stats in anEq[] etc. */
118224   int i;                      /* Index of first sample >= pRec */
118225   int iSample;                /* Smallest sample larger than or equal to pRec */
118226   int iMin = 0;               /* Smallest sample not yet tested */
118227   int iTest;                  /* Next sample to test */
118228   int res;                    /* Result of comparison operation */
118229   int nField;                 /* Number of fields in pRec */
118230   tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */
118231 
118232 #ifndef SQLITE_DEBUG
118233   UNUSED_PARAMETER( pParse );
118234 #endif
118235   assert( pRec!=0 );
118236   assert( pIdx->nSample>0 );
118237   assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
118238 
118239   /* Do a binary search to find the first sample greater than or equal
118240   ** to pRec. If pRec contains a single field, the set of samples to search
118241   ** is simply the aSample[] array. If the samples in aSample[] contain more
118242   ** than one fields, all fields following the first are ignored.
118243   **
118244   ** If pRec contains N fields, where N is more than one, then as well as the
118245   ** samples in aSample[] (truncated to N fields), the search also has to
118246   ** consider prefixes of those samples. For example, if the set of samples
118247   ** in aSample is:
118248   **
118249   **     aSample[0] = (a, 5)
118250   **     aSample[1] = (a, 10)
118251   **     aSample[2] = (b, 5)
118252   **     aSample[3] = (c, 100)
118253   **     aSample[4] = (c, 105)
118254   **
118255   ** Then the search space should ideally be the samples above and the
118256   ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
118257   ** the code actually searches this set:
118258   **
118259   **     0: (a)
118260   **     1: (a, 5)
118261   **     2: (a, 10)
118262   **     3: (a, 10)
118263   **     4: (b)
118264   **     5: (b, 5)
118265   **     6: (c)
118266   **     7: (c, 100)
118267   **     8: (c, 105)
118268   **     9: (c, 105)
118269   **
118270   ** For each sample in the aSample[] array, N samples are present in the
118271   ** effective sample array. In the above, samples 0 and 1 are based on
118272   ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
118273   **
118274   ** Often, sample i of each block of N effective samples has (i+1) fields.
118275   ** Except, each sample may be extended to ensure that it is greater than or
118276   ** equal to the previous sample in the array. For example, in the above,
118277   ** sample 2 is the first sample of a block of N samples, so at first it
118278   ** appears that it should be 1 field in size. However, that would make it
118279   ** smaller than sample 1, so the binary search would not work. As a result,
118280   ** it is extended to two fields. The duplicates that this creates do not
118281   ** cause any problems.
118282   */
118283   nField = pRec->nField;
118284   iCol = 0;
118285   iSample = pIdx->nSample * nField;
118286   do{
118287     int iSamp;                    /* Index in aSample[] of test sample */
118288     int n;                        /* Number of fields in test sample */
118289 
118290     iTest = (iMin+iSample)/2;
118291     iSamp = iTest / nField;
118292     if( iSamp>0 ){
118293       /* The proposed effective sample is a prefix of sample aSample[iSamp].
118294       ** Specifically, the shortest prefix of at least (1 + iTest%nField)
118295       ** fields that is greater than the previous effective sample.  */
118296       for(n=(iTest % nField) + 1; n<nField; n++){
118297         if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
118298       }
118299     }else{
118300       n = iTest + 1;
118301     }
118302 
118303     pRec->nField = n;
118304     res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
118305     if( res<0 ){
118306       iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
118307       iMin = iTest+1;
118308     }else if( res==0 && n<nField ){
118309       iLower = aSample[iSamp].anLt[n-1];
118310       iMin = iTest+1;
118311       res = -1;
118312     }else{
118313       iSample = iTest;
118314       iCol = n-1;
118315     }
118316   }while( res && iMin<iSample );
118317   i = iSample / nField;
118318 
118319 #ifdef SQLITE_DEBUG
118320   /* The following assert statements check that the binary search code
118321   ** above found the right answer. This block serves no purpose other
118322   ** than to invoke the asserts.  */
118323   if( pParse->db->mallocFailed==0 ){
118324     if( res==0 ){
118325       /* If (res==0) is true, then pRec must be equal to sample i. */
118326       assert( i<pIdx->nSample );
118327       assert( iCol==nField-1 );
118328       pRec->nField = nField;
118329       assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
118330            || pParse->db->mallocFailed
118331       );
118332     }else{
118333       /* Unless i==pIdx->nSample, indicating that pRec is larger than
118334       ** all samples in the aSample[] array, pRec must be smaller than the
118335       ** (iCol+1) field prefix of sample i.  */
118336       assert( i<=pIdx->nSample && i>=0 );
118337       pRec->nField = iCol+1;
118338       assert( i==pIdx->nSample
118339            || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
118340            || pParse->db->mallocFailed );
118341 
118342       /* if i==0 and iCol==0, then record pRec is smaller than all samples
118343       ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
118344       ** be greater than or equal to the (iCol) field prefix of sample i.
118345       ** If (i>0), then pRec must also be greater than sample (i-1).  */
118346       if( iCol>0 ){
118347         pRec->nField = iCol;
118348         assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
118349              || pParse->db->mallocFailed );
118350       }
118351       if( i>0 ){
118352         pRec->nField = nField;
118353         assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
118354              || pParse->db->mallocFailed );
118355       }
118356     }
118357   }
118358 #endif /* ifdef SQLITE_DEBUG */
118359 
118360   if( res==0 ){
118361     /* Record pRec is equal to sample i */
118362     assert( iCol==nField-1 );
118363     aStat[0] = aSample[i].anLt[iCol];
118364     aStat[1] = aSample[i].anEq[iCol];
118365   }else{
118366     /* At this point, the (iCol+1) field prefix of aSample[i] is the first
118367     ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
118368     ** is larger than all samples in the array. */
118369     tRowcnt iUpper, iGap;
118370     if( i>=pIdx->nSample ){
118371       iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
118372     }else{
118373       iUpper = aSample[i].anLt[iCol];
118374     }
118375 
118376     if( iLower>=iUpper ){
118377       iGap = 0;
118378     }else{
118379       iGap = iUpper - iLower;
118380     }
118381     if( roundUp ){
118382       iGap = (iGap*2)/3;
118383     }else{
118384       iGap = iGap/3;
118385     }
118386     aStat[0] = iLower + iGap;
118387     aStat[1] = pIdx->aAvgEq[iCol];
118388   }
118389 
118390   /* Restore the pRec->nField value before returning.  */
118391   pRec->nField = nField;
118392   return i;
118393 }
118394 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
118395 
118396 /*
118397 ** If it is not NULL, pTerm is a term that provides an upper or lower
118398 ** bound on a range scan. Without considering pTerm, it is estimated
118399 ** that the scan will visit nNew rows. This function returns the number
118400 ** estimated to be visited after taking pTerm into account.
118401 **
118402 ** If the user explicitly specified a likelihood() value for this term,
118403 ** then the return value is the likelihood multiplied by the number of
118404 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
118405 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
118406 */
118407 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
118408   LogEst nRet = nNew;
118409   if( pTerm ){
118410     if( pTerm->truthProb<=0 ){
118411       nRet += pTerm->truthProb;
118412     }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
118413       nRet -= 20;        assert( 20==sqlite3LogEst(4) );
118414     }
118415   }
118416   return nRet;
118417 }
118418 
118419 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118420 /*
118421 ** This function is called to estimate the number of rows visited by a
118422 ** range-scan on a skip-scan index. For example:
118423 **
118424 **   CREATE INDEX i1 ON t1(a, b, c);
118425 **   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
118426 **
118427 ** Value pLoop->nOut is currently set to the estimated number of rows
118428 ** visited for scanning (a=? AND b=?). This function reduces that estimate
118429 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
118430 ** on the stat4 data for the index. this scan will be peformed multiple
118431 ** times (once for each (a,b) combination that matches a=?) is dealt with
118432 ** by the caller.
118433 **
118434 ** It does this by scanning through all stat4 samples, comparing values
118435 ** extracted from pLower and pUpper with the corresponding column in each
118436 ** sample. If L and U are the number of samples found to be less than or
118437 ** equal to the values extracted from pLower and pUpper respectively, and
118438 ** N is the total number of samples, the pLoop->nOut value is adjusted
118439 ** as follows:
118440 **
118441 **   nOut = nOut * ( min(U - L, 1) / N )
118442 **
118443 ** If pLower is NULL, or a value cannot be extracted from the term, L is
118444 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
118445 ** U is set to N.
118446 **
118447 ** Normally, this function sets *pbDone to 1 before returning. However,
118448 ** if no value can be extracted from either pLower or pUpper (and so the
118449 ** estimate of the number of rows delivered remains unchanged), *pbDone
118450 ** is left as is.
118451 **
118452 ** If an error occurs, an SQLite error code is returned. Otherwise,
118453 ** SQLITE_OK.
118454 */
118455 static int whereRangeSkipScanEst(
118456   Parse *pParse,       /* Parsing & code generating context */
118457   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
118458   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
118459   WhereLoop *pLoop,    /* Update the .nOut value of this loop */
118460   int *pbDone          /* Set to true if at least one expr. value extracted */
118461 ){
118462   Index *p = pLoop->u.btree.pIndex;
118463   int nEq = pLoop->u.btree.nEq;
118464   sqlite3 *db = pParse->db;
118465   int nLower = -1;
118466   int nUpper = p->nSample+1;
118467   int rc = SQLITE_OK;
118468   int iCol = p->aiColumn[nEq];
118469   u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
118470   CollSeq *pColl;
118471 
118472   sqlite3_value *p1 = 0;          /* Value extracted from pLower */
118473   sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
118474   sqlite3_value *pVal = 0;        /* Value extracted from record */
118475 
118476   pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
118477   if( pLower ){
118478     rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
118479     nLower = 0;
118480   }
118481   if( pUpper && rc==SQLITE_OK ){
118482     rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
118483     nUpper = p2 ? 0 : p->nSample;
118484   }
118485 
118486   if( p1 || p2 ){
118487     int i;
118488     int nDiff;
118489     for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
118490       rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
118491       if( rc==SQLITE_OK && p1 ){
118492         int res = sqlite3MemCompare(p1, pVal, pColl);
118493         if( res>=0 ) nLower++;
118494       }
118495       if( rc==SQLITE_OK && p2 ){
118496         int res = sqlite3MemCompare(p2, pVal, pColl);
118497         if( res>=0 ) nUpper++;
118498       }
118499     }
118500     nDiff = (nUpper - nLower);
118501     if( nDiff<=0 ) nDiff = 1;
118502 
118503     /* If there is both an upper and lower bound specified, and the
118504     ** comparisons indicate that they are close together, use the fallback
118505     ** method (assume that the scan visits 1/64 of the rows) for estimating
118506     ** the number of rows visited. Otherwise, estimate the number of rows
118507     ** using the method described in the header comment for this function. */
118508     if( nDiff!=1 || pUpper==0 || pLower==0 ){
118509       int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
118510       pLoop->nOut -= nAdjust;
118511       *pbDone = 1;
118512       WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
118513                            nLower, nUpper, nAdjust*-1, pLoop->nOut));
118514     }
118515 
118516   }else{
118517     assert( *pbDone==0 );
118518   }
118519 
118520   sqlite3ValueFree(p1);
118521   sqlite3ValueFree(p2);
118522   sqlite3ValueFree(pVal);
118523 
118524   return rc;
118525 }
118526 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
118527 
118528 /*
118529 ** This function is used to estimate the number of rows that will be visited
118530 ** by scanning an index for a range of values. The range may have an upper
118531 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
118532 ** and lower bounds are represented by pLower and pUpper respectively. For
118533 ** example, assuming that index p is on t1(a):
118534 **
118535 **   ... FROM t1 WHERE a > ? AND a < ? ...
118536 **                    |_____|   |_____|
118537 **                       |         |
118538 **                     pLower    pUpper
118539 **
118540 ** If either of the upper or lower bound is not present, then NULL is passed in
118541 ** place of the corresponding WhereTerm.
118542 **
118543 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
118544 ** column subject to the range constraint. Or, equivalently, the number of
118545 ** equality constraints optimized by the proposed index scan. For example,
118546 ** assuming index p is on t1(a, b), and the SQL query is:
118547 **
118548 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
118549 **
118550 ** then nEq is set to 1 (as the range restricted column, b, is the second
118551 ** left-most column of the index). Or, if the query is:
118552 **
118553 **   ... FROM t1 WHERE a > ? AND a < ? ...
118554 **
118555 ** then nEq is set to 0.
118556 **
118557 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
118558 ** number of rows that the index scan is expected to visit without
118559 ** considering the range constraints. If nEq is 0, then *pnOut is the number of
118560 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
118561 ** to account for the range constraints pLower and pUpper.
118562 **
118563 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
118564 ** used, a single range inequality reduces the search space by a factor of 4.
118565 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
118566 ** rows visited by a factor of 64.
118567 */
118568 static int whereRangeScanEst(
118569   Parse *pParse,       /* Parsing & code generating context */
118570   WhereLoopBuilder *pBuilder,
118571   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
118572   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
118573   WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
118574 ){
118575   int rc = SQLITE_OK;
118576   int nOut = pLoop->nOut;
118577   LogEst nNew;
118578 
118579 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118580   Index *p = pLoop->u.btree.pIndex;
118581   int nEq = pLoop->u.btree.nEq;
118582 
118583   if( p->nSample>0 && nEq<p->nSampleCol ){
118584     if( nEq==pBuilder->nRecValid ){
118585       UnpackedRecord *pRec = pBuilder->pRec;
118586       tRowcnt a[2];
118587       u8 aff;
118588 
118589       /* Variable iLower will be set to the estimate of the number of rows in
118590       ** the index that are less than the lower bound of the range query. The
118591       ** lower bound being the concatenation of $P and $L, where $P is the
118592       ** key-prefix formed by the nEq values matched against the nEq left-most
118593       ** columns of the index, and $L is the value in pLower.
118594       **
118595       ** Or, if pLower is NULL or $L cannot be extracted from it (because it
118596       ** is not a simple variable or literal value), the lower bound of the
118597       ** range is $P. Due to a quirk in the way whereKeyStats() works, even
118598       ** if $L is available, whereKeyStats() is called for both ($P) and
118599       ** ($P:$L) and the larger of the two returned values is used.
118600       **
118601       ** Similarly, iUpper is to be set to the estimate of the number of rows
118602       ** less than the upper bound of the range query. Where the upper bound
118603       ** is either ($P) or ($P:$U). Again, even if $U is available, both values
118604       ** of iUpper are requested of whereKeyStats() and the smaller used.
118605       **
118606       ** The number of rows between the two bounds is then just iUpper-iLower.
118607       */
118608       tRowcnt iLower;     /* Rows less than the lower bound */
118609       tRowcnt iUpper;     /* Rows less than the upper bound */
118610       int iLwrIdx = -2;   /* aSample[] for the lower bound */
118611       int iUprIdx = -1;   /* aSample[] for the upper bound */
118612 
118613       if( pRec ){
118614         testcase( pRec->nField!=pBuilder->nRecValid );
118615         pRec->nField = pBuilder->nRecValid;
118616       }
118617       if( nEq==p->nKeyCol ){
118618         aff = SQLITE_AFF_INTEGER;
118619       }else{
118620         aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
118621       }
118622       /* Determine iLower and iUpper using ($P) only. */
118623       if( nEq==0 ){
118624         iLower = 0;
118625         iUpper = p->nRowEst0;
118626       }else{
118627         /* Note: this call could be optimized away - since the same values must
118628         ** have been requested when testing key $P in whereEqualScanEst().  */
118629         whereKeyStats(pParse, p, pRec, 0, a);
118630         iLower = a[0];
118631         iUpper = a[0] + a[1];
118632       }
118633 
118634       assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
118635       assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
118636       assert( p->aSortOrder!=0 );
118637       if( p->aSortOrder[nEq] ){
118638         /* The roles of pLower and pUpper are swapped for a DESC index */
118639         SWAP(WhereTerm*, pLower, pUpper);
118640       }
118641 
118642       /* If possible, improve on the iLower estimate using ($P:$L). */
118643       if( pLower ){
118644         int bOk;                    /* True if value is extracted from pExpr */
118645         Expr *pExpr = pLower->pExpr->pRight;
118646         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
118647         if( rc==SQLITE_OK && bOk ){
118648           tRowcnt iNew;
118649           iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
118650           iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
118651           if( iNew>iLower ) iLower = iNew;
118652           nOut--;
118653           pLower = 0;
118654         }
118655       }
118656 
118657       /* If possible, improve on the iUpper estimate using ($P:$U). */
118658       if( pUpper ){
118659         int bOk;                    /* True if value is extracted from pExpr */
118660         Expr *pExpr = pUpper->pExpr->pRight;
118661         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
118662         if( rc==SQLITE_OK && bOk ){
118663           tRowcnt iNew;
118664           iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
118665           iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
118666           if( iNew<iUpper ) iUpper = iNew;
118667           nOut--;
118668           pUpper = 0;
118669         }
118670       }
118671 
118672       pBuilder->pRec = pRec;
118673       if( rc==SQLITE_OK ){
118674         if( iUpper>iLower ){
118675           nNew = sqlite3LogEst(iUpper - iLower);
118676           /* TUNING:  If both iUpper and iLower are derived from the same
118677           ** sample, then assume they are 4x more selective.  This brings
118678           ** the estimated selectivity more in line with what it would be
118679           ** if estimated without the use of STAT3/4 tables. */
118680           if( iLwrIdx==iUprIdx ) nNew -= 20;  assert( 20==sqlite3LogEst(4) );
118681         }else{
118682           nNew = 10;        assert( 10==sqlite3LogEst(2) );
118683         }
118684         if( nNew<nOut ){
118685           nOut = nNew;
118686         }
118687         WHERETRACE(0x10, ("STAT4 range scan: %u..%u  est=%d\n",
118688                            (u32)iLower, (u32)iUpper, nOut));
118689       }
118690     }else{
118691       int bDone = 0;
118692       rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
118693       if( bDone ) return rc;
118694     }
118695   }
118696 #else
118697   UNUSED_PARAMETER(pParse);
118698   UNUSED_PARAMETER(pBuilder);
118699   assert( pLower || pUpper );
118700 #endif
118701   assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
118702   nNew = whereRangeAdjust(pLower, nOut);
118703   nNew = whereRangeAdjust(pUpper, nNew);
118704 
118705   /* TUNING: If there is both an upper and lower limit and neither limit
118706   ** has an application-defined likelihood(), assume the range is
118707   ** reduced by an additional 75%. This means that, by default, an open-ended
118708   ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
118709   ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
118710   ** match 1/64 of the index. */
118711   if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
118712     nNew -= 20;
118713   }
118714 
118715   nOut -= (pLower!=0) + (pUpper!=0);
118716   if( nNew<10 ) nNew = 10;
118717   if( nNew<nOut ) nOut = nNew;
118718 #if defined(WHERETRACE_ENABLED)
118719   if( pLoop->nOut>nOut ){
118720     WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
118721                     pLoop->nOut, nOut));
118722   }
118723 #endif
118724   pLoop->nOut = (LogEst)nOut;
118725   return rc;
118726 }
118727 
118728 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118729 /*
118730 ** Estimate the number of rows that will be returned based on
118731 ** an equality constraint x=VALUE and where that VALUE occurs in
118732 ** the histogram data.  This only works when x is the left-most
118733 ** column of an index and sqlite_stat3 histogram data is available
118734 ** for that index.  When pExpr==NULL that means the constraint is
118735 ** "x IS NULL" instead of "x=VALUE".
118736 **
118737 ** Write the estimated row count into *pnRow and return SQLITE_OK.
118738 ** If unable to make an estimate, leave *pnRow unchanged and return
118739 ** non-zero.
118740 **
118741 ** This routine can fail if it is unable to load a collating sequence
118742 ** required for string comparison, or if unable to allocate memory
118743 ** for a UTF conversion required for comparison.  The error is stored
118744 ** in the pParse structure.
118745 */
118746 static int whereEqualScanEst(
118747   Parse *pParse,       /* Parsing & code generating context */
118748   WhereLoopBuilder *pBuilder,
118749   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
118750   tRowcnt *pnRow       /* Write the revised row estimate here */
118751 ){
118752   Index *p = pBuilder->pNew->u.btree.pIndex;
118753   int nEq = pBuilder->pNew->u.btree.nEq;
118754   UnpackedRecord *pRec = pBuilder->pRec;
118755   u8 aff;                   /* Column affinity */
118756   int rc;                   /* Subfunction return code */
118757   tRowcnt a[2];             /* Statistics */
118758   int bOk;
118759 
118760   assert( nEq>=1 );
118761   assert( nEq<=p->nColumn );
118762   assert( p->aSample!=0 );
118763   assert( p->nSample>0 );
118764   assert( pBuilder->nRecValid<nEq );
118765 
118766   /* If values are not available for all fields of the index to the left
118767   ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
118768   if( pBuilder->nRecValid<(nEq-1) ){
118769     return SQLITE_NOTFOUND;
118770   }
118771 
118772   /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
118773   ** below would return the same value.  */
118774   if( nEq>=p->nColumn ){
118775     *pnRow = 1;
118776     return SQLITE_OK;
118777   }
118778 
118779   aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
118780   rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
118781   pBuilder->pRec = pRec;
118782   if( rc!=SQLITE_OK ) return rc;
118783   if( bOk==0 ) return SQLITE_NOTFOUND;
118784   pBuilder->nRecValid = nEq;
118785 
118786   whereKeyStats(pParse, p, pRec, 0, a);
118787   WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
118788   *pnRow = a[1];
118789 
118790   return rc;
118791 }
118792 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
118793 
118794 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118795 /*
118796 ** Estimate the number of rows that will be returned based on
118797 ** an IN constraint where the right-hand side of the IN operator
118798 ** is a list of values.  Example:
118799 **
118800 **        WHERE x IN (1,2,3,4)
118801 **
118802 ** Write the estimated row count into *pnRow and return SQLITE_OK.
118803 ** If unable to make an estimate, leave *pnRow unchanged and return
118804 ** non-zero.
118805 **
118806 ** This routine can fail if it is unable to load a collating sequence
118807 ** required for string comparison, or if unable to allocate memory
118808 ** for a UTF conversion required for comparison.  The error is stored
118809 ** in the pParse structure.
118810 */
118811 static int whereInScanEst(
118812   Parse *pParse,       /* Parsing & code generating context */
118813   WhereLoopBuilder *pBuilder,
118814   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
118815   tRowcnt *pnRow       /* Write the revised row estimate here */
118816 ){
118817   Index *p = pBuilder->pNew->u.btree.pIndex;
118818   i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
118819   int nRecValid = pBuilder->nRecValid;
118820   int rc = SQLITE_OK;     /* Subfunction return code */
118821   tRowcnt nEst;           /* Number of rows for a single term */
118822   tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
118823   int i;                  /* Loop counter */
118824 
118825   assert( p->aSample!=0 );
118826   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
118827     nEst = nRow0;
118828     rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
118829     nRowEst += nEst;
118830     pBuilder->nRecValid = nRecValid;
118831   }
118832 
118833   if( rc==SQLITE_OK ){
118834     if( nRowEst > nRow0 ) nRowEst = nRow0;
118835     *pnRow = nRowEst;
118836     WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
118837   }
118838   assert( pBuilder->nRecValid==nRecValid );
118839   return rc;
118840 }
118841 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
118842 
118843 /*
118844 ** Disable a term in the WHERE clause.  Except, do not disable the term
118845 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
118846 ** or USING clause of that join.
118847 **
118848 ** Consider the term t2.z='ok' in the following queries:
118849 **
118850 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
118851 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
118852 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
118853 **
118854 ** The t2.z='ok' is disabled in the in (2) because it originates
118855 ** in the ON clause.  The term is disabled in (3) because it is not part
118856 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
118857 **
118858 ** Disabling a term causes that term to not be tested in the inner loop
118859 ** of the join.  Disabling is an optimization.  When terms are satisfied
118860 ** by indices, we disable them to prevent redundant tests in the inner
118861 ** loop.  We would get the correct results if nothing were ever disabled,
118862 ** but joins might run a little slower.  The trick is to disable as much
118863 ** as we can without disabling too much.  If we disabled in (1), we'd get
118864 ** the wrong answer.  See ticket #813.
118865 **
118866 ** If all the children of a term are disabled, then that term is also
118867 ** automatically disabled.  In this way, terms get disabled if derived
118868 ** virtual terms are tested first.  For example:
118869 **
118870 **      x GLOB 'abc*' AND x>='abc' AND x<'acd'
118871 **      \___________/     \______/     \_____/
118872 **         parent          child1       child2
118873 **
118874 ** Only the parent term was in the original WHERE clause.  The child1
118875 ** and child2 terms were added by the LIKE optimization.  If both of
118876 ** the virtual child terms are valid, then testing of the parent can be
118877 ** skipped.
118878 **
118879 ** Usually the parent term is marked as TERM_CODED.  But if the parent
118880 ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
118881 ** The TERM_LIKECOND marking indicates that the term should be coded inside
118882 ** a conditional such that is only evaluated on the second pass of a
118883 ** LIKE-optimization loop, when scanning BLOBs instead of strings.
118884 */
118885 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
118886   int nLoop = 0;
118887   while( pTerm
118888       && (pTerm->wtFlags & TERM_CODED)==0
118889       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
118890       && (pLevel->notReady & pTerm->prereqAll)==0
118891   ){
118892     if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
118893       pTerm->wtFlags |= TERM_LIKECOND;
118894     }else{
118895       pTerm->wtFlags |= TERM_CODED;
118896     }
118897     if( pTerm->iParent<0 ) break;
118898     pTerm = &pTerm->pWC->a[pTerm->iParent];
118899     pTerm->nChild--;
118900     if( pTerm->nChild!=0 ) break;
118901     nLoop++;
118902   }
118903 }
118904 
118905 /*
118906 ** Code an OP_Affinity opcode to apply the column affinity string zAff
118907 ** to the n registers starting at base.
118908 **
118909 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
118910 ** beginning and end of zAff are ignored.  If all entries in zAff are
118911 ** SQLITE_AFF_NONE, then no code gets generated.
118912 **
118913 ** This routine makes its own copy of zAff so that the caller is free
118914 ** to modify zAff after this routine returns.
118915 */
118916 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
118917   Vdbe *v = pParse->pVdbe;
118918   if( zAff==0 ){
118919     assert( pParse->db->mallocFailed );
118920     return;
118921   }
118922   assert( v!=0 );
118923 
118924   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
118925   ** and end of the affinity string.
118926   */
118927   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
118928     n--;
118929     base++;
118930     zAff++;
118931   }
118932   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
118933     n--;
118934   }
118935 
118936   /* Code the OP_Affinity opcode if there is anything left to do. */
118937   if( n>0 ){
118938     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
118939     sqlite3VdbeChangeP4(v, -1, zAff, n);
118940     sqlite3ExprCacheAffinityChange(pParse, base, n);
118941   }
118942 }
118943 
118944 
118945 /*
118946 ** Generate code for a single equality term of the WHERE clause.  An equality
118947 ** term can be either X=expr or X IN (...).   pTerm is the term to be
118948 ** coded.
118949 **
118950 ** The current value for the constraint is left in register iReg.
118951 **
118952 ** For a constraint of the form X=expr, the expression is evaluated and its
118953 ** result is left on the stack.  For constraints of the form X IN (...)
118954 ** this routine sets up a loop that will iterate over all values of X.
118955 */
118956 static int codeEqualityTerm(
118957   Parse *pParse,      /* The parsing context */
118958   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
118959   WhereLevel *pLevel, /* The level of the FROM clause we are working on */
118960   int iEq,            /* Index of the equality term within this level */
118961   int bRev,           /* True for reverse-order IN operations */
118962   int iTarget         /* Attempt to leave results in this register */
118963 ){
118964   Expr *pX = pTerm->pExpr;
118965   Vdbe *v = pParse->pVdbe;
118966   int iReg;                  /* Register holding results */
118967 
118968   assert( iTarget>0 );
118969   if( pX->op==TK_EQ ){
118970     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
118971   }else if( pX->op==TK_ISNULL ){
118972     iReg = iTarget;
118973     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
118974 #ifndef SQLITE_OMIT_SUBQUERY
118975   }else{
118976     int eType;
118977     int iTab;
118978     struct InLoop *pIn;
118979     WhereLoop *pLoop = pLevel->pWLoop;
118980 
118981     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
118982       && pLoop->u.btree.pIndex!=0
118983       && pLoop->u.btree.pIndex->aSortOrder[iEq]
118984     ){
118985       testcase( iEq==0 );
118986       testcase( bRev );
118987       bRev = !bRev;
118988     }
118989     assert( pX->op==TK_IN );
118990     iReg = iTarget;
118991     eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
118992     if( eType==IN_INDEX_INDEX_DESC ){
118993       testcase( bRev );
118994       bRev = !bRev;
118995     }
118996     iTab = pX->iTable;
118997     sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
118998     VdbeCoverageIf(v, bRev);
118999     VdbeCoverageIf(v, !bRev);
119000     assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
119001     pLoop->wsFlags |= WHERE_IN_ABLE;
119002     if( pLevel->u.in.nIn==0 ){
119003       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
119004     }
119005     pLevel->u.in.nIn++;
119006     pLevel->u.in.aInLoop =
119007        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
119008                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
119009     pIn = pLevel->u.in.aInLoop;
119010     if( pIn ){
119011       pIn += pLevel->u.in.nIn - 1;
119012       pIn->iCur = iTab;
119013       if( eType==IN_INDEX_ROWID ){
119014         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
119015       }else{
119016         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
119017       }
119018       pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
119019       sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
119020     }else{
119021       pLevel->u.in.nIn = 0;
119022     }
119023 #endif
119024   }
119025   disableTerm(pLevel, pTerm);
119026   return iReg;
119027 }
119028 
119029 /*
119030 ** Generate code that will evaluate all == and IN constraints for an
119031 ** index scan.
119032 **
119033 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
119034 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
119035 ** The index has as many as three equality constraints, but in this
119036 ** example, the third "c" value is an inequality.  So only two
119037 ** constraints are coded.  This routine will generate code to evaluate
119038 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
119039 ** in consecutive registers and the index of the first register is returned.
119040 **
119041 ** In the example above nEq==2.  But this subroutine works for any value
119042 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
119043 ** The only thing it does is allocate the pLevel->iMem memory cell and
119044 ** compute the affinity string.
119045 **
119046 ** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
119047 ** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
119048 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
119049 ** occurs after the nEq quality constraints.
119050 **
119051 ** This routine allocates a range of nEq+nExtraReg memory cells and returns
119052 ** the index of the first memory cell in that range. The code that
119053 ** calls this routine will use that memory range to store keys for
119054 ** start and termination conditions of the loop.
119055 ** key value of the loop.  If one or more IN operators appear, then
119056 ** this routine allocates an additional nEq memory cells for internal
119057 ** use.
119058 **
119059 ** Before returning, *pzAff is set to point to a buffer containing a
119060 ** copy of the column affinity string of the index allocated using
119061 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
119062 ** with equality constraints that use NONE affinity are set to
119063 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
119064 **
119065 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
119066 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
119067 **
119068 ** In the example above, the index on t1(a) has TEXT affinity. But since
119069 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
119070 ** no conversion should be attempted before using a t2.b value as part of
119071 ** a key to search the index. Hence the first byte in the returned affinity
119072 ** string in this example would be set to SQLITE_AFF_NONE.
119073 */
119074 static int codeAllEqualityTerms(
119075   Parse *pParse,        /* Parsing context */
119076   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
119077   int bRev,             /* Reverse the order of IN operators */
119078   int nExtraReg,        /* Number of extra registers to allocate */
119079   char **pzAff          /* OUT: Set to point to affinity string */
119080 ){
119081   u16 nEq;                      /* The number of == or IN constraints to code */
119082   u16 nSkip;                    /* Number of left-most columns to skip */
119083   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
119084   Index *pIdx;                  /* The index being used for this loop */
119085   WhereTerm *pTerm;             /* A single constraint term */
119086   WhereLoop *pLoop;             /* The WhereLoop object */
119087   int j;                        /* Loop counter */
119088   int regBase;                  /* Base register */
119089   int nReg;                     /* Number of registers to allocate */
119090   char *zAff;                   /* Affinity string to return */
119091 
119092   /* This module is only called on query plans that use an index. */
119093   pLoop = pLevel->pWLoop;
119094   assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
119095   nEq = pLoop->u.btree.nEq;
119096   nSkip = pLoop->nSkip;
119097   pIdx = pLoop->u.btree.pIndex;
119098   assert( pIdx!=0 );
119099 
119100   /* Figure out how many memory cells we will need then allocate them.
119101   */
119102   regBase = pParse->nMem + 1;
119103   nReg = pLoop->u.btree.nEq + nExtraReg;
119104   pParse->nMem += nReg;
119105 
119106   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
119107   if( !zAff ){
119108     pParse->db->mallocFailed = 1;
119109   }
119110 
119111   if( nSkip ){
119112     int iIdxCur = pLevel->iIdxCur;
119113     sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
119114     VdbeCoverageIf(v, bRev==0);
119115     VdbeCoverageIf(v, bRev!=0);
119116     VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
119117     j = sqlite3VdbeAddOp0(v, OP_Goto);
119118     pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
119119                             iIdxCur, 0, regBase, nSkip);
119120     VdbeCoverageIf(v, bRev==0);
119121     VdbeCoverageIf(v, bRev!=0);
119122     sqlite3VdbeJumpHere(v, j);
119123     for(j=0; j<nSkip; j++){
119124       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
119125       assert( pIdx->aiColumn[j]>=0 );
119126       VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
119127     }
119128   }
119129 
119130   /* Evaluate the equality constraints
119131   */
119132   assert( zAff==0 || (int)strlen(zAff)>=nEq );
119133   for(j=nSkip; j<nEq; j++){
119134     int r1;
119135     pTerm = pLoop->aLTerm[j];
119136     assert( pTerm!=0 );
119137     /* The following testcase is true for indices with redundant columns.
119138     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
119139     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
119140     testcase( pTerm->wtFlags & TERM_VIRTUAL );
119141     r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
119142     if( r1!=regBase+j ){
119143       if( nReg==1 ){
119144         sqlite3ReleaseTempReg(pParse, regBase);
119145         regBase = r1;
119146       }else{
119147         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
119148       }
119149     }
119150     testcase( pTerm->eOperator & WO_ISNULL );
119151     testcase( pTerm->eOperator & WO_IN );
119152     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
119153       Expr *pRight = pTerm->pExpr->pRight;
119154       if( sqlite3ExprCanBeNull(pRight) ){
119155         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
119156         VdbeCoverage(v);
119157       }
119158       if( zAff ){
119159         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
119160           zAff[j] = SQLITE_AFF_NONE;
119161         }
119162         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
119163           zAff[j] = SQLITE_AFF_NONE;
119164         }
119165       }
119166     }
119167   }
119168   *pzAff = zAff;
119169   return regBase;
119170 }
119171 
119172 #ifndef SQLITE_OMIT_EXPLAIN
119173 /*
119174 ** This routine is a helper for explainIndexRange() below
119175 **
119176 ** pStr holds the text of an expression that we are building up one term
119177 ** at a time.  This routine adds a new term to the end of the expression.
119178 ** Terms are separated by AND so add the "AND" text for second and subsequent
119179 ** terms only.
119180 */
119181 static void explainAppendTerm(
119182   StrAccum *pStr,             /* The text expression being built */
119183   int iTerm,                  /* Index of this term.  First is zero */
119184   const char *zColumn,        /* Name of the column */
119185   const char *zOp             /* Name of the operator */
119186 ){
119187   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
119188   sqlite3StrAccumAppendAll(pStr, zColumn);
119189   sqlite3StrAccumAppend(pStr, zOp, 1);
119190   sqlite3StrAccumAppend(pStr, "?", 1);
119191 }
119192 
119193 /*
119194 ** Argument pLevel describes a strategy for scanning table pTab. This
119195 ** function appends text to pStr that describes the subset of table
119196 ** rows scanned by the strategy in the form of an SQL expression.
119197 **
119198 ** For example, if the query:
119199 **
119200 **   SELECT * FROM t1 WHERE a=1 AND b>2;
119201 **
119202 ** is run and there is an index on (a, b), then this function returns a
119203 ** string similar to:
119204 **
119205 **   "a=? AND b>?"
119206 */
119207 static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
119208   Index *pIndex = pLoop->u.btree.pIndex;
119209   u16 nEq = pLoop->u.btree.nEq;
119210   u16 nSkip = pLoop->nSkip;
119211   int i, j;
119212   Column *aCol = pTab->aCol;
119213   i16 *aiColumn = pIndex->aiColumn;
119214 
119215   if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
119216   sqlite3StrAccumAppend(pStr, " (", 2);
119217   for(i=0; i<nEq; i++){
119218     char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
119219     if( i>=nSkip ){
119220       explainAppendTerm(pStr, i, z, "=");
119221     }else{
119222       if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
119223       sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
119224     }
119225   }
119226 
119227   j = i;
119228   if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
119229     char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
119230     explainAppendTerm(pStr, i++, z, ">");
119231   }
119232   if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
119233     char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
119234     explainAppendTerm(pStr, i, z, "<");
119235   }
119236   sqlite3StrAccumAppend(pStr, ")", 1);
119237 }
119238 
119239 /*
119240 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
119241 ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
119242 ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
119243 ** is added to the output to describe the table scan strategy in pLevel.
119244 **
119245 ** If an OP_Explain opcode is added to the VM, its address is returned.
119246 ** Otherwise, if no OP_Explain is coded, zero is returned.
119247 */
119248 static int explainOneScan(
119249   Parse *pParse,                  /* Parse context */
119250   SrcList *pTabList,              /* Table list this loop refers to */
119251   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
119252   int iLevel,                     /* Value for "level" column of output */
119253   int iFrom,                      /* Value for "from" column of output */
119254   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
119255 ){
119256   int ret = 0;
119257 #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
119258   if( pParse->explain==2 )
119259 #endif
119260   {
119261     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
119262     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
119263     sqlite3 *db = pParse->db;     /* Database handle */
119264     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
119265     int isSearch;                 /* True for a SEARCH. False for SCAN. */
119266     WhereLoop *pLoop;             /* The controlling WhereLoop object */
119267     u32 flags;                    /* Flags that describe this loop */
119268     char *zMsg;                   /* Text to add to EQP output */
119269     StrAccum str;                 /* EQP output string */
119270     char zBuf[100];               /* Initial space for EQP output string */
119271 
119272     pLoop = pLevel->pWLoop;
119273     flags = pLoop->wsFlags;
119274     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
119275 
119276     isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
119277             || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
119278             || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
119279 
119280     sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
119281     sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
119282     if( pItem->pSelect ){
119283       sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
119284     }else{
119285       sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
119286     }
119287 
119288     if( pItem->zAlias ){
119289       sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
119290     }
119291     if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
119292       const char *zFmt = 0;
119293       Index *pIdx;
119294 
119295       assert( pLoop->u.btree.pIndex!=0 );
119296       pIdx = pLoop->u.btree.pIndex;
119297       assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
119298       if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
119299         if( isSearch ){
119300           zFmt = "PRIMARY KEY";
119301         }
119302       }else if( flags & WHERE_PARTIALIDX ){
119303         zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
119304       }else if( flags & WHERE_AUTO_INDEX ){
119305         zFmt = "AUTOMATIC COVERING INDEX";
119306       }else if( flags & WHERE_IDX_ONLY ){
119307         zFmt = "COVERING INDEX %s";
119308       }else{
119309         zFmt = "INDEX %s";
119310       }
119311       if( zFmt ){
119312         sqlite3StrAccumAppend(&str, " USING ", 7);
119313         sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
119314         explainIndexRange(&str, pLoop, pItem->pTab);
119315       }
119316     }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
119317       const char *zRange;
119318       if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
119319         zRange = "(rowid=?)";
119320       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
119321         zRange = "(rowid>? AND rowid<?)";
119322       }else if( flags&WHERE_BTM_LIMIT ){
119323         zRange = "(rowid>?)";
119324       }else{
119325         assert( flags&WHERE_TOP_LIMIT);
119326         zRange = "(rowid<?)";
119327       }
119328       sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY ");
119329       sqlite3StrAccumAppendAll(&str, zRange);
119330     }
119331 #ifndef SQLITE_OMIT_VIRTUALTABLE
119332     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
119333       sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
119334                   pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
119335     }
119336 #endif
119337 #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
119338     if( pLoop->nOut>=10 ){
119339       sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
119340     }else{
119341       sqlite3StrAccumAppend(&str, " (~1 row)", 9);
119342     }
119343 #endif
119344     zMsg = sqlite3StrAccumFinish(&str);
119345     ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
119346   }
119347   return ret;
119348 }
119349 #else
119350 # define explainOneScan(u,v,w,x,y,z) 0
119351 #endif /* SQLITE_OMIT_EXPLAIN */
119352 
119353 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
119354 /*
119355 ** Configure the VM passed as the first argument with an
119356 ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
119357 ** implement level pLvl. Argument pSrclist is a pointer to the FROM
119358 ** clause that the scan reads data from.
119359 **
119360 ** If argument addrExplain is not 0, it must be the address of an
119361 ** OP_Explain instruction that describes the same loop.
119362 */
119363 static void addScanStatus(
119364   Vdbe *v,                        /* Vdbe to add scanstatus entry to */
119365   SrcList *pSrclist,              /* FROM clause pLvl reads data from */
119366   WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
119367   int addrExplain                 /* Address of OP_Explain (or 0) */
119368 ){
119369   const char *zObj = 0;
119370   WhereLoop *pLoop = pLvl->pWLoop;
119371   if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
119372     zObj = pLoop->u.btree.pIndex->zName;
119373   }else{
119374     zObj = pSrclist->a[pLvl->iFrom].zName;
119375   }
119376   sqlite3VdbeScanStatus(
119377       v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
119378   );
119379 }
119380 #else
119381 # define addScanStatus(a, b, c, d) ((void)d)
119382 #endif
119383 
119384 /*
119385 ** If the most recently coded instruction is a constant range contraint
119386 ** that originated from the LIKE optimization, then change the P3 to be
119387 ** pLoop->iLikeRepCntr and set P5.
119388 **
119389 ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
119390 ** expression: "x>='ABC' AND x<'abd'".  But this requires that the range
119391 ** scan loop run twice, once for strings and a second time for BLOBs.
119392 ** The OP_String opcodes on the second pass convert the upper and lower
119393 ** bound string contants to blobs.  This routine makes the necessary changes
119394 ** to the OP_String opcodes for that to happen.
119395 */
119396 static void whereLikeOptimizationStringFixup(
119397   Vdbe *v,                /* prepared statement under construction */
119398   WhereLevel *pLevel,     /* The loop that contains the LIKE operator */
119399   WhereTerm *pTerm        /* The upper or lower bound just coded */
119400 ){
119401   if( pTerm->wtFlags & TERM_LIKEOPT ){
119402     VdbeOp *pOp;
119403     assert( pLevel->iLikeRepCntr>0 );
119404     pOp = sqlite3VdbeGetOp(v, -1);
119405     assert( pOp!=0 );
119406     assert( pOp->opcode==OP_String8
119407             || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
119408     pOp->p3 = pLevel->iLikeRepCntr;
119409     pOp->p5 = 1;
119410   }
119411 }
119412 
119413 /*
119414 ** Generate code for the start of the iLevel-th loop in the WHERE clause
119415 ** implementation described by pWInfo.
119416 */
119417 static Bitmask codeOneLoopStart(
119418   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
119419   int iLevel,          /* Which level of pWInfo->a[] should be coded */
119420   Bitmask notReady     /* Which tables are currently available */
119421 ){
119422   int j, k;            /* Loop counters */
119423   int iCur;            /* The VDBE cursor for the table */
119424   int addrNxt;         /* Where to jump to continue with the next IN case */
119425   int omitTable;       /* True if we use the index only */
119426   int bRev;            /* True if we need to scan in reverse order */
119427   WhereLevel *pLevel;  /* The where level to be coded */
119428   WhereLoop *pLoop;    /* The WhereLoop object being coded */
119429   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
119430   WhereTerm *pTerm;               /* A WHERE clause term */
119431   Parse *pParse;                  /* Parsing context */
119432   sqlite3 *db;                    /* Database connection */
119433   Vdbe *v;                        /* The prepared stmt under constructions */
119434   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
119435   int addrBrk;                    /* Jump here to break out of the loop */
119436   int addrCont;                   /* Jump here to continue with next cycle */
119437   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
119438   int iReleaseReg = 0;      /* Temp register to free before returning */
119439 
119440   pParse = pWInfo->pParse;
119441   v = pParse->pVdbe;
119442   pWC = &pWInfo->sWC;
119443   db = pParse->db;
119444   pLevel = &pWInfo->a[iLevel];
119445   pLoop = pLevel->pWLoop;
119446   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
119447   iCur = pTabItem->iCursor;
119448   pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
119449   bRev = (pWInfo->revMask>>iLevel)&1;
119450   omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
119451            && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
119452   VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
119453 
119454   /* Create labels for the "break" and "continue" instructions
119455   ** for the current loop.  Jump to addrBrk to break out of a loop.
119456   ** Jump to cont to go immediately to the next iteration of the
119457   ** loop.
119458   **
119459   ** When there is an IN operator, we also have a "addrNxt" label that
119460   ** means to continue with the next IN value combination.  When
119461   ** there are no IN operators in the constraints, the "addrNxt" label
119462   ** is the same as "addrBrk".
119463   */
119464   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
119465   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
119466 
119467   /* If this is the right table of a LEFT OUTER JOIN, allocate and
119468   ** initialize a memory cell that records if this table matches any
119469   ** row of the left table of the join.
119470   */
119471   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
119472     pLevel->iLeftJoin = ++pParse->nMem;
119473     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
119474     VdbeComment((v, "init LEFT JOIN no-match flag"));
119475   }
119476 
119477   /* Special case of a FROM clause subquery implemented as a co-routine */
119478   if( pTabItem->viaCoroutine ){
119479     int regYield = pTabItem->regReturn;
119480     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
119481     pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
119482     VdbeCoverage(v);
119483     VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
119484     pLevel->op = OP_Goto;
119485   }else
119486 
119487 #ifndef SQLITE_OMIT_VIRTUALTABLE
119488   if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
119489     /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
119490     **          to access the data.
119491     */
119492     int iReg;   /* P3 Value for OP_VFilter */
119493     int addrNotFound;
119494     int nConstraint = pLoop->nLTerm;
119495 
119496     sqlite3ExprCachePush(pParse);
119497     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
119498     addrNotFound = pLevel->addrBrk;
119499     for(j=0; j<nConstraint; j++){
119500       int iTarget = iReg+j+2;
119501       pTerm = pLoop->aLTerm[j];
119502       if( pTerm==0 ) continue;
119503       if( pTerm->eOperator & WO_IN ){
119504         codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
119505         addrNotFound = pLevel->addrNxt;
119506       }else{
119507         sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
119508       }
119509     }
119510     sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
119511     sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
119512     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
119513                       pLoop->u.vtab.idxStr,
119514                       pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
119515     VdbeCoverage(v);
119516     pLoop->u.vtab.needFree = 0;
119517     for(j=0; j<nConstraint && j<16; j++){
119518       if( (pLoop->u.vtab.omitMask>>j)&1 ){
119519         disableTerm(pLevel, pLoop->aLTerm[j]);
119520       }
119521     }
119522     pLevel->op = OP_VNext;
119523     pLevel->p1 = iCur;
119524     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
119525     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
119526     sqlite3ExprCachePop(pParse);
119527   }else
119528 #endif /* SQLITE_OMIT_VIRTUALTABLE */
119529 
119530   if( (pLoop->wsFlags & WHERE_IPK)!=0
119531    && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
119532   ){
119533     /* Case 2:  We can directly reference a single row using an
119534     **          equality comparison against the ROWID field.  Or
119535     **          we reference multiple rows using a "rowid IN (...)"
119536     **          construct.
119537     */
119538     assert( pLoop->u.btree.nEq==1 );
119539     pTerm = pLoop->aLTerm[0];
119540     assert( pTerm!=0 );
119541     assert( pTerm->pExpr!=0 );
119542     assert( omitTable==0 );
119543     testcase( pTerm->wtFlags & TERM_VIRTUAL );
119544     iReleaseReg = ++pParse->nMem;
119545     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
119546     if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
119547     addrNxt = pLevel->addrNxt;
119548     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
119549     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
119550     VdbeCoverage(v);
119551     sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
119552     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
119553     VdbeComment((v, "pk"));
119554     pLevel->op = OP_Noop;
119555   }else if( (pLoop->wsFlags & WHERE_IPK)!=0
119556          && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
119557   ){
119558     /* Case 3:  We have an inequality comparison against the ROWID field.
119559     */
119560     int testOp = OP_Noop;
119561     int start;
119562     int memEndValue = 0;
119563     WhereTerm *pStart, *pEnd;
119564 
119565     assert( omitTable==0 );
119566     j = 0;
119567     pStart = pEnd = 0;
119568     if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
119569     if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
119570     assert( pStart!=0 || pEnd!=0 );
119571     if( bRev ){
119572       pTerm = pStart;
119573       pStart = pEnd;
119574       pEnd = pTerm;
119575     }
119576     if( pStart ){
119577       Expr *pX;             /* The expression that defines the start bound */
119578       int r1, rTemp;        /* Registers for holding the start boundary */
119579 
119580       /* The following constant maps TK_xx codes into corresponding
119581       ** seek opcodes.  It depends on a particular ordering of TK_xx
119582       */
119583       const u8 aMoveOp[] = {
119584            /* TK_GT */  OP_SeekGT,
119585            /* TK_LE */  OP_SeekLE,
119586            /* TK_LT */  OP_SeekLT,
119587            /* TK_GE */  OP_SeekGE
119588       };
119589       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
119590       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
119591       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
119592 
119593       assert( (pStart->wtFlags & TERM_VNULL)==0 );
119594       testcase( pStart->wtFlags & TERM_VIRTUAL );
119595       pX = pStart->pExpr;
119596       assert( pX!=0 );
119597       testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
119598       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
119599       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
119600       VdbeComment((v, "pk"));
119601       VdbeCoverageIf(v, pX->op==TK_GT);
119602       VdbeCoverageIf(v, pX->op==TK_LE);
119603       VdbeCoverageIf(v, pX->op==TK_LT);
119604       VdbeCoverageIf(v, pX->op==TK_GE);
119605       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
119606       sqlite3ReleaseTempReg(pParse, rTemp);
119607       disableTerm(pLevel, pStart);
119608     }else{
119609       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
119610       VdbeCoverageIf(v, bRev==0);
119611       VdbeCoverageIf(v, bRev!=0);
119612     }
119613     if( pEnd ){
119614       Expr *pX;
119615       pX = pEnd->pExpr;
119616       assert( pX!=0 );
119617       assert( (pEnd->wtFlags & TERM_VNULL)==0 );
119618       testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
119619       testcase( pEnd->wtFlags & TERM_VIRTUAL );
119620       memEndValue = ++pParse->nMem;
119621       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
119622       if( pX->op==TK_LT || pX->op==TK_GT ){
119623         testOp = bRev ? OP_Le : OP_Ge;
119624       }else{
119625         testOp = bRev ? OP_Lt : OP_Gt;
119626       }
119627       disableTerm(pLevel, pEnd);
119628     }
119629     start = sqlite3VdbeCurrentAddr(v);
119630     pLevel->op = bRev ? OP_Prev : OP_Next;
119631     pLevel->p1 = iCur;
119632     pLevel->p2 = start;
119633     assert( pLevel->p5==0 );
119634     if( testOp!=OP_Noop ){
119635       iRowidReg = ++pParse->nMem;
119636       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
119637       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
119638       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
119639       VdbeCoverageIf(v, testOp==OP_Le);
119640       VdbeCoverageIf(v, testOp==OP_Lt);
119641       VdbeCoverageIf(v, testOp==OP_Ge);
119642       VdbeCoverageIf(v, testOp==OP_Gt);
119643       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
119644     }
119645   }else if( pLoop->wsFlags & WHERE_INDEXED ){
119646     /* Case 4: A scan using an index.
119647     **
119648     **         The WHERE clause may contain zero or more equality
119649     **         terms ("==" or "IN" operators) that refer to the N
119650     **         left-most columns of the index. It may also contain
119651     **         inequality constraints (>, <, >= or <=) on the indexed
119652     **         column that immediately follows the N equalities. Only
119653     **         the right-most column can be an inequality - the rest must
119654     **         use the "==" and "IN" operators. For example, if the
119655     **         index is on (x,y,z), then the following clauses are all
119656     **         optimized:
119657     **
119658     **            x=5
119659     **            x=5 AND y=10
119660     **            x=5 AND y<10
119661     **            x=5 AND y>5 AND y<10
119662     **            x=5 AND y=5 AND z<=10
119663     **
119664     **         The z<10 term of the following cannot be used, only
119665     **         the x=5 term:
119666     **
119667     **            x=5 AND z<10
119668     **
119669     **         N may be zero if there are inequality constraints.
119670     **         If there are no inequality constraints, then N is at
119671     **         least one.
119672     **
119673     **         This case is also used when there are no WHERE clause
119674     **         constraints but an index is selected anyway, in order
119675     **         to force the output order to conform to an ORDER BY.
119676     */
119677     static const u8 aStartOp[] = {
119678       0,
119679       0,
119680       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
119681       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
119682       OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
119683       OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
119684       OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
119685       OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
119686     };
119687     static const u8 aEndOp[] = {
119688       OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
119689       OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
119690       OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
119691       OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
119692     };
119693     u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
119694     int regBase;                 /* Base register holding constraint values */
119695     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
119696     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
119697     int startEq;                 /* True if range start uses ==, >= or <= */
119698     int endEq;                   /* True if range end uses ==, >= or <= */
119699     int start_constraints;       /* Start of range is constrained */
119700     int nConstraint;             /* Number of constraint terms */
119701     Index *pIdx;                 /* The index we will be using */
119702     int iIdxCur;                 /* The VDBE cursor for the index */
119703     int nExtraReg = 0;           /* Number of extra registers needed */
119704     int op;                      /* Instruction opcode */
119705     char *zStartAff;             /* Affinity for start of range constraint */
119706     char cEndAff = 0;            /* Affinity for end of range constraint */
119707     u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
119708     u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
119709 
119710     pIdx = pLoop->u.btree.pIndex;
119711     iIdxCur = pLevel->iIdxCur;
119712     assert( nEq>=pLoop->nSkip );
119713 
119714     /* If this loop satisfies a sort order (pOrderBy) request that
119715     ** was passed to this function to implement a "SELECT min(x) ..."
119716     ** query, then the caller will only allow the loop to run for
119717     ** a single iteration. This means that the first row returned
119718     ** should not have a NULL value stored in 'x'. If column 'x' is
119719     ** the first one after the nEq equality constraints in the index,
119720     ** this requires some special handling.
119721     */
119722     assert( pWInfo->pOrderBy==0
119723          || pWInfo->pOrderBy->nExpr==1
119724          || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
119725     if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
119726      && pWInfo->nOBSat>0
119727      && (pIdx->nKeyCol>nEq)
119728     ){
119729       assert( pLoop->nSkip==0 );
119730       bSeekPastNull = 1;
119731       nExtraReg = 1;
119732     }
119733 
119734     /* Find any inequality constraint terms for the start and end
119735     ** of the range.
119736     */
119737     j = nEq;
119738     if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
119739       pRangeStart = pLoop->aLTerm[j++];
119740       nExtraReg = 1;
119741       /* Like optimization range constraints always occur in pairs */
119742       assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
119743               (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
119744     }
119745     if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
119746       pRangeEnd = pLoop->aLTerm[j++];
119747       nExtraReg = 1;
119748       if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
119749         assert( pRangeStart!=0 );                     /* LIKE opt constraints */
119750         assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */
119751         pLevel->iLikeRepCntr = ++pParse->nMem;
119752         testcase( bRev );
119753         testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
119754         sqlite3VdbeAddOp2(v, OP_Integer,
119755                           bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
119756                           pLevel->iLikeRepCntr);
119757         VdbeComment((v, "LIKE loop counter"));
119758         pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
119759       }
119760       if( pRangeStart==0
119761        && (j = pIdx->aiColumn[nEq])>=0
119762        && pIdx->pTable->aCol[j].notNull==0
119763       ){
119764         bSeekPastNull = 1;
119765       }
119766     }
119767     assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
119768 
119769     /* Generate code to evaluate all constraint terms using == or IN
119770     ** and store the values of those terms in an array of registers
119771     ** starting at regBase.
119772     */
119773     regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
119774     assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
119775     if( zStartAff ) cEndAff = zStartAff[nEq];
119776     addrNxt = pLevel->addrNxt;
119777 
119778     /* If we are doing a reverse order scan on an ascending index, or
119779     ** a forward order scan on a descending index, interchange the
119780     ** start and end terms (pRangeStart and pRangeEnd).
119781     */
119782     if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
119783      || (bRev && pIdx->nKeyCol==nEq)
119784     ){
119785       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
119786       SWAP(u8, bSeekPastNull, bStopAtNull);
119787     }
119788 
119789     testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
119790     testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
119791     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
119792     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
119793     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
119794     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
119795     start_constraints = pRangeStart || nEq>0;
119796 
119797     /* Seek the index cursor to the start of the range. */
119798     nConstraint = nEq;
119799     if( pRangeStart ){
119800       Expr *pRight = pRangeStart->pExpr->pRight;
119801       sqlite3ExprCode(pParse, pRight, regBase+nEq);
119802       whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
119803       if( (pRangeStart->wtFlags & TERM_VNULL)==0
119804        && sqlite3ExprCanBeNull(pRight)
119805       ){
119806         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
119807         VdbeCoverage(v);
119808       }
119809       if( zStartAff ){
119810         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
119811           /* Since the comparison is to be performed with no conversions
119812           ** applied to the operands, set the affinity to apply to pRight to
119813           ** SQLITE_AFF_NONE.  */
119814           zStartAff[nEq] = SQLITE_AFF_NONE;
119815         }
119816         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
119817           zStartAff[nEq] = SQLITE_AFF_NONE;
119818         }
119819       }
119820       nConstraint++;
119821       testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
119822     }else if( bSeekPastNull ){
119823       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
119824       nConstraint++;
119825       startEq = 0;
119826       start_constraints = 1;
119827     }
119828     codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
119829     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
119830     assert( op!=0 );
119831     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
119832     VdbeCoverage(v);
119833     VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
119834     VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
119835     VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
119836     VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
119837     VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
119838     VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
119839 
119840     /* Load the value for the inequality constraint at the end of the
119841     ** range (if any).
119842     */
119843     nConstraint = nEq;
119844     if( pRangeEnd ){
119845       Expr *pRight = pRangeEnd->pExpr->pRight;
119846       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
119847       sqlite3ExprCode(pParse, pRight, regBase+nEq);
119848       whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
119849       if( (pRangeEnd->wtFlags & TERM_VNULL)==0
119850        && sqlite3ExprCanBeNull(pRight)
119851       ){
119852         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
119853         VdbeCoverage(v);
119854       }
119855       if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
119856        && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
119857       ){
119858         codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
119859       }
119860       nConstraint++;
119861       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
119862     }else if( bStopAtNull ){
119863       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
119864       endEq = 0;
119865       nConstraint++;
119866     }
119867     sqlite3DbFree(db, zStartAff);
119868 
119869     /* Top of the loop body */
119870     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
119871 
119872     /* Check if the index cursor is past the end of the range. */
119873     if( nConstraint ){
119874       op = aEndOp[bRev*2 + endEq];
119875       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
119876       testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
119877       testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
119878       testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
119879       testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
119880     }
119881 
119882     /* Seek the table cursor, if required */
119883     disableTerm(pLevel, pRangeStart);
119884     disableTerm(pLevel, pRangeEnd);
119885     if( omitTable ){
119886       /* pIdx is a covering index.  No need to access the main table. */
119887     }else if( HasRowid(pIdx->pTable) ){
119888       iRowidReg = ++pParse->nMem;
119889       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
119890       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
119891       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
119892     }else if( iCur!=iIdxCur ){
119893       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
119894       iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
119895       for(j=0; j<pPk->nKeyCol; j++){
119896         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
119897         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
119898       }
119899       sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
119900                            iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
119901     }
119902 
119903     /* Record the instruction used to terminate the loop. Disable
119904     ** WHERE clause terms made redundant by the index range scan.
119905     */
119906     if( pLoop->wsFlags & WHERE_ONEROW ){
119907       pLevel->op = OP_Noop;
119908     }else if( bRev ){
119909       pLevel->op = OP_Prev;
119910     }else{
119911       pLevel->op = OP_Next;
119912     }
119913     pLevel->p1 = iIdxCur;
119914     pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
119915     if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
119916       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
119917     }else{
119918       assert( pLevel->p5==0 );
119919     }
119920   }else
119921 
119922 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
119923   if( pLoop->wsFlags & WHERE_MULTI_OR ){
119924     /* Case 5:  Two or more separately indexed terms connected by OR
119925     **
119926     ** Example:
119927     **
119928     **   CREATE TABLE t1(a,b,c,d);
119929     **   CREATE INDEX i1 ON t1(a);
119930     **   CREATE INDEX i2 ON t1(b);
119931     **   CREATE INDEX i3 ON t1(c);
119932     **
119933     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
119934     **
119935     ** In the example, there are three indexed terms connected by OR.
119936     ** The top of the loop looks like this:
119937     **
119938     **          Null       1                # Zero the rowset in reg 1
119939     **
119940     ** Then, for each indexed term, the following. The arguments to
119941     ** RowSetTest are such that the rowid of the current row is inserted
119942     ** into the RowSet. If it is already present, control skips the
119943     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
119944     **
119945     **        sqlite3WhereBegin(<term>)
119946     **          RowSetTest                  # Insert rowid into rowset
119947     **          Gosub      2 A
119948     **        sqlite3WhereEnd()
119949     **
119950     ** Following the above, code to terminate the loop. Label A, the target
119951     ** of the Gosub above, jumps to the instruction right after the Goto.
119952     **
119953     **          Null       1                # Zero the rowset in reg 1
119954     **          Goto       B                # The loop is finished.
119955     **
119956     **       A: <loop body>                 # Return data, whatever.
119957     **
119958     **          Return     2                # Jump back to the Gosub
119959     **
119960     **       B: <after the loop>
119961     **
119962     ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
119963     ** use an ephemeral index instead of a RowSet to record the primary
119964     ** keys of the rows we have already seen.
119965     **
119966     */
119967     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
119968     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
119969     Index *pCov = 0;             /* Potential covering index (or NULL) */
119970     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
119971 
119972     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
119973     int regRowset = 0;                        /* Register for RowSet object */
119974     int regRowid = 0;                         /* Register holding rowid */
119975     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
119976     int iRetInit;                             /* Address of regReturn init */
119977     int untestedTerms = 0;             /* Some terms not completely tested */
119978     int ii;                            /* Loop counter */
119979     u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
119980     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
119981     Table *pTab = pTabItem->pTab;
119982 
119983     pTerm = pLoop->aLTerm[0];
119984     assert( pTerm!=0 );
119985     assert( pTerm->eOperator & WO_OR );
119986     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
119987     pOrWc = &pTerm->u.pOrInfo->wc;
119988     pLevel->op = OP_Return;
119989     pLevel->p1 = regReturn;
119990 
119991     /* Set up a new SrcList in pOrTab containing the table being scanned
119992     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
119993     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
119994     */
119995     if( pWInfo->nLevel>1 ){
119996       int nNotReady;                 /* The number of notReady tables */
119997       struct SrcList_item *origSrc;     /* Original list of tables */
119998       nNotReady = pWInfo->nLevel - iLevel - 1;
119999       pOrTab = sqlite3StackAllocRaw(db,
120000                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
120001       if( pOrTab==0 ) return notReady;
120002       pOrTab->nAlloc = (u8)(nNotReady + 1);
120003       pOrTab->nSrc = pOrTab->nAlloc;
120004       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
120005       origSrc = pWInfo->pTabList->a;
120006       for(k=1; k<=nNotReady; k++){
120007         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
120008       }
120009     }else{
120010       pOrTab = pWInfo->pTabList;
120011     }
120012 
120013     /* Initialize the rowset register to contain NULL. An SQL NULL is
120014     ** equivalent to an empty rowset.  Or, create an ephemeral index
120015     ** capable of holding primary keys in the case of a WITHOUT ROWID.
120016     **
120017     ** Also initialize regReturn to contain the address of the instruction
120018     ** immediately following the OP_Return at the bottom of the loop. This
120019     ** is required in a few obscure LEFT JOIN cases where control jumps
120020     ** over the top of the loop into the body of it. In this case the
120021     ** correct response for the end-of-loop code (the OP_Return) is to
120022     ** fall through to the next instruction, just as an OP_Next does if
120023     ** called on an uninitialized cursor.
120024     */
120025     if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
120026       if( HasRowid(pTab) ){
120027         regRowset = ++pParse->nMem;
120028         sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
120029       }else{
120030         Index *pPk = sqlite3PrimaryKeyIndex(pTab);
120031         regRowset = pParse->nTab++;
120032         sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
120033         sqlite3VdbeSetP4KeyInfo(pParse, pPk);
120034       }
120035       regRowid = ++pParse->nMem;
120036     }
120037     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
120038 
120039     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
120040     ** Then for every term xN, evaluate as the subexpression: xN AND z
120041     ** That way, terms in y that are factored into the disjunction will
120042     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
120043     **
120044     ** Actually, each subexpression is converted to "xN AND w" where w is
120045     ** the "interesting" terms of z - terms that did not originate in the
120046     ** ON or USING clause of a LEFT JOIN, and terms that are usable as
120047     ** indices.
120048     **
120049     ** This optimization also only applies if the (x1 OR x2 OR ...) term
120050     ** is not contained in the ON clause of a LEFT JOIN.
120051     ** See ticket http://www.sqlite.org/src/info/f2369304e4
120052     */
120053     if( pWC->nTerm>1 ){
120054       int iTerm;
120055       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
120056         Expr *pExpr = pWC->a[iTerm].pExpr;
120057         if( &pWC->a[iTerm] == pTerm ) continue;
120058         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
120059         if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
120060         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
120061         testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
120062         pExpr = sqlite3ExprDup(db, pExpr, 0);
120063         pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
120064       }
120065       if( pAndExpr ){
120066         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
120067       }
120068     }
120069 
120070     /* Run a separate WHERE clause for each term of the OR clause.  After
120071     ** eliminating duplicates from other WHERE clauses, the action for each
120072     ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
120073     */
120074     wctrlFlags =  WHERE_OMIT_OPEN_CLOSE
120075                 | WHERE_FORCE_TABLE
120076                 | WHERE_ONETABLE_ONLY
120077                 | WHERE_NO_AUTOINDEX;
120078     for(ii=0; ii<pOrWc->nTerm; ii++){
120079       WhereTerm *pOrTerm = &pOrWc->a[ii];
120080       if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
120081         WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
120082         Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
120083         int j1 = 0;                     /* Address of jump operation */
120084         if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
120085           pAndExpr->pLeft = pOrExpr;
120086           pOrExpr = pAndExpr;
120087         }
120088         /* Loop through table entries that match term pOrTerm. */
120089         WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
120090         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
120091                                       wctrlFlags, iCovCur);
120092         assert( pSubWInfo || pParse->nErr || db->mallocFailed );
120093         if( pSubWInfo ){
120094           WhereLoop *pSubLoop;
120095           int addrExplain = explainOneScan(
120096               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
120097           );
120098           addScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
120099 
120100           /* This is the sub-WHERE clause body.  First skip over
120101           ** duplicate rows from prior sub-WHERE clauses, and record the
120102           ** rowid (or PRIMARY KEY) for the current row so that the same
120103           ** row will be skipped in subsequent sub-WHERE clauses.
120104           */
120105           if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
120106             int r;
120107             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
120108             if( HasRowid(pTab) ){
120109               r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
120110               j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
120111               VdbeCoverage(v);
120112             }else{
120113               Index *pPk = sqlite3PrimaryKeyIndex(pTab);
120114               int nPk = pPk->nKeyCol;
120115               int iPk;
120116 
120117               /* Read the PK into an array of temp registers. */
120118               r = sqlite3GetTempRange(pParse, nPk);
120119               for(iPk=0; iPk<nPk; iPk++){
120120                 int iCol = pPk->aiColumn[iPk];
120121                 sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
120122               }
120123 
120124               /* Check if the temp table already contains this key. If so,
120125               ** the row has already been included in the result set and
120126               ** can be ignored (by jumping past the Gosub below). Otherwise,
120127               ** insert the key into the temp table and proceed with processing
120128               ** the row.
120129               **
120130               ** Use some of the same optimizations as OP_RowSetTest: If iSet
120131               ** is zero, assume that the key cannot already be present in
120132               ** the temp table. And if iSet is -1, assume that there is no
120133               ** need to insert the key into the temp table, as it will never
120134               ** be tested for.  */
120135               if( iSet ){
120136                 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
120137                 VdbeCoverage(v);
120138               }
120139               if( iSet>=0 ){
120140                 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
120141                 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
120142                 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
120143               }
120144 
120145               /* Release the array of temp registers */
120146               sqlite3ReleaseTempRange(pParse, r, nPk);
120147             }
120148           }
120149 
120150           /* Invoke the main loop body as a subroutine */
120151           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
120152 
120153           /* Jump here (skipping the main loop body subroutine) if the
120154           ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
120155           if( j1 ) sqlite3VdbeJumpHere(v, j1);
120156 
120157           /* The pSubWInfo->untestedTerms flag means that this OR term
120158           ** contained one or more AND term from a notReady table.  The
120159           ** terms from the notReady table could not be tested and will
120160           ** need to be tested later.
120161           */
120162           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
120163 
120164           /* If all of the OR-connected terms are optimized using the same
120165           ** index, and the index is opened using the same cursor number
120166           ** by each call to sqlite3WhereBegin() made by this loop, it may
120167           ** be possible to use that index as a covering index.
120168           **
120169           ** If the call to sqlite3WhereBegin() above resulted in a scan that
120170           ** uses an index, and this is either the first OR-connected term
120171           ** processed or the index is the same as that used by all previous
120172           ** terms, set pCov to the candidate covering index. Otherwise, set
120173           ** pCov to NULL to indicate that no candidate covering index will
120174           ** be available.
120175           */
120176           pSubLoop = pSubWInfo->a[0].pWLoop;
120177           assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
120178           if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
120179            && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
120180            && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
120181           ){
120182             assert( pSubWInfo->a[0].iIdxCur==iCovCur );
120183             pCov = pSubLoop->u.btree.pIndex;
120184             wctrlFlags |= WHERE_REOPEN_IDX;
120185           }else{
120186             pCov = 0;
120187           }
120188 
120189           /* Finish the loop through table entries that match term pOrTerm. */
120190           sqlite3WhereEnd(pSubWInfo);
120191         }
120192       }
120193     }
120194     pLevel->u.pCovidx = pCov;
120195     if( pCov ) pLevel->iIdxCur = iCovCur;
120196     if( pAndExpr ){
120197       pAndExpr->pLeft = 0;
120198       sqlite3ExprDelete(db, pAndExpr);
120199     }
120200     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
120201     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
120202     sqlite3VdbeResolveLabel(v, iLoopBody);
120203 
120204     if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
120205     if( !untestedTerms ) disableTerm(pLevel, pTerm);
120206   }else
120207 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
120208 
120209   {
120210     /* Case 6:  There is no usable index.  We must do a complete
120211     **          scan of the entire table.
120212     */
120213     static const u8 aStep[] = { OP_Next, OP_Prev };
120214     static const u8 aStart[] = { OP_Rewind, OP_Last };
120215     assert( bRev==0 || bRev==1 );
120216     if( pTabItem->isRecursive ){
120217       /* Tables marked isRecursive have only a single row that is stored in
120218       ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
120219       pLevel->op = OP_Noop;
120220     }else{
120221       pLevel->op = aStep[bRev];
120222       pLevel->p1 = iCur;
120223       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
120224       VdbeCoverageIf(v, bRev==0);
120225       VdbeCoverageIf(v, bRev!=0);
120226       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
120227     }
120228   }
120229 
120230 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
120231   pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
120232 #endif
120233 
120234   /* Insert code to test every subexpression that can be completely
120235   ** computed using the current set of tables.
120236   */
120237   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
120238     Expr *pE;
120239     int skipLikeAddr = 0;
120240     testcase( pTerm->wtFlags & TERM_VIRTUAL );
120241     testcase( pTerm->wtFlags & TERM_CODED );
120242     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
120243     if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
120244       testcase( pWInfo->untestedTerms==0
120245                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
120246       pWInfo->untestedTerms = 1;
120247       continue;
120248     }
120249     pE = pTerm->pExpr;
120250     assert( pE!=0 );
120251     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
120252       continue;
120253     }
120254     if( pTerm->wtFlags & TERM_LIKECOND ){
120255       assert( pLevel->iLikeRepCntr>0 );
120256       skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
120257       VdbeCoverage(v);
120258     }
120259     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
120260     if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
120261     pTerm->wtFlags |= TERM_CODED;
120262   }
120263 
120264   /* Insert code to test for implied constraints based on transitivity
120265   ** of the "==" operator.
120266   **
120267   ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
120268   ** and we are coding the t1 loop and the t2 loop has not yet coded,
120269   ** then we cannot use the "t1.a=t2.b" constraint, but we can code
120270   ** the implied "t1.a=123" constraint.
120271   */
120272   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
120273     Expr *pE, *pEAlt;
120274     WhereTerm *pAlt;
120275     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
120276     if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
120277     if( pTerm->leftCursor!=iCur ) continue;
120278     if( pLevel->iLeftJoin ) continue;
120279     pE = pTerm->pExpr;
120280     assert( !ExprHasProperty(pE, EP_FromJoin) );
120281     assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
120282     pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
120283     if( pAlt==0 ) continue;
120284     if( pAlt->wtFlags & (TERM_CODED) ) continue;
120285     testcase( pAlt->eOperator & WO_EQ );
120286     testcase( pAlt->eOperator & WO_IN );
120287     VdbeModuleComment((v, "begin transitive constraint"));
120288     pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
120289     if( pEAlt ){
120290       *pEAlt = *pAlt->pExpr;
120291       pEAlt->pLeft = pE->pLeft;
120292       sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
120293       sqlite3StackFree(db, pEAlt);
120294     }
120295   }
120296 
120297   /* For a LEFT OUTER JOIN, generate code that will record the fact that
120298   ** at least one row of the right table has matched the left table.
120299   */
120300   if( pLevel->iLeftJoin ){
120301     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
120302     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
120303     VdbeComment((v, "record LEFT JOIN hit"));
120304     sqlite3ExprCacheClear(pParse);
120305     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
120306       testcase( pTerm->wtFlags & TERM_VIRTUAL );
120307       testcase( pTerm->wtFlags & TERM_CODED );
120308       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
120309       if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
120310         assert( pWInfo->untestedTerms );
120311         continue;
120312       }
120313       assert( pTerm->pExpr );
120314       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
120315       pTerm->wtFlags |= TERM_CODED;
120316     }
120317   }
120318 
120319   return pLevel->notReady;
120320 }
120321 
120322 #ifdef WHERETRACE_ENABLED
120323 /*
120324 ** Print the content of a WhereTerm object
120325 */
120326 static void whereTermPrint(WhereTerm *pTerm, int iTerm){
120327   if( pTerm==0 ){
120328     sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
120329   }else{
120330     char zType[4];
120331     memcpy(zType, "...", 4);
120332     if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
120333     if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
120334     if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
120335     sqlite3DebugPrintf("TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x\n",
120336                        iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
120337                        pTerm->eOperator);
120338     sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
120339   }
120340 }
120341 #endif
120342 
120343 #ifdef WHERETRACE_ENABLED
120344 /*
120345 ** Print a WhereLoop object for debugging purposes
120346 */
120347 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
120348   WhereInfo *pWInfo = pWC->pWInfo;
120349   int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
120350   struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
120351   Table *pTab = pItem->pTab;
120352   sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
120353                      p->iTab, nb, p->maskSelf, nb, p->prereq);
120354   sqlite3DebugPrintf(" %12s",
120355                      pItem->zAlias ? pItem->zAlias : pTab->zName);
120356   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
120357     const char *zName;
120358     if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
120359       if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
120360         int i = sqlite3Strlen30(zName) - 1;
120361         while( zName[i]!='_' ) i--;
120362         zName += i;
120363       }
120364       sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
120365     }else{
120366       sqlite3DebugPrintf("%20s","");
120367     }
120368   }else{
120369     char *z;
120370     if( p->u.vtab.idxStr ){
120371       z = sqlite3_mprintf("(%d,\"%s\",%x)",
120372                 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
120373     }else{
120374       z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
120375     }
120376     sqlite3DebugPrintf(" %-19s", z);
120377     sqlite3_free(z);
120378   }
120379   if( p->wsFlags & WHERE_SKIPSCAN ){
120380     sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
120381   }else{
120382     sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
120383   }
120384   sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
120385   if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
120386     int i;
120387     for(i=0; i<p->nLTerm; i++){
120388       whereTermPrint(p->aLTerm[i], i);
120389     }
120390   }
120391 }
120392 #endif
120393 
120394 /*
120395 ** Convert bulk memory into a valid WhereLoop that can be passed
120396 ** to whereLoopClear harmlessly.
120397 */
120398 static void whereLoopInit(WhereLoop *p){
120399   p->aLTerm = p->aLTermSpace;
120400   p->nLTerm = 0;
120401   p->nLSlot = ArraySize(p->aLTermSpace);
120402   p->wsFlags = 0;
120403 }
120404 
120405 /*
120406 ** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
120407 */
120408 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
120409   if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
120410     if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
120411       sqlite3_free(p->u.vtab.idxStr);
120412       p->u.vtab.needFree = 0;
120413       p->u.vtab.idxStr = 0;
120414     }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
120415       sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
120416       sqlite3DbFree(db, p->u.btree.pIndex);
120417       p->u.btree.pIndex = 0;
120418     }
120419   }
120420 }
120421 
120422 /*
120423 ** Deallocate internal memory used by a WhereLoop object
120424 */
120425 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
120426   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
120427   whereLoopClearUnion(db, p);
120428   whereLoopInit(p);
120429 }
120430 
120431 /*
120432 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
120433 */
120434 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
120435   WhereTerm **paNew;
120436   if( p->nLSlot>=n ) return SQLITE_OK;
120437   n = (n+7)&~7;
120438   paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
120439   if( paNew==0 ) return SQLITE_NOMEM;
120440   memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
120441   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
120442   p->aLTerm = paNew;
120443   p->nLSlot = n;
120444   return SQLITE_OK;
120445 }
120446 
120447 /*
120448 ** Transfer content from the second pLoop into the first.
120449 */
120450 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
120451   whereLoopClearUnion(db, pTo);
120452   if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
120453     memset(&pTo->u, 0, sizeof(pTo->u));
120454     return SQLITE_NOMEM;
120455   }
120456   memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
120457   memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
120458   if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
120459     pFrom->u.vtab.needFree = 0;
120460   }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
120461     pFrom->u.btree.pIndex = 0;
120462   }
120463   return SQLITE_OK;
120464 }
120465 
120466 /*
120467 ** Delete a WhereLoop object
120468 */
120469 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
120470   whereLoopClear(db, p);
120471   sqlite3DbFree(db, p);
120472 }
120473 
120474 /*
120475 ** Free a WhereInfo structure
120476 */
120477 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
120478   if( ALWAYS(pWInfo) ){
120479     int i;
120480     for(i=0; i<pWInfo->nLevel; i++){
120481       WhereLevel *pLevel = &pWInfo->a[i];
120482       if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
120483         sqlite3DbFree(db, pLevel->u.in.aInLoop);
120484       }
120485     }
120486     whereClauseClear(&pWInfo->sWC);
120487     while( pWInfo->pLoops ){
120488       WhereLoop *p = pWInfo->pLoops;
120489       pWInfo->pLoops = p->pNextLoop;
120490       whereLoopDelete(db, p);
120491     }
120492     sqlite3DbFree(db, pWInfo);
120493   }
120494 }
120495 
120496 /*
120497 ** Return TRUE if all of the following are true:
120498 **
120499 **   (1)  X has the same or lower cost that Y
120500 **   (2)  X is a proper subset of Y
120501 **   (3)  X skips at least as many columns as Y
120502 **
120503 ** By "proper subset" we mean that X uses fewer WHERE clause terms
120504 ** than Y and that every WHERE clause term used by X is also used
120505 ** by Y.
120506 **
120507 ** If X is a proper subset of Y then Y is a better choice and ought
120508 ** to have a lower cost.  This routine returns TRUE when that cost
120509 ** relationship is inverted and needs to be adjusted.  The third rule
120510 ** was added because if X uses skip-scan less than Y it still might
120511 ** deserve a lower cost even if it is a proper subset of Y.
120512 */
120513 static int whereLoopCheaperProperSubset(
120514   const WhereLoop *pX,       /* First WhereLoop to compare */
120515   const WhereLoop *pY        /* Compare against this WhereLoop */
120516 ){
120517   int i, j;
120518   if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
120519     return 0; /* X is not a subset of Y */
120520   }
120521   if( pY->nSkip > pX->nSkip ) return 0;
120522   if( pX->rRun >= pY->rRun ){
120523     if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
120524     if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
120525   }
120526   for(i=pX->nLTerm-1; i>=0; i--){
120527     if( pX->aLTerm[i]==0 ) continue;
120528     for(j=pY->nLTerm-1; j>=0; j--){
120529       if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
120530     }
120531     if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
120532   }
120533   return 1;  /* All conditions meet */
120534 }
120535 
120536 /*
120537 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
120538 ** that:
120539 **
120540 **   (1) pTemplate costs less than any other WhereLoops that are a proper
120541 **       subset of pTemplate
120542 **
120543 **   (2) pTemplate costs more than any other WhereLoops for which pTemplate
120544 **       is a proper subset.
120545 **
120546 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
120547 ** WHERE clause terms than Y and that every WHERE clause term used by X is
120548 ** also used by Y.
120549 */
120550 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
120551   if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
120552   for(; p; p=p->pNextLoop){
120553     if( p->iTab!=pTemplate->iTab ) continue;
120554     if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
120555     if( whereLoopCheaperProperSubset(p, pTemplate) ){
120556       /* Adjust pTemplate cost downward so that it is cheaper than its
120557       ** subset p. */
120558       WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
120559                        pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
120560       pTemplate->rRun = p->rRun;
120561       pTemplate->nOut = p->nOut - 1;
120562     }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
120563       /* Adjust pTemplate cost upward so that it is costlier than p since
120564       ** pTemplate is a proper subset of p */
120565       WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
120566                        pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
120567       pTemplate->rRun = p->rRun;
120568       pTemplate->nOut = p->nOut + 1;
120569     }
120570   }
120571 }
120572 
120573 /*
120574 ** Search the list of WhereLoops in *ppPrev looking for one that can be
120575 ** supplanted by pTemplate.
120576 **
120577 ** Return NULL if the WhereLoop list contains an entry that can supplant
120578 ** pTemplate, in other words if pTemplate does not belong on the list.
120579 **
120580 ** If pX is a WhereLoop that pTemplate can supplant, then return the
120581 ** link that points to pX.
120582 **
120583 ** If pTemplate cannot supplant any existing element of the list but needs
120584 ** to be added to the list, then return a pointer to the tail of the list.
120585 */
120586 static WhereLoop **whereLoopFindLesser(
120587   WhereLoop **ppPrev,
120588   const WhereLoop *pTemplate
120589 ){
120590   WhereLoop *p;
120591   for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
120592     if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
120593       /* If either the iTab or iSortIdx values for two WhereLoop are different
120594       ** then those WhereLoops need to be considered separately.  Neither is
120595       ** a candidate to replace the other. */
120596       continue;
120597     }
120598     /* In the current implementation, the rSetup value is either zero
120599     ** or the cost of building an automatic index (NlogN) and the NlogN
120600     ** is the same for compatible WhereLoops. */
120601     assert( p->rSetup==0 || pTemplate->rSetup==0
120602                  || p->rSetup==pTemplate->rSetup );
120603 
120604     /* whereLoopAddBtree() always generates and inserts the automatic index
120605     ** case first.  Hence compatible candidate WhereLoops never have a larger
120606     ** rSetup. Call this SETUP-INVARIANT */
120607     assert( p->rSetup>=pTemplate->rSetup );
120608 
120609     /* Any loop using an appliation-defined index (or PRIMARY KEY or
120610     ** UNIQUE constraint) with one or more == constraints is better
120611     ** than an automatic index. Unless it is a skip-scan. */
120612     if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
120613      && (pTemplate->nSkip)==0
120614      && (pTemplate->wsFlags & WHERE_INDEXED)!=0
120615      && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
120616      && (p->prereq & pTemplate->prereq)==pTemplate->prereq
120617     ){
120618       break;
120619     }
120620 
120621     /* If existing WhereLoop p is better than pTemplate, pTemplate can be
120622     ** discarded.  WhereLoop p is better if:
120623     **   (1)  p has no more dependencies than pTemplate, and
120624     **   (2)  p has an equal or lower cost than pTemplate
120625     */
120626     if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
120627      && p->rSetup<=pTemplate->rSetup                  /* (2a) */
120628      && p->rRun<=pTemplate->rRun                      /* (2b) */
120629      && p->nOut<=pTemplate->nOut                      /* (2c) */
120630     ){
120631       return 0;  /* Discard pTemplate */
120632     }
120633 
120634     /* If pTemplate is always better than p, then cause p to be overwritten
120635     ** with pTemplate.  pTemplate is better than p if:
120636     **   (1)  pTemplate has no more dependences than p, and
120637     **   (2)  pTemplate has an equal or lower cost than p.
120638     */
120639     if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
120640      && p->rRun>=pTemplate->rRun                             /* (2a) */
120641      && p->nOut>=pTemplate->nOut                             /* (2b) */
120642     ){
120643       assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
120644       break;   /* Cause p to be overwritten by pTemplate */
120645     }
120646   }
120647   return ppPrev;
120648 }
120649 
120650 /*
120651 ** Insert or replace a WhereLoop entry using the template supplied.
120652 **
120653 ** An existing WhereLoop entry might be overwritten if the new template
120654 ** is better and has fewer dependencies.  Or the template will be ignored
120655 ** and no insert will occur if an existing WhereLoop is faster and has
120656 ** fewer dependencies than the template.  Otherwise a new WhereLoop is
120657 ** added based on the template.
120658 **
120659 ** If pBuilder->pOrSet is not NULL then we care about only the
120660 ** prerequisites and rRun and nOut costs of the N best loops.  That
120661 ** information is gathered in the pBuilder->pOrSet object.  This special
120662 ** processing mode is used only for OR clause processing.
120663 **
120664 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
120665 ** still might overwrite similar loops with the new template if the
120666 ** new template is better.  Loops may be overwritten if the following
120667 ** conditions are met:
120668 **
120669 **    (1)  They have the same iTab.
120670 **    (2)  They have the same iSortIdx.
120671 **    (3)  The template has same or fewer dependencies than the current loop
120672 **    (4)  The template has the same or lower cost than the current loop
120673 */
120674 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
120675   WhereLoop **ppPrev, *p;
120676   WhereInfo *pWInfo = pBuilder->pWInfo;
120677   sqlite3 *db = pWInfo->pParse->db;
120678 
120679   /* If pBuilder->pOrSet is defined, then only keep track of the costs
120680   ** and prereqs.
120681   */
120682   if( pBuilder->pOrSet!=0 ){
120683 #if WHERETRACE_ENABLED
120684     u16 n = pBuilder->pOrSet->n;
120685     int x =
120686 #endif
120687     whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
120688                                     pTemplate->nOut);
120689 #if WHERETRACE_ENABLED /* 0x8 */
120690     if( sqlite3WhereTrace & 0x8 ){
120691       sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
120692       whereLoopPrint(pTemplate, pBuilder->pWC);
120693     }
120694 #endif
120695     return SQLITE_OK;
120696   }
120697 
120698   /* Look for an existing WhereLoop to replace with pTemplate
120699   */
120700   whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
120701   ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
120702 
120703   if( ppPrev==0 ){
120704     /* There already exists a WhereLoop on the list that is better
120705     ** than pTemplate, so just ignore pTemplate */
120706 #if WHERETRACE_ENABLED /* 0x8 */
120707     if( sqlite3WhereTrace & 0x8 ){
120708       sqlite3DebugPrintf("   skip: ");
120709       whereLoopPrint(pTemplate, pBuilder->pWC);
120710     }
120711 #endif
120712     return SQLITE_OK;
120713   }else{
120714     p = *ppPrev;
120715   }
120716 
120717   /* If we reach this point it means that either p[] should be overwritten
120718   ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
120719   ** WhereLoop and insert it.
120720   */
120721 #if WHERETRACE_ENABLED /* 0x8 */
120722   if( sqlite3WhereTrace & 0x8 ){
120723     if( p!=0 ){
120724       sqlite3DebugPrintf("replace: ");
120725       whereLoopPrint(p, pBuilder->pWC);
120726     }
120727     sqlite3DebugPrintf("    add: ");
120728     whereLoopPrint(pTemplate, pBuilder->pWC);
120729   }
120730 #endif
120731   if( p==0 ){
120732     /* Allocate a new WhereLoop to add to the end of the list */
120733     *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
120734     if( p==0 ) return SQLITE_NOMEM;
120735     whereLoopInit(p);
120736     p->pNextLoop = 0;
120737   }else{
120738     /* We will be overwriting WhereLoop p[].  But before we do, first
120739     ** go through the rest of the list and delete any other entries besides
120740     ** p[] that are also supplated by pTemplate */
120741     WhereLoop **ppTail = &p->pNextLoop;
120742     WhereLoop *pToDel;
120743     while( *ppTail ){
120744       ppTail = whereLoopFindLesser(ppTail, pTemplate);
120745       if( ppTail==0 ) break;
120746       pToDel = *ppTail;
120747       if( pToDel==0 ) break;
120748       *ppTail = pToDel->pNextLoop;
120749 #if WHERETRACE_ENABLED /* 0x8 */
120750       if( sqlite3WhereTrace & 0x8 ){
120751         sqlite3DebugPrintf(" delete: ");
120752         whereLoopPrint(pToDel, pBuilder->pWC);
120753       }
120754 #endif
120755       whereLoopDelete(db, pToDel);
120756     }
120757   }
120758   whereLoopXfer(db, p, pTemplate);
120759   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
120760     Index *pIndex = p->u.btree.pIndex;
120761     if( pIndex && pIndex->tnum==0 ){
120762       p->u.btree.pIndex = 0;
120763     }
120764   }
120765   return SQLITE_OK;
120766 }
120767 
120768 /*
120769 ** Adjust the WhereLoop.nOut value downward to account for terms of the
120770 ** WHERE clause that reference the loop but which are not used by an
120771 ** index.
120772 *
120773 ** For every WHERE clause term that is not used by the index
120774 ** and which has a truth probability assigned by one of the likelihood(),
120775 ** likely(), or unlikely() SQL functions, reduce the estimated number
120776 ** of output rows by the probability specified.
120777 **
120778 ** TUNING:  For every WHERE clause term that is not used by the index
120779 ** and which does not have an assigned truth probability, heuristics
120780 ** described below are used to try to estimate the truth probability.
120781 ** TODO --> Perhaps this is something that could be improved by better
120782 ** table statistics.
120783 **
120784 ** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
120785 ** value corresponds to -1 in LogEst notation, so this means decrement
120786 ** the WhereLoop.nOut field for every such WHERE clause term.
120787 **
120788 ** Heuristic 2:  If there exists one or more WHERE clause terms of the
120789 ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
120790 ** final output row estimate is no greater than 1/4 of the total number
120791 ** of rows in the table.  In other words, assume that x==EXPR will filter
120792 ** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
120793 ** "x" column is boolean or else -1 or 0 or 1 is a common default value
120794 ** on the "x" column and so in that case only cap the output row estimate
120795 ** at 1/2 instead of 1/4.
120796 */
120797 static void whereLoopOutputAdjust(
120798   WhereClause *pWC,      /* The WHERE clause */
120799   WhereLoop *pLoop,      /* The loop to adjust downward */
120800   LogEst nRow            /* Number of rows in the entire table */
120801 ){
120802   WhereTerm *pTerm, *pX;
120803   Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
120804   int i, j, k;
120805   LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
120806 
120807   assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
120808   for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
120809     if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
120810     if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
120811     if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
120812     for(j=pLoop->nLTerm-1; j>=0; j--){
120813       pX = pLoop->aLTerm[j];
120814       if( pX==0 ) continue;
120815       if( pX==pTerm ) break;
120816       if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
120817     }
120818     if( j<0 ){
120819       if( pTerm->truthProb<=0 ){
120820         /* If a truth probability is specified using the likelihood() hints,
120821         ** then use the probability provided by the application. */
120822         pLoop->nOut += pTerm->truthProb;
120823       }else{
120824         /* In the absence of explicit truth probabilities, use heuristics to
120825         ** guess a reasonable truth probability. */
120826         pLoop->nOut--;
120827         if( pTerm->eOperator&WO_EQ ){
120828           Expr *pRight = pTerm->pExpr->pRight;
120829           if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
120830             k = 10;
120831           }else{
120832             k = 20;
120833           }
120834           if( iReduce<k ) iReduce = k;
120835         }
120836       }
120837     }
120838   }
120839   if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;
120840 }
120841 
120842 /*
120843 ** Adjust the cost C by the costMult facter T.  This only occurs if
120844 ** compiled with -DSQLITE_ENABLE_COSTMULT
120845 */
120846 #ifdef SQLITE_ENABLE_COSTMULT
120847 # define ApplyCostMultiplier(C,T)  C += T
120848 #else
120849 # define ApplyCostMultiplier(C,T)
120850 #endif
120851 
120852 /*
120853 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
120854 ** index pIndex. Try to match one more.
120855 **
120856 ** When this function is called, pBuilder->pNew->nOut contains the
120857 ** number of rows expected to be visited by filtering using the nEq
120858 ** terms only. If it is modified, this value is restored before this
120859 ** function returns.
120860 **
120861 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
120862 ** INTEGER PRIMARY KEY.
120863 */
120864 static int whereLoopAddBtreeIndex(
120865   WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
120866   struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
120867   Index *pProbe,                  /* An index on pSrc */
120868   LogEst nInMul                   /* log(Number of iterations due to IN) */
120869 ){
120870   WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
120871   Parse *pParse = pWInfo->pParse;        /* Parsing context */
120872   sqlite3 *db = pParse->db;       /* Database connection malloc context */
120873   WhereLoop *pNew;                /* Template WhereLoop under construction */
120874   WhereTerm *pTerm;               /* A WhereTerm under consideration */
120875   int opMask;                     /* Valid operators for constraints */
120876   WhereScan scan;                 /* Iterator for WHERE terms */
120877   Bitmask saved_prereq;           /* Original value of pNew->prereq */
120878   u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
120879   u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
120880   u16 saved_nSkip;                /* Original value of pNew->nSkip */
120881   u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
120882   LogEst saved_nOut;              /* Original value of pNew->nOut */
120883   int iCol;                       /* Index of the column in the table */
120884   int rc = SQLITE_OK;             /* Return code */
120885   LogEst rSize;                   /* Number of rows in the table */
120886   LogEst rLogSize;                /* Logarithm of table size */
120887   WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
120888 
120889   pNew = pBuilder->pNew;
120890   if( db->mallocFailed ) return SQLITE_NOMEM;
120891 
120892   assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
120893   assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
120894   if( pNew->wsFlags & WHERE_BTM_LIMIT ){
120895     opMask = WO_LT|WO_LE;
120896   }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
120897     opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
120898   }else{
120899     opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
120900   }
120901   if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
120902 
120903   assert( pNew->u.btree.nEq<pProbe->nColumn );
120904   iCol = pProbe->aiColumn[pNew->u.btree.nEq];
120905 
120906   pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
120907                         opMask, pProbe);
120908   saved_nEq = pNew->u.btree.nEq;
120909   saved_nSkip = pNew->nSkip;
120910   saved_nLTerm = pNew->nLTerm;
120911   saved_wsFlags = pNew->wsFlags;
120912   saved_prereq = pNew->prereq;
120913   saved_nOut = pNew->nOut;
120914   pNew->rSetup = 0;
120915   rSize = pProbe->aiRowLogEst[0];
120916   rLogSize = estLog(rSize);
120917   for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
120918     u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
120919     LogEst rCostIdx;
120920     LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
120921     int nIn = 0;
120922 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
120923     int nRecValid = pBuilder->nRecValid;
120924 #endif
120925     if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
120926      && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
120927     ){
120928       continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
120929     }
120930     if( pTerm->prereqRight & pNew->maskSelf ) continue;
120931 
120932     /* Do not allow the upper bound of a LIKE optimization range constraint
120933     ** to mix with a lower range bound from some other source */
120934     if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
120935 
120936     pNew->wsFlags = saved_wsFlags;
120937     pNew->u.btree.nEq = saved_nEq;
120938     pNew->nLTerm = saved_nLTerm;
120939     if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
120940     pNew->aLTerm[pNew->nLTerm++] = pTerm;
120941     pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
120942 
120943     assert( nInMul==0
120944         || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
120945         || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
120946         || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
120947     );
120948 
120949     if( eOp & WO_IN ){
120950       Expr *pExpr = pTerm->pExpr;
120951       pNew->wsFlags |= WHERE_COLUMN_IN;
120952       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
120953         /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
120954         nIn = 46;  assert( 46==sqlite3LogEst(25) );
120955       }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
120956         /* "x IN (value, value, ...)" */
120957         nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
120958       }
120959       assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
120960                         ** changes "x IN (?)" into "x=?". */
120961 
120962     }else if( eOp & (WO_EQ) ){
120963       pNew->wsFlags |= WHERE_COLUMN_EQ;
120964       if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
120965         if( iCol>=0 && pProbe->uniqNotNull==0 ){
120966           pNew->wsFlags |= WHERE_UNQ_WANTED;
120967         }else{
120968           pNew->wsFlags |= WHERE_ONEROW;
120969         }
120970       }
120971     }else if( eOp & WO_ISNULL ){
120972       pNew->wsFlags |= WHERE_COLUMN_NULL;
120973     }else if( eOp & (WO_GT|WO_GE) ){
120974       testcase( eOp & WO_GT );
120975       testcase( eOp & WO_GE );
120976       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
120977       pBtm = pTerm;
120978       pTop = 0;
120979       if( pTerm->wtFlags & TERM_LIKEOPT ){
120980         /* Range contraints that come from the LIKE optimization are
120981         ** always used in pairs. */
120982         pTop = &pTerm[1];
120983         assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
120984         assert( pTop->wtFlags & TERM_LIKEOPT );
120985         assert( pTop->eOperator==WO_LT );
120986         if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
120987         pNew->aLTerm[pNew->nLTerm++] = pTop;
120988         pNew->wsFlags |= WHERE_TOP_LIMIT;
120989       }
120990     }else{
120991       assert( eOp & (WO_LT|WO_LE) );
120992       testcase( eOp & WO_LT );
120993       testcase( eOp & WO_LE );
120994       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
120995       pTop = pTerm;
120996       pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
120997                      pNew->aLTerm[pNew->nLTerm-2] : 0;
120998     }
120999 
121000     /* At this point pNew->nOut is set to the number of rows expected to
121001     ** be visited by the index scan before considering term pTerm, or the
121002     ** values of nIn and nInMul. In other words, assuming that all
121003     ** "x IN(...)" terms are replaced with "x = ?". This block updates
121004     ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
121005     assert( pNew->nOut==saved_nOut );
121006     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
121007       /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
121008       ** data, using some other estimate.  */
121009       whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
121010     }else{
121011       int nEq = ++pNew->u.btree.nEq;
121012       assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
121013 
121014       assert( pNew->nOut==saved_nOut );
121015       if( pTerm->truthProb<=0 && iCol>=0 ){
121016         assert( (eOp & WO_IN) || nIn==0 );
121017         testcase( eOp & WO_IN );
121018         pNew->nOut += pTerm->truthProb;
121019         pNew->nOut -= nIn;
121020       }else{
121021 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
121022         tRowcnt nOut = 0;
121023         if( nInMul==0
121024          && pProbe->nSample
121025          && pNew->u.btree.nEq<=pProbe->nSampleCol
121026          && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
121027         ){
121028           Expr *pExpr = pTerm->pExpr;
121029           if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
121030             testcase( eOp & WO_EQ );
121031             testcase( eOp & WO_ISNULL );
121032             rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
121033           }else{
121034             rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
121035           }
121036           if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
121037           if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
121038           if( nOut ){
121039             pNew->nOut = sqlite3LogEst(nOut);
121040             if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
121041             pNew->nOut -= nIn;
121042           }
121043         }
121044         if( nOut==0 )
121045 #endif
121046         {
121047           pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
121048           if( eOp & WO_ISNULL ){
121049             /* TUNING: If there is no likelihood() value, assume that a
121050             ** "col IS NULL" expression matches twice as many rows
121051             ** as (col=?). */
121052             pNew->nOut += 10;
121053           }
121054         }
121055       }
121056     }
121057 
121058     /* Set rCostIdx to the cost of visiting selected rows in index. Add
121059     ** it to pNew->rRun, which is currently set to the cost of the index
121060     ** seek only. Then, if this is a non-covering index, add the cost of
121061     ** visiting the rows in the main table.  */
121062     rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
121063     pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
121064     if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
121065       pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
121066     }
121067     ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
121068 
121069     nOutUnadjusted = pNew->nOut;
121070     pNew->rRun += nInMul + nIn;
121071     pNew->nOut += nInMul + nIn;
121072     whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
121073     rc = whereLoopInsert(pBuilder, pNew);
121074 
121075     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
121076       pNew->nOut = saved_nOut;
121077     }else{
121078       pNew->nOut = nOutUnadjusted;
121079     }
121080 
121081     if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
121082      && pNew->u.btree.nEq<pProbe->nColumn
121083     ){
121084       whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
121085     }
121086     pNew->nOut = saved_nOut;
121087 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
121088     pBuilder->nRecValid = nRecValid;
121089 #endif
121090   }
121091   pNew->prereq = saved_prereq;
121092   pNew->u.btree.nEq = saved_nEq;
121093   pNew->nSkip = saved_nSkip;
121094   pNew->wsFlags = saved_wsFlags;
121095   pNew->nOut = saved_nOut;
121096   pNew->nLTerm = saved_nLTerm;
121097 
121098   /* Consider using a skip-scan if there are no WHERE clause constraints
121099   ** available for the left-most terms of the index, and if the average
121100   ** number of repeats in the left-most terms is at least 18.
121101   **
121102   ** The magic number 18 is selected on the basis that scanning 17 rows
121103   ** is almost always quicker than an index seek (even though if the index
121104   ** contains fewer than 2^17 rows we assume otherwise in other parts of
121105   ** the code). And, even if it is not, it should not be too much slower.
121106   ** On the other hand, the extra seeks could end up being significantly
121107   ** more expensive.  */
121108   assert( 42==sqlite3LogEst(18) );
121109   if( saved_nEq==saved_nSkip
121110    && saved_nEq+1<pProbe->nKeyCol
121111    && pProbe->noSkipScan==0
121112    && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
121113    && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
121114   ){
121115     LogEst nIter;
121116     pNew->u.btree.nEq++;
121117     pNew->nSkip++;
121118     pNew->aLTerm[pNew->nLTerm++] = 0;
121119     pNew->wsFlags |= WHERE_SKIPSCAN;
121120     nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
121121     pNew->nOut -= nIter;
121122     /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
121123     ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
121124     nIter += 5;
121125     whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
121126     pNew->nOut = saved_nOut;
121127     pNew->u.btree.nEq = saved_nEq;
121128     pNew->nSkip = saved_nSkip;
121129     pNew->wsFlags = saved_wsFlags;
121130   }
121131 
121132   return rc;
121133 }
121134 
121135 /*
121136 ** Return True if it is possible that pIndex might be useful in
121137 ** implementing the ORDER BY clause in pBuilder.
121138 **
121139 ** Return False if pBuilder does not contain an ORDER BY clause or
121140 ** if there is no way for pIndex to be useful in implementing that
121141 ** ORDER BY clause.
121142 */
121143 static int indexMightHelpWithOrderBy(
121144   WhereLoopBuilder *pBuilder,
121145   Index *pIndex,
121146   int iCursor
121147 ){
121148   ExprList *pOB;
121149   int ii, jj;
121150 
121151   if( pIndex->bUnordered ) return 0;
121152   if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
121153   for(ii=0; ii<pOB->nExpr; ii++){
121154     Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
121155     if( pExpr->op!=TK_COLUMN ) return 0;
121156     if( pExpr->iTable==iCursor ){
121157       if( pExpr->iColumn<0 ) return 1;
121158       for(jj=0; jj<pIndex->nKeyCol; jj++){
121159         if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
121160       }
121161     }
121162   }
121163   return 0;
121164 }
121165 
121166 /*
121167 ** Return a bitmask where 1s indicate that the corresponding column of
121168 ** the table is used by an index.  Only the first 63 columns are considered.
121169 */
121170 static Bitmask columnsInIndex(Index *pIdx){
121171   Bitmask m = 0;
121172   int j;
121173   for(j=pIdx->nColumn-1; j>=0; j--){
121174     int x = pIdx->aiColumn[j];
121175     if( x>=0 ){
121176       testcase( x==BMS-1 );
121177       testcase( x==BMS-2 );
121178       if( x<BMS-1 ) m |= MASKBIT(x);
121179     }
121180   }
121181   return m;
121182 }
121183 
121184 /* Check to see if a partial index with pPartIndexWhere can be used
121185 ** in the current query.  Return true if it can be and false if not.
121186 */
121187 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
121188   int i;
121189   WhereTerm *pTerm;
121190   for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
121191     Expr *pExpr = pTerm->pExpr;
121192     if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
121193      && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
121194     ){
121195       return 1;
121196     }
121197   }
121198   return 0;
121199 }
121200 
121201 /*
121202 ** Add all WhereLoop objects for a single table of the join where the table
121203 ** is idenfied by pBuilder->pNew->iTab.  That table is guaranteed to be
121204 ** a b-tree table, not a virtual table.
121205 **
121206 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
121207 ** are calculated as follows:
121208 **
121209 ** For a full scan, assuming the table (or index) contains nRow rows:
121210 **
121211 **     cost = nRow * 3.0                    // full-table scan
121212 **     cost = nRow * K                      // scan of covering index
121213 **     cost = nRow * (K+3.0)                // scan of non-covering index
121214 **
121215 ** where K is a value between 1.1 and 3.0 set based on the relative
121216 ** estimated average size of the index and table records.
121217 **
121218 ** For an index scan, where nVisit is the number of index rows visited
121219 ** by the scan, and nSeek is the number of seek operations required on
121220 ** the index b-tree:
121221 **
121222 **     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
121223 **     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
121224 **
121225 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
121226 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
121227 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
121228 **
121229 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
121230 ** of uncertainty.  For this reason, scoring is designed to pick plans that
121231 ** "do the least harm" if the estimates are inaccurate.  For example, a
121232 ** log(nRow) factor is omitted from a non-covering index scan in order to
121233 ** bias the scoring in favor of using an index, since the worst-case
121234 ** performance of using an index is far better than the worst-case performance
121235 ** of a full table scan.
121236 */
121237 static int whereLoopAddBtree(
121238   WhereLoopBuilder *pBuilder, /* WHERE clause information */
121239   Bitmask mExtra              /* Extra prerequesites for using this table */
121240 ){
121241   WhereInfo *pWInfo;          /* WHERE analysis context */
121242   Index *pProbe;              /* An index we are evaluating */
121243   Index sPk;                  /* A fake index object for the primary key */
121244   LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
121245   i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
121246   SrcList *pTabList;          /* The FROM clause */
121247   struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
121248   WhereLoop *pNew;            /* Template WhereLoop object */
121249   int rc = SQLITE_OK;         /* Return code */
121250   int iSortIdx = 1;           /* Index number */
121251   int b;                      /* A boolean value */
121252   LogEst rSize;               /* number of rows in the table */
121253   LogEst rLogSize;            /* Logarithm of the number of rows in the table */
121254   WhereClause *pWC;           /* The parsed WHERE clause */
121255   Table *pTab;                /* Table being queried */
121256 
121257   pNew = pBuilder->pNew;
121258   pWInfo = pBuilder->pWInfo;
121259   pTabList = pWInfo->pTabList;
121260   pSrc = pTabList->a + pNew->iTab;
121261   pTab = pSrc->pTab;
121262   pWC = pBuilder->pWC;
121263   assert( !IsVirtual(pSrc->pTab) );
121264 
121265   if( pSrc->pIndex ){
121266     /* An INDEXED BY clause specifies a particular index to use */
121267     pProbe = pSrc->pIndex;
121268   }else if( !HasRowid(pTab) ){
121269     pProbe = pTab->pIndex;
121270   }else{
121271     /* There is no INDEXED BY clause.  Create a fake Index object in local
121272     ** variable sPk to represent the rowid primary key index.  Make this
121273     ** fake index the first in a chain of Index objects with all of the real
121274     ** indices to follow */
121275     Index *pFirst;                  /* First of real indices on the table */
121276     memset(&sPk, 0, sizeof(Index));
121277     sPk.nKeyCol = 1;
121278     sPk.nColumn = 1;
121279     sPk.aiColumn = &aiColumnPk;
121280     sPk.aiRowLogEst = aiRowEstPk;
121281     sPk.onError = OE_Replace;
121282     sPk.pTable = pTab;
121283     sPk.szIdxRow = pTab->szTabRow;
121284     aiRowEstPk[0] = pTab->nRowLogEst;
121285     aiRowEstPk[1] = 0;
121286     pFirst = pSrc->pTab->pIndex;
121287     if( pSrc->notIndexed==0 ){
121288       /* The real indices of the table are only considered if the
121289       ** NOT INDEXED qualifier is omitted from the FROM clause */
121290       sPk.pNext = pFirst;
121291     }
121292     pProbe = &sPk;
121293   }
121294   rSize = pTab->nRowLogEst;
121295   rLogSize = estLog(rSize);
121296 
121297 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
121298   /* Automatic indexes */
121299   if( !pBuilder->pOrSet
121300    && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
121301    && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
121302    && pSrc->pIndex==0
121303    && !pSrc->viaCoroutine
121304    && !pSrc->notIndexed
121305    && HasRowid(pTab)
121306    && !pSrc->isCorrelated
121307    && !pSrc->isRecursive
121308   ){
121309     /* Generate auto-index WhereLoops */
121310     WhereTerm *pTerm;
121311     WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
121312     for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
121313       if( pTerm->prereqRight & pNew->maskSelf ) continue;
121314       if( termCanDriveIndex(pTerm, pSrc, 0) ){
121315         pNew->u.btree.nEq = 1;
121316         pNew->nSkip = 0;
121317         pNew->u.btree.pIndex = 0;
121318         pNew->nLTerm = 1;
121319         pNew->aLTerm[0] = pTerm;
121320         /* TUNING: One-time cost for computing the automatic index is
121321         ** estimated to be X*N*log2(N) where N is the number of rows in
121322         ** the table being indexed and where X is 7 (LogEst=28) for normal
121323         ** tables or 1.375 (LogEst=4) for views and subqueries.  The value
121324         ** of X is smaller for views and subqueries so that the query planner
121325         ** will be more aggressive about generating automatic indexes for
121326         ** those objects, since there is no opportunity to add schema
121327         ** indexes on subqueries and views. */
121328         pNew->rSetup = rLogSize + rSize + 4;
121329         if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
121330           pNew->rSetup += 24;
121331         }
121332         ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
121333         /* TUNING: Each index lookup yields 20 rows in the table.  This
121334         ** is more than the usual guess of 10 rows, since we have no way
121335         ** of knowing how selective the index will ultimately be.  It would
121336         ** not be unreasonable to make this value much larger. */
121337         pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
121338         pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
121339         pNew->wsFlags = WHERE_AUTO_INDEX;
121340         pNew->prereq = mExtra | pTerm->prereqRight;
121341         rc = whereLoopInsert(pBuilder, pNew);
121342       }
121343     }
121344   }
121345 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
121346 
121347   /* Loop over all indices
121348   */
121349   for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
121350     if( pProbe->pPartIdxWhere!=0
121351      && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
121352       testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
121353       continue;  /* Partial index inappropriate for this query */
121354     }
121355     rSize = pProbe->aiRowLogEst[0];
121356     pNew->u.btree.nEq = 0;
121357     pNew->nSkip = 0;
121358     pNew->nLTerm = 0;
121359     pNew->iSortIdx = 0;
121360     pNew->rSetup = 0;
121361     pNew->prereq = mExtra;
121362     pNew->nOut = rSize;
121363     pNew->u.btree.pIndex = pProbe;
121364     b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
121365     /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
121366     assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
121367     if( pProbe->tnum<=0 ){
121368       /* Integer primary key index */
121369       pNew->wsFlags = WHERE_IPK;
121370 
121371       /* Full table scan */
121372       pNew->iSortIdx = b ? iSortIdx : 0;
121373       /* TUNING: Cost of full table scan is (N*3.0). */
121374       pNew->rRun = rSize + 16;
121375       ApplyCostMultiplier(pNew->rRun, pTab->costMult);
121376       whereLoopOutputAdjust(pWC, pNew, rSize);
121377       rc = whereLoopInsert(pBuilder, pNew);
121378       pNew->nOut = rSize;
121379       if( rc ) break;
121380     }else{
121381       Bitmask m;
121382       if( pProbe->isCovering ){
121383         pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
121384         m = 0;
121385       }else{
121386         m = pSrc->colUsed & ~columnsInIndex(pProbe);
121387         pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
121388       }
121389 
121390       /* Full scan via index */
121391       if( b
121392        || !HasRowid(pTab)
121393        || ( m==0
121394          && pProbe->bUnordered==0
121395          && (pProbe->szIdxRow<pTab->szTabRow)
121396          && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
121397          && sqlite3GlobalConfig.bUseCis
121398          && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
121399           )
121400       ){
121401         pNew->iSortIdx = b ? iSortIdx : 0;
121402 
121403         /* The cost of visiting the index rows is N*K, where K is
121404         ** between 1.1 and 3.0, depending on the relative sizes of the
121405         ** index and table rows. If this is a non-covering index scan,
121406         ** also add the cost of visiting table rows (N*3.0).  */
121407         pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
121408         if( m!=0 ){
121409           pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
121410         }
121411         ApplyCostMultiplier(pNew->rRun, pTab->costMult);
121412         whereLoopOutputAdjust(pWC, pNew, rSize);
121413         rc = whereLoopInsert(pBuilder, pNew);
121414         pNew->nOut = rSize;
121415         if( rc ) break;
121416       }
121417     }
121418 
121419     rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
121420 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
121421     sqlite3Stat4ProbeFree(pBuilder->pRec);
121422     pBuilder->nRecValid = 0;
121423     pBuilder->pRec = 0;
121424 #endif
121425 
121426     /* If there was an INDEXED BY clause, then only that one index is
121427     ** considered. */
121428     if( pSrc->pIndex ) break;
121429   }
121430   return rc;
121431 }
121432 
121433 #ifndef SQLITE_OMIT_VIRTUALTABLE
121434 /*
121435 ** Add all WhereLoop objects for a table of the join identified by
121436 ** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
121437 */
121438 static int whereLoopAddVirtual(
121439   WhereLoopBuilder *pBuilder,  /* WHERE clause information */
121440   Bitmask mExtra
121441 ){
121442   WhereInfo *pWInfo;           /* WHERE analysis context */
121443   Parse *pParse;               /* The parsing context */
121444   WhereClause *pWC;            /* The WHERE clause */
121445   struct SrcList_item *pSrc;   /* The FROM clause term to search */
121446   Table *pTab;
121447   sqlite3 *db;
121448   sqlite3_index_info *pIdxInfo;
121449   struct sqlite3_index_constraint *pIdxCons;
121450   struct sqlite3_index_constraint_usage *pUsage;
121451   WhereTerm *pTerm;
121452   int i, j;
121453   int iTerm, mxTerm;
121454   int nConstraint;
121455   int seenIn = 0;              /* True if an IN operator is seen */
121456   int seenVar = 0;             /* True if a non-constant constraint is seen */
121457   int iPhase;                  /* 0: const w/o IN, 1: const, 2: no IN,  2: IN */
121458   WhereLoop *pNew;
121459   int rc = SQLITE_OK;
121460 
121461   pWInfo = pBuilder->pWInfo;
121462   pParse = pWInfo->pParse;
121463   db = pParse->db;
121464   pWC = pBuilder->pWC;
121465   pNew = pBuilder->pNew;
121466   pSrc = &pWInfo->pTabList->a[pNew->iTab];
121467   pTab = pSrc->pTab;
121468   assert( IsVirtual(pTab) );
121469   pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
121470   if( pIdxInfo==0 ) return SQLITE_NOMEM;
121471   pNew->prereq = 0;
121472   pNew->rSetup = 0;
121473   pNew->wsFlags = WHERE_VIRTUALTABLE;
121474   pNew->nLTerm = 0;
121475   pNew->u.vtab.needFree = 0;
121476   pUsage = pIdxInfo->aConstraintUsage;
121477   nConstraint = pIdxInfo->nConstraint;
121478   if( whereLoopResize(db, pNew, nConstraint) ){
121479     sqlite3DbFree(db, pIdxInfo);
121480     return SQLITE_NOMEM;
121481   }
121482 
121483   for(iPhase=0; iPhase<=3; iPhase++){
121484     if( !seenIn && (iPhase&1)!=0 ){
121485       iPhase++;
121486       if( iPhase>3 ) break;
121487     }
121488     if( !seenVar && iPhase>1 ) break;
121489     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
121490     for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
121491       j = pIdxCons->iTermOffset;
121492       pTerm = &pWC->a[j];
121493       switch( iPhase ){
121494         case 0:    /* Constants without IN operator */
121495           pIdxCons->usable = 0;
121496           if( (pTerm->eOperator & WO_IN)!=0 ){
121497             seenIn = 1;
121498           }
121499           if( pTerm->prereqRight!=0 ){
121500             seenVar = 1;
121501           }else if( (pTerm->eOperator & WO_IN)==0 ){
121502             pIdxCons->usable = 1;
121503           }
121504           break;
121505         case 1:    /* Constants with IN operators */
121506           assert( seenIn );
121507           pIdxCons->usable = (pTerm->prereqRight==0);
121508           break;
121509         case 2:    /* Variables without IN */
121510           assert( seenVar );
121511           pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
121512           break;
121513         default:   /* Variables with IN */
121514           assert( seenVar && seenIn );
121515           pIdxCons->usable = 1;
121516           break;
121517       }
121518     }
121519     memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
121520     if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
121521     pIdxInfo->idxStr = 0;
121522     pIdxInfo->idxNum = 0;
121523     pIdxInfo->needToFreeIdxStr = 0;
121524     pIdxInfo->orderByConsumed = 0;
121525     pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
121526     pIdxInfo->estimatedRows = 25;
121527     rc = vtabBestIndex(pParse, pTab, pIdxInfo);
121528     if( rc ) goto whereLoopAddVtab_exit;
121529     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
121530     pNew->prereq = mExtra;
121531     mxTerm = -1;
121532     assert( pNew->nLSlot>=nConstraint );
121533     for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
121534     pNew->u.vtab.omitMask = 0;
121535     for(i=0; i<nConstraint; i++, pIdxCons++){
121536       if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
121537         j = pIdxCons->iTermOffset;
121538         if( iTerm>=nConstraint
121539          || j<0
121540          || j>=pWC->nTerm
121541          || pNew->aLTerm[iTerm]!=0
121542         ){
121543           rc = SQLITE_ERROR;
121544           sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
121545           goto whereLoopAddVtab_exit;
121546         }
121547         testcase( iTerm==nConstraint-1 );
121548         testcase( j==0 );
121549         testcase( j==pWC->nTerm-1 );
121550         pTerm = &pWC->a[j];
121551         pNew->prereq |= pTerm->prereqRight;
121552         assert( iTerm<pNew->nLSlot );
121553         pNew->aLTerm[iTerm] = pTerm;
121554         if( iTerm>mxTerm ) mxTerm = iTerm;
121555         testcase( iTerm==15 );
121556         testcase( iTerm==16 );
121557         if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
121558         if( (pTerm->eOperator & WO_IN)!=0 ){
121559           if( pUsage[i].omit==0 ){
121560             /* Do not attempt to use an IN constraint if the virtual table
121561             ** says that the equivalent EQ constraint cannot be safely omitted.
121562             ** If we do attempt to use such a constraint, some rows might be
121563             ** repeated in the output. */
121564             break;
121565           }
121566           /* A virtual table that is constrained by an IN clause may not
121567           ** consume the ORDER BY clause because (1) the order of IN terms
121568           ** is not necessarily related to the order of output terms and
121569           ** (2) Multiple outputs from a single IN value will not merge
121570           ** together.  */
121571           pIdxInfo->orderByConsumed = 0;
121572         }
121573       }
121574     }
121575     if( i>=nConstraint ){
121576       pNew->nLTerm = mxTerm+1;
121577       assert( pNew->nLTerm<=pNew->nLSlot );
121578       pNew->u.vtab.idxNum = pIdxInfo->idxNum;
121579       pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
121580       pIdxInfo->needToFreeIdxStr = 0;
121581       pNew->u.vtab.idxStr = pIdxInfo->idxStr;
121582       pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
121583                                       pIdxInfo->nOrderBy : 0);
121584       pNew->rSetup = 0;
121585       pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
121586       pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
121587       whereLoopInsert(pBuilder, pNew);
121588       if( pNew->u.vtab.needFree ){
121589         sqlite3_free(pNew->u.vtab.idxStr);
121590         pNew->u.vtab.needFree = 0;
121591       }
121592     }
121593   }
121594 
121595 whereLoopAddVtab_exit:
121596   if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
121597   sqlite3DbFree(db, pIdxInfo);
121598   return rc;
121599 }
121600 #endif /* SQLITE_OMIT_VIRTUALTABLE */
121601 
121602 /*
121603 ** Add WhereLoop entries to handle OR terms.  This works for either
121604 ** btrees or virtual tables.
121605 */
121606 static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
121607   WhereInfo *pWInfo = pBuilder->pWInfo;
121608   WhereClause *pWC;
121609   WhereLoop *pNew;
121610   WhereTerm *pTerm, *pWCEnd;
121611   int rc = SQLITE_OK;
121612   int iCur;
121613   WhereClause tempWC;
121614   WhereLoopBuilder sSubBuild;
121615   WhereOrSet sSum, sCur;
121616   struct SrcList_item *pItem;
121617 
121618   pWC = pBuilder->pWC;
121619   pWCEnd = pWC->a + pWC->nTerm;
121620   pNew = pBuilder->pNew;
121621   memset(&sSum, 0, sizeof(sSum));
121622   pItem = pWInfo->pTabList->a + pNew->iTab;
121623   iCur = pItem->iCursor;
121624 
121625   for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
121626     if( (pTerm->eOperator & WO_OR)!=0
121627      && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
121628     ){
121629       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
121630       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
121631       WhereTerm *pOrTerm;
121632       int once = 1;
121633       int i, j;
121634 
121635       sSubBuild = *pBuilder;
121636       sSubBuild.pOrderBy = 0;
121637       sSubBuild.pOrSet = &sCur;
121638 
121639       WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
121640       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
121641         if( (pOrTerm->eOperator & WO_AND)!=0 ){
121642           sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
121643         }else if( pOrTerm->leftCursor==iCur ){
121644           tempWC.pWInfo = pWC->pWInfo;
121645           tempWC.pOuter = pWC;
121646           tempWC.op = TK_AND;
121647           tempWC.nTerm = 1;
121648           tempWC.a = pOrTerm;
121649           sSubBuild.pWC = &tempWC;
121650         }else{
121651           continue;
121652         }
121653         sCur.n = 0;
121654 #ifdef WHERETRACE_ENABLED
121655         WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
121656                    (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
121657         if( sqlite3WhereTrace & 0x400 ){
121658           for(i=0; i<sSubBuild.pWC->nTerm; i++){
121659             whereTermPrint(&sSubBuild.pWC->a[i], i);
121660           }
121661         }
121662 #endif
121663 #ifndef SQLITE_OMIT_VIRTUALTABLE
121664         if( IsVirtual(pItem->pTab) ){
121665           rc = whereLoopAddVirtual(&sSubBuild, mExtra);
121666         }else
121667 #endif
121668         {
121669           rc = whereLoopAddBtree(&sSubBuild, mExtra);
121670         }
121671         if( rc==SQLITE_OK ){
121672           rc = whereLoopAddOr(&sSubBuild, mExtra);
121673         }
121674         assert( rc==SQLITE_OK || sCur.n==0 );
121675         if( sCur.n==0 ){
121676           sSum.n = 0;
121677           break;
121678         }else if( once ){
121679           whereOrMove(&sSum, &sCur);
121680           once = 0;
121681         }else{
121682           WhereOrSet sPrev;
121683           whereOrMove(&sPrev, &sSum);
121684           sSum.n = 0;
121685           for(i=0; i<sPrev.n; i++){
121686             for(j=0; j<sCur.n; j++){
121687               whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
121688                             sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
121689                             sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
121690             }
121691           }
121692         }
121693       }
121694       pNew->nLTerm = 1;
121695       pNew->aLTerm[0] = pTerm;
121696       pNew->wsFlags = WHERE_MULTI_OR;
121697       pNew->rSetup = 0;
121698       pNew->iSortIdx = 0;
121699       memset(&pNew->u, 0, sizeof(pNew->u));
121700       for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
121701         /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
121702         ** of all sub-scans required by the OR-scan. However, due to rounding
121703         ** errors, it may be that the cost of the OR-scan is equal to its
121704         ** most expensive sub-scan. Add the smallest possible penalty
121705         ** (equivalent to multiplying the cost by 1.07) to ensure that
121706         ** this does not happen. Otherwise, for WHERE clauses such as the
121707         ** following where there is an index on "y":
121708         **
121709         **     WHERE likelihood(x=?, 0.99) OR y=?
121710         **
121711         ** the planner may elect to "OR" together a full-table scan and an
121712         ** index lookup. And other similarly odd results.  */
121713         pNew->rRun = sSum.a[i].rRun + 1;
121714         pNew->nOut = sSum.a[i].nOut;
121715         pNew->prereq = sSum.a[i].prereq;
121716         rc = whereLoopInsert(pBuilder, pNew);
121717       }
121718       WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
121719     }
121720   }
121721   return rc;
121722 }
121723 
121724 /*
121725 ** Add all WhereLoop objects for all tables
121726 */
121727 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
121728   WhereInfo *pWInfo = pBuilder->pWInfo;
121729   Bitmask mExtra = 0;
121730   Bitmask mPrior = 0;
121731   int iTab;
121732   SrcList *pTabList = pWInfo->pTabList;
121733   struct SrcList_item *pItem;
121734   sqlite3 *db = pWInfo->pParse->db;
121735   int nTabList = pWInfo->nLevel;
121736   int rc = SQLITE_OK;
121737   u8 priorJoinType = 0;
121738   WhereLoop *pNew;
121739 
121740   /* Loop over the tables in the join, from left to right */
121741   pNew = pBuilder->pNew;
121742   whereLoopInit(pNew);
121743   for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
121744     pNew->iTab = iTab;
121745     pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
121746     if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
121747       mExtra = mPrior;
121748     }
121749     priorJoinType = pItem->jointype;
121750     if( IsVirtual(pItem->pTab) ){
121751       rc = whereLoopAddVirtual(pBuilder, mExtra);
121752     }else{
121753       rc = whereLoopAddBtree(pBuilder, mExtra);
121754     }
121755     if( rc==SQLITE_OK ){
121756       rc = whereLoopAddOr(pBuilder, mExtra);
121757     }
121758     mPrior |= pNew->maskSelf;
121759     if( rc || db->mallocFailed ) break;
121760   }
121761   whereLoopClear(db, pNew);
121762   return rc;
121763 }
121764 
121765 /*
121766 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
121767 ** parameters) to see if it outputs rows in the requested ORDER BY
121768 ** (or GROUP BY) without requiring a separate sort operation.  Return N:
121769 **
121770 **   N>0:   N terms of the ORDER BY clause are satisfied
121771 **   N==0:  No terms of the ORDER BY clause are satisfied
121772 **   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
121773 **
121774 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
121775 ** strict.  With GROUP BY and DISTINCT the only requirement is that
121776 ** equivalent rows appear immediately adjacent to one another.  GROUP BY
121777 ** and DISTINCT do not require rows to appear in any particular order as long
121778 ** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
121779 ** the pOrderBy terms can be matched in any order.  With ORDER BY, the
121780 ** pOrderBy terms must be matched in strict left-to-right order.
121781 */
121782 static i8 wherePathSatisfiesOrderBy(
121783   WhereInfo *pWInfo,    /* The WHERE clause */
121784   ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
121785   WherePath *pPath,     /* The WherePath to check */
121786   u16 wctrlFlags,       /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
121787   u16 nLoop,            /* Number of entries in pPath->aLoop[] */
121788   WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
121789   Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
121790 ){
121791   u8 revSet;            /* True if rev is known */
121792   u8 rev;               /* Composite sort order */
121793   u8 revIdx;            /* Index sort order */
121794   u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
121795   u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
121796   u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
121797   u16 nKeyCol;          /* Number of key columns in pIndex */
121798   u16 nColumn;          /* Total number of ordered columns in the index */
121799   u16 nOrderBy;         /* Number terms in the ORDER BY clause */
121800   int iLoop;            /* Index of WhereLoop in pPath being processed */
121801   int i, j;             /* Loop counters */
121802   int iCur;             /* Cursor number for current WhereLoop */
121803   int iColumn;          /* A column number within table iCur */
121804   WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
121805   WhereTerm *pTerm;     /* A single term of the WHERE clause */
121806   Expr *pOBExpr;        /* An expression from the ORDER BY clause */
121807   CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
121808   Index *pIndex;        /* The index associated with pLoop */
121809   sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
121810   Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
121811   Bitmask obDone;       /* Mask of all ORDER BY terms */
121812   Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
121813   Bitmask ready;              /* Mask of inner loops */
121814 
121815   /*
121816   ** We say the WhereLoop is "one-row" if it generates no more than one
121817   ** row of output.  A WhereLoop is one-row if all of the following are true:
121818   **  (a) All index columns match with WHERE_COLUMN_EQ.
121819   **  (b) The index is unique
121820   ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
121821   ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
121822   **
121823   ** We say the WhereLoop is "order-distinct" if the set of columns from
121824   ** that WhereLoop that are in the ORDER BY clause are different for every
121825   ** row of the WhereLoop.  Every one-row WhereLoop is automatically
121826   ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
121827   ** is not order-distinct. To be order-distinct is not quite the same as being
121828   ** UNIQUE since a UNIQUE column or index can have multiple rows that
121829   ** are NULL and NULL values are equivalent for the purpose of order-distinct.
121830   ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
121831   **
121832   ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
121833   ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
121834   ** automatically order-distinct.
121835   */
121836 
121837   assert( pOrderBy!=0 );
121838   if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
121839 
121840   nOrderBy = pOrderBy->nExpr;
121841   testcase( nOrderBy==BMS-1 );
121842   if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
121843   isOrderDistinct = 1;
121844   obDone = MASKBIT(nOrderBy)-1;
121845   orderDistinctMask = 0;
121846   ready = 0;
121847   for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
121848     if( iLoop>0 ) ready |= pLoop->maskSelf;
121849     pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
121850     if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
121851       if( pLoop->u.vtab.isOrdered ) obSat = obDone;
121852       break;
121853     }
121854     iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
121855 
121856     /* Mark off any ORDER BY term X that is a column in the table of
121857     ** the current loop for which there is term in the WHERE
121858     ** clause of the form X IS NULL or X=? that reference only outer
121859     ** loops.
121860     */
121861     for(i=0; i<nOrderBy; i++){
121862       if( MASKBIT(i) & obSat ) continue;
121863       pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
121864       if( pOBExpr->op!=TK_COLUMN ) continue;
121865       if( pOBExpr->iTable!=iCur ) continue;
121866       pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
121867                        ~ready, WO_EQ|WO_ISNULL, 0);
121868       if( pTerm==0 ) continue;
121869       if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
121870         const char *z1, *z2;
121871         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
121872         if( !pColl ) pColl = db->pDfltColl;
121873         z1 = pColl->zName;
121874         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
121875         if( !pColl ) pColl = db->pDfltColl;
121876         z2 = pColl->zName;
121877         if( sqlite3StrICmp(z1, z2)!=0 ) continue;
121878       }
121879       obSat |= MASKBIT(i);
121880     }
121881 
121882     if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
121883       if( pLoop->wsFlags & WHERE_IPK ){
121884         pIndex = 0;
121885         nKeyCol = 0;
121886         nColumn = 1;
121887       }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
121888         return 0;
121889       }else{
121890         nKeyCol = pIndex->nKeyCol;
121891         nColumn = pIndex->nColumn;
121892         assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
121893         assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
121894         isOrderDistinct = IsUniqueIndex(pIndex);
121895       }
121896 
121897       /* Loop through all columns of the index and deal with the ones
121898       ** that are not constrained by == or IN.
121899       */
121900       rev = revSet = 0;
121901       distinctColumns = 0;
121902       for(j=0; j<nColumn; j++){
121903         u8 bOnce;   /* True to run the ORDER BY search loop */
121904 
121905         /* Skip over == and IS NULL terms */
121906         if( j<pLoop->u.btree.nEq
121907          && pLoop->nSkip==0
121908          && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
121909         ){
121910           if( i & WO_ISNULL ){
121911             testcase( isOrderDistinct );
121912             isOrderDistinct = 0;
121913           }
121914           continue;
121915         }
121916 
121917         /* Get the column number in the table (iColumn) and sort order
121918         ** (revIdx) for the j-th column of the index.
121919         */
121920         if( pIndex ){
121921           iColumn = pIndex->aiColumn[j];
121922           revIdx = pIndex->aSortOrder[j];
121923           if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
121924         }else{
121925           iColumn = -1;
121926           revIdx = 0;
121927         }
121928 
121929         /* An unconstrained column that might be NULL means that this
121930         ** WhereLoop is not well-ordered
121931         */
121932         if( isOrderDistinct
121933          && iColumn>=0
121934          && j>=pLoop->u.btree.nEq
121935          && pIndex->pTable->aCol[iColumn].notNull==0
121936         ){
121937           isOrderDistinct = 0;
121938         }
121939 
121940         /* Find the ORDER BY term that corresponds to the j-th column
121941         ** of the index and mark that ORDER BY term off
121942         */
121943         bOnce = 1;
121944         isMatch = 0;
121945         for(i=0; bOnce && i<nOrderBy; i++){
121946           if( MASKBIT(i) & obSat ) continue;
121947           pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
121948           testcase( wctrlFlags & WHERE_GROUPBY );
121949           testcase( wctrlFlags & WHERE_DISTINCTBY );
121950           if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
121951           if( pOBExpr->op!=TK_COLUMN ) continue;
121952           if( pOBExpr->iTable!=iCur ) continue;
121953           if( pOBExpr->iColumn!=iColumn ) continue;
121954           if( iColumn>=0 ){
121955             pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
121956             if( !pColl ) pColl = db->pDfltColl;
121957             if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
121958           }
121959           isMatch = 1;
121960           break;
121961         }
121962         if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
121963           /* Make sure the sort order is compatible in an ORDER BY clause.
121964           ** Sort order is irrelevant for a GROUP BY clause. */
121965           if( revSet ){
121966             if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
121967           }else{
121968             rev = revIdx ^ pOrderBy->a[i].sortOrder;
121969             if( rev ) *pRevMask |= MASKBIT(iLoop);
121970             revSet = 1;
121971           }
121972         }
121973         if( isMatch ){
121974           if( iColumn<0 ){
121975             testcase( distinctColumns==0 );
121976             distinctColumns = 1;
121977           }
121978           obSat |= MASKBIT(i);
121979         }else{
121980           /* No match found */
121981           if( j==0 || j<nKeyCol ){
121982             testcase( isOrderDistinct!=0 );
121983             isOrderDistinct = 0;
121984           }
121985           break;
121986         }
121987       } /* end Loop over all index columns */
121988       if( distinctColumns ){
121989         testcase( isOrderDistinct==0 );
121990         isOrderDistinct = 1;
121991       }
121992     } /* end-if not one-row */
121993 
121994     /* Mark off any other ORDER BY terms that reference pLoop */
121995     if( isOrderDistinct ){
121996       orderDistinctMask |= pLoop->maskSelf;
121997       for(i=0; i<nOrderBy; i++){
121998         Expr *p;
121999         Bitmask mTerm;
122000         if( MASKBIT(i) & obSat ) continue;
122001         p = pOrderBy->a[i].pExpr;
122002         mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
122003         if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
122004         if( (mTerm&~orderDistinctMask)==0 ){
122005           obSat |= MASKBIT(i);
122006         }
122007       }
122008     }
122009   } /* End the loop over all WhereLoops from outer-most down to inner-most */
122010   if( obSat==obDone ) return (i8)nOrderBy;
122011   if( !isOrderDistinct ){
122012     for(i=nOrderBy-1; i>0; i--){
122013       Bitmask m = MASKBIT(i) - 1;
122014       if( (obSat&m)==m ) return i;
122015     }
122016     return 0;
122017   }
122018   return -1;
122019 }
122020 
122021 
122022 /*
122023 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
122024 ** the planner assumes that the specified pOrderBy list is actually a GROUP
122025 ** BY clause - and so any order that groups rows as required satisfies the
122026 ** request.
122027 **
122028 ** Normally, in this case it is not possible for the caller to determine
122029 ** whether or not the rows are really being delivered in sorted order, or
122030 ** just in some other order that provides the required grouping. However,
122031 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
122032 ** this function may be called on the returned WhereInfo object. It returns
122033 ** true if the rows really will be sorted in the specified order, or false
122034 ** otherwise.
122035 **
122036 ** For example, assuming:
122037 **
122038 **   CREATE INDEX i1 ON t1(x, Y);
122039 **
122040 ** then
122041 **
122042 **   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
122043 **   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
122044 */
122045 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
122046   assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
122047   assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
122048   return pWInfo->sorted;
122049 }
122050 
122051 #ifdef WHERETRACE_ENABLED
122052 /* For debugging use only: */
122053 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
122054   static char zName[65];
122055   int i;
122056   for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
122057   if( pLast ) zName[i++] = pLast->cId;
122058   zName[i] = 0;
122059   return zName;
122060 }
122061 #endif
122062 
122063 /*
122064 ** Return the cost of sorting nRow rows, assuming that the keys have
122065 ** nOrderby columns and that the first nSorted columns are already in
122066 ** order.
122067 */
122068 static LogEst whereSortingCost(
122069   WhereInfo *pWInfo,
122070   LogEst nRow,
122071   int nOrderBy,
122072   int nSorted
122073 ){
122074   /* TUNING: Estimated cost of a full external sort, where N is
122075   ** the number of rows to sort is:
122076   **
122077   **   cost = (3.0 * N * log(N)).
122078   **
122079   ** Or, if the order-by clause has X terms but only the last Y
122080   ** terms are out of order, then block-sorting will reduce the
122081   ** sorting cost to:
122082   **
122083   **   cost = (3.0 * N * log(N)) * (Y/X)
122084   **
122085   ** The (Y/X) term is implemented using stack variable rScale
122086   ** below.  */
122087   LogEst rScale, rSortCost;
122088   assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
122089   rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
122090   rSortCost = nRow + estLog(nRow) + rScale + 16;
122091 
122092   /* TUNING: The cost of implementing DISTINCT using a B-TREE is
122093   ** similar but with a larger constant of proportionality.
122094   ** Multiply by an additional factor of 3.0.  */
122095   if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
122096     rSortCost += 16;
122097   }
122098 
122099   return rSortCost;
122100 }
122101 
122102 /*
122103 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
122104 ** attempts to find the lowest cost path that visits each WhereLoop
122105 ** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
122106 **
122107 ** Assume that the total number of output rows that will need to be sorted
122108 ** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
122109 ** costs if nRowEst==0.
122110 **
122111 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
122112 ** error occurs.
122113 */
122114 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
122115   int mxChoice;             /* Maximum number of simultaneous paths tracked */
122116   int nLoop;                /* Number of terms in the join */
122117   Parse *pParse;            /* Parsing context */
122118   sqlite3 *db;              /* The database connection */
122119   int iLoop;                /* Loop counter over the terms of the join */
122120   int ii, jj;               /* Loop counters */
122121   int mxI = 0;              /* Index of next entry to replace */
122122   int nOrderBy;             /* Number of ORDER BY clause terms */
122123   LogEst mxCost = 0;        /* Maximum cost of a set of paths */
122124   LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
122125   int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
122126   WherePath *aFrom;         /* All nFrom paths at the previous level */
122127   WherePath *aTo;           /* The nTo best paths at the current level */
122128   WherePath *pFrom;         /* An element of aFrom[] that we are working on */
122129   WherePath *pTo;           /* An element of aTo[] that we are working on */
122130   WhereLoop *pWLoop;        /* One of the WhereLoop objects */
122131   WhereLoop **pX;           /* Used to divy up the pSpace memory */
122132   LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
122133   char *pSpace;             /* Temporary memory used by this routine */
122134   int nSpace;               /* Bytes of space allocated at pSpace */
122135 
122136   pParse = pWInfo->pParse;
122137   db = pParse->db;
122138   nLoop = pWInfo->nLevel;
122139   /* TUNING: For simple queries, only the best path is tracked.
122140   ** For 2-way joins, the 5 best paths are followed.
122141   ** For joins of 3 or more tables, track the 10 best paths */
122142   mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
122143   assert( nLoop<=pWInfo->pTabList->nSrc );
122144   WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
122145 
122146   /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
122147   ** case the purpose of this call is to estimate the number of rows returned
122148   ** by the overall query. Once this estimate has been obtained, the caller
122149   ** will invoke this function a second time, passing the estimate as the
122150   ** nRowEst parameter.  */
122151   if( pWInfo->pOrderBy==0 || nRowEst==0 ){
122152     nOrderBy = 0;
122153   }else{
122154     nOrderBy = pWInfo->pOrderBy->nExpr;
122155   }
122156 
122157   /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
122158   nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
122159   nSpace += sizeof(LogEst) * nOrderBy;
122160   pSpace = sqlite3DbMallocRaw(db, nSpace);
122161   if( pSpace==0 ) return SQLITE_NOMEM;
122162   aTo = (WherePath*)pSpace;
122163   aFrom = aTo+mxChoice;
122164   memset(aFrom, 0, sizeof(aFrom[0]));
122165   pX = (WhereLoop**)(aFrom+mxChoice);
122166   for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
122167     pFrom->aLoop = pX;
122168   }
122169   if( nOrderBy ){
122170     /* If there is an ORDER BY clause and it is not being ignored, set up
122171     ** space for the aSortCost[] array. Each element of the aSortCost array
122172     ** is either zero - meaning it has not yet been initialized - or the
122173     ** cost of sorting nRowEst rows of data where the first X terms of
122174     ** the ORDER BY clause are already in order, where X is the array
122175     ** index.  */
122176     aSortCost = (LogEst*)pX;
122177     memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
122178   }
122179   assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
122180   assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
122181 
122182   /* Seed the search with a single WherePath containing zero WhereLoops.
122183   **
122184   ** TUNING: Do not let the number of iterations go above 28.  If the cost
122185   ** of computing an automatic index is not paid back within the first 28
122186   ** rows, then do not use the automatic index. */
122187   aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );
122188   nFrom = 1;
122189   assert( aFrom[0].isOrdered==0 );
122190   if( nOrderBy ){
122191     /* If nLoop is zero, then there are no FROM terms in the query. Since
122192     ** in this case the query may return a maximum of one row, the results
122193     ** are already in the requested order. Set isOrdered to nOrderBy to
122194     ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
122195     ** -1, indicating that the result set may or may not be ordered,
122196     ** depending on the loops added to the current plan.  */
122197     aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
122198   }
122199 
122200   /* Compute successively longer WherePaths using the previous generation
122201   ** of WherePaths as the basis for the next.  Keep track of the mxChoice
122202   ** best paths at each generation */
122203   for(iLoop=0; iLoop<nLoop; iLoop++){
122204     nTo = 0;
122205     for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
122206       for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
122207         LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
122208         LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
122209         LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
122210         i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
122211         Bitmask maskNew;                  /* Mask of src visited by (..) */
122212         Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
122213 
122214         if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
122215         if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
122216         /* At this point, pWLoop is a candidate to be the next loop.
122217         ** Compute its cost */
122218         rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
122219         rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
122220         nOut = pFrom->nRow + pWLoop->nOut;
122221         maskNew = pFrom->maskLoop | pWLoop->maskSelf;
122222         if( isOrdered<0 ){
122223           isOrdered = wherePathSatisfiesOrderBy(pWInfo,
122224                        pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
122225                        iLoop, pWLoop, &revMask);
122226         }else{
122227           revMask = pFrom->revLoop;
122228         }
122229         if( isOrdered>=0 && isOrdered<nOrderBy ){
122230           if( aSortCost[isOrdered]==0 ){
122231             aSortCost[isOrdered] = whereSortingCost(
122232                 pWInfo, nRowEst, nOrderBy, isOrdered
122233             );
122234           }
122235           rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
122236 
122237           WHERETRACE(0x002,
122238               ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
122239                aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
122240                rUnsorted, rCost));
122241         }else{
122242           rCost = rUnsorted;
122243         }
122244 
122245         /* Check to see if pWLoop should be added to the set of
122246         ** mxChoice best-so-far paths.
122247         **
122248         ** First look for an existing path among best-so-far paths
122249         ** that covers the same set of loops and has the same isOrdered
122250         ** setting as the current path candidate.
122251         **
122252         ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
122253         ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
122254         ** of legal values for isOrdered, -1..64.
122255         */
122256         for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
122257           if( pTo->maskLoop==maskNew
122258            && ((pTo->isOrdered^isOrdered)&0x80)==0
122259           ){
122260             testcase( jj==nTo-1 );
122261             break;
122262           }
122263         }
122264         if( jj>=nTo ){
122265           /* None of the existing best-so-far paths match the candidate. */
122266           if( nTo>=mxChoice
122267            && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
122268           ){
122269             /* The current candidate is no better than any of the mxChoice
122270             ** paths currently in the best-so-far buffer.  So discard
122271             ** this candidate as not viable. */
122272 #ifdef WHERETRACE_ENABLED /* 0x4 */
122273             if( sqlite3WhereTrace&0x4 ){
122274               sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
122275                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
122276                   isOrdered>=0 ? isOrdered+'0' : '?');
122277             }
122278 #endif
122279             continue;
122280           }
122281           /* If we reach this points it means that the new candidate path
122282           ** needs to be added to the set of best-so-far paths. */
122283           if( nTo<mxChoice ){
122284             /* Increase the size of the aTo set by one */
122285             jj = nTo++;
122286           }else{
122287             /* New path replaces the prior worst to keep count below mxChoice */
122288             jj = mxI;
122289           }
122290           pTo = &aTo[jj];
122291 #ifdef WHERETRACE_ENABLED /* 0x4 */
122292           if( sqlite3WhereTrace&0x4 ){
122293             sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
122294                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
122295                 isOrdered>=0 ? isOrdered+'0' : '?');
122296           }
122297 #endif
122298         }else{
122299           /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
122300           ** same set of loops and has the sam isOrdered setting as the
122301           ** candidate path.  Check to see if the candidate should replace
122302           ** pTo or if the candidate should be skipped */
122303           if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
122304 #ifdef WHERETRACE_ENABLED /* 0x4 */
122305             if( sqlite3WhereTrace&0x4 ){
122306               sqlite3DebugPrintf(
122307                   "Skip   %s cost=%-3d,%3d order=%c",
122308                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
122309                   isOrdered>=0 ? isOrdered+'0' : '?');
122310               sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
122311                   wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
122312                   pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
122313             }
122314 #endif
122315             /* Discard the candidate path from further consideration */
122316             testcase( pTo->rCost==rCost );
122317             continue;
122318           }
122319           testcase( pTo->rCost==rCost+1 );
122320           /* Control reaches here if the candidate path is better than the
122321           ** pTo path.  Replace pTo with the candidate. */
122322 #ifdef WHERETRACE_ENABLED /* 0x4 */
122323           if( sqlite3WhereTrace&0x4 ){
122324             sqlite3DebugPrintf(
122325                 "Update %s cost=%-3d,%3d order=%c",
122326                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
122327                 isOrdered>=0 ? isOrdered+'0' : '?');
122328             sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
122329                 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
122330                 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
122331           }
122332 #endif
122333         }
122334         /* pWLoop is a winner.  Add it to the set of best so far */
122335         pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
122336         pTo->revLoop = revMask;
122337         pTo->nRow = nOut;
122338         pTo->rCost = rCost;
122339         pTo->rUnsorted = rUnsorted;
122340         pTo->isOrdered = isOrdered;
122341         memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
122342         pTo->aLoop[iLoop] = pWLoop;
122343         if( nTo>=mxChoice ){
122344           mxI = 0;
122345           mxCost = aTo[0].rCost;
122346           mxUnsorted = aTo[0].nRow;
122347           for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
122348             if( pTo->rCost>mxCost
122349              || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
122350             ){
122351               mxCost = pTo->rCost;
122352               mxUnsorted = pTo->rUnsorted;
122353               mxI = jj;
122354             }
122355           }
122356         }
122357       }
122358     }
122359 
122360 #ifdef WHERETRACE_ENABLED  /* >=2 */
122361     if( sqlite3WhereTrace & 0x02 ){
122362       sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
122363       for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
122364         sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
122365            wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
122366            pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
122367         if( pTo->isOrdered>0 ){
122368           sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
122369         }else{
122370           sqlite3DebugPrintf("\n");
122371         }
122372       }
122373     }
122374 #endif
122375 
122376     /* Swap the roles of aFrom and aTo for the next generation */
122377     pFrom = aTo;
122378     aTo = aFrom;
122379     aFrom = pFrom;
122380     nFrom = nTo;
122381   }
122382 
122383   if( nFrom==0 ){
122384     sqlite3ErrorMsg(pParse, "no query solution");
122385     sqlite3DbFree(db, pSpace);
122386     return SQLITE_ERROR;
122387   }
122388 
122389   /* Find the lowest cost path.  pFrom will be left pointing to that path */
122390   pFrom = aFrom;
122391   for(ii=1; ii<nFrom; ii++){
122392     if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
122393   }
122394   assert( pWInfo->nLevel==nLoop );
122395   /* Load the lowest cost path into pWInfo */
122396   for(iLoop=0; iLoop<nLoop; iLoop++){
122397     WhereLevel *pLevel = pWInfo->a + iLoop;
122398     pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
122399     pLevel->iFrom = pWLoop->iTab;
122400     pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
122401   }
122402   if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
122403    && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
122404    && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
122405    && nRowEst
122406   ){
122407     Bitmask notUsed;
122408     int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
122409                  WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
122410     if( rc==pWInfo->pResultSet->nExpr ){
122411       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
122412     }
122413   }
122414   if( pWInfo->pOrderBy ){
122415     if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
122416       if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
122417         pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
122418       }
122419     }else{
122420       pWInfo->nOBSat = pFrom->isOrdered;
122421       if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
122422       pWInfo->revMask = pFrom->revLoop;
122423     }
122424     if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
122425         && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
122426     ){
122427       Bitmask revMask = 0;
122428       int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
122429           pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
122430       );
122431       assert( pWInfo->sorted==0 );
122432       if( nOrder==pWInfo->pOrderBy->nExpr ){
122433         pWInfo->sorted = 1;
122434         pWInfo->revMask = revMask;
122435       }
122436     }
122437   }
122438 
122439 
122440   pWInfo->nRowOut = pFrom->nRow;
122441 
122442   /* Free temporary memory and return success */
122443   sqlite3DbFree(db, pSpace);
122444   return SQLITE_OK;
122445 }
122446 
122447 /*
122448 ** Most queries use only a single table (they are not joins) and have
122449 ** simple == constraints against indexed fields.  This routine attempts
122450 ** to plan those simple cases using much less ceremony than the
122451 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
122452 ** times for the common case.
122453 **
122454 ** Return non-zero on success, if this query can be handled by this
122455 ** no-frills query planner.  Return zero if this query needs the
122456 ** general-purpose query planner.
122457 */
122458 static int whereShortCut(WhereLoopBuilder *pBuilder){
122459   WhereInfo *pWInfo;
122460   struct SrcList_item *pItem;
122461   WhereClause *pWC;
122462   WhereTerm *pTerm;
122463   WhereLoop *pLoop;
122464   int iCur;
122465   int j;
122466   Table *pTab;
122467   Index *pIdx;
122468 
122469   pWInfo = pBuilder->pWInfo;
122470   if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
122471   assert( pWInfo->pTabList->nSrc>=1 );
122472   pItem = pWInfo->pTabList->a;
122473   pTab = pItem->pTab;
122474   if( IsVirtual(pTab) ) return 0;
122475   if( pItem->zIndex ) return 0;
122476   iCur = pItem->iCursor;
122477   pWC = &pWInfo->sWC;
122478   pLoop = pBuilder->pNew;
122479   pLoop->wsFlags = 0;
122480   pLoop->nSkip = 0;
122481   pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
122482   if( pTerm ){
122483     pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
122484     pLoop->aLTerm[0] = pTerm;
122485     pLoop->nLTerm = 1;
122486     pLoop->u.btree.nEq = 1;
122487     /* TUNING: Cost of a rowid lookup is 10 */
122488     pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
122489   }else{
122490     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
122491       assert( pLoop->aLTermSpace==pLoop->aLTerm );
122492       if( !IsUniqueIndex(pIdx)
122493        || pIdx->pPartIdxWhere!=0
122494        || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
122495       ) continue;
122496       for(j=0; j<pIdx->nKeyCol; j++){
122497         pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
122498         if( pTerm==0 ) break;
122499         pLoop->aLTerm[j] = pTerm;
122500       }
122501       if( j!=pIdx->nKeyCol ) continue;
122502       pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
122503       if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
122504         pLoop->wsFlags |= WHERE_IDX_ONLY;
122505       }
122506       pLoop->nLTerm = j;
122507       pLoop->u.btree.nEq = j;
122508       pLoop->u.btree.pIndex = pIdx;
122509       /* TUNING: Cost of a unique index lookup is 15 */
122510       pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
122511       break;
122512     }
122513   }
122514   if( pLoop->wsFlags ){
122515     pLoop->nOut = (LogEst)1;
122516     pWInfo->a[0].pWLoop = pLoop;
122517     pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
122518     pWInfo->a[0].iTabCur = iCur;
122519     pWInfo->nRowOut = 1;
122520     if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
122521     if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
122522       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
122523     }
122524 #ifdef SQLITE_DEBUG
122525     pLoop->cId = '0';
122526 #endif
122527     return 1;
122528   }
122529   return 0;
122530 }
122531 
122532 /*
122533 ** Generate the beginning of the loop used for WHERE clause processing.
122534 ** The return value is a pointer to an opaque structure that contains
122535 ** information needed to terminate the loop.  Later, the calling routine
122536 ** should invoke sqlite3WhereEnd() with the return value of this function
122537 ** in order to complete the WHERE clause processing.
122538 **
122539 ** If an error occurs, this routine returns NULL.
122540 **
122541 ** The basic idea is to do a nested loop, one loop for each table in
122542 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
122543 ** same as a SELECT with only a single table in the FROM clause.)  For
122544 ** example, if the SQL is this:
122545 **
122546 **       SELECT * FROM t1, t2, t3 WHERE ...;
122547 **
122548 ** Then the code generated is conceptually like the following:
122549 **
122550 **      foreach row1 in t1 do       \    Code generated
122551 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
122552 **          foreach row3 in t3 do   /
122553 **            ...
122554 **          end                     \    Code generated
122555 **        end                        |-- by sqlite3WhereEnd()
122556 **      end                         /
122557 **
122558 ** Note that the loops might not be nested in the order in which they
122559 ** appear in the FROM clause if a different order is better able to make
122560 ** use of indices.  Note also that when the IN operator appears in
122561 ** the WHERE clause, it might result in additional nested loops for
122562 ** scanning through all values on the right-hand side of the IN.
122563 **
122564 ** There are Btree cursors associated with each table.  t1 uses cursor
122565 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
122566 ** And so forth.  This routine generates code to open those VDBE cursors
122567 ** and sqlite3WhereEnd() generates the code to close them.
122568 **
122569 ** The code that sqlite3WhereBegin() generates leaves the cursors named
122570 ** in pTabList pointing at their appropriate entries.  The [...] code
122571 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
122572 ** data from the various tables of the loop.
122573 **
122574 ** If the WHERE clause is empty, the foreach loops must each scan their
122575 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
122576 ** the tables have indices and there are terms in the WHERE clause that
122577 ** refer to those indices, a complete table scan can be avoided and the
122578 ** code will run much faster.  Most of the work of this routine is checking
122579 ** to see if there are indices that can be used to speed up the loop.
122580 **
122581 ** Terms of the WHERE clause are also used to limit which rows actually
122582 ** make it to the "..." in the middle of the loop.  After each "foreach",
122583 ** terms of the WHERE clause that use only terms in that loop and outer
122584 ** loops are evaluated and if false a jump is made around all subsequent
122585 ** inner loops (or around the "..." if the test occurs within the inner-
122586 ** most loop)
122587 **
122588 ** OUTER JOINS
122589 **
122590 ** An outer join of tables t1 and t2 is conceptally coded as follows:
122591 **
122592 **    foreach row1 in t1 do
122593 **      flag = 0
122594 **      foreach row2 in t2 do
122595 **        start:
122596 **          ...
122597 **          flag = 1
122598 **      end
122599 **      if flag==0 then
122600 **        move the row2 cursor to a null row
122601 **        goto start
122602 **      fi
122603 **    end
122604 **
122605 ** ORDER BY CLAUSE PROCESSING
122606 **
122607 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
122608 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
122609 ** if there is one.  If there is no ORDER BY clause or if this routine
122610 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
122611 **
122612 ** The iIdxCur parameter is the cursor number of an index.  If
122613 ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
122614 ** to use for OR clause processing.  The WHERE clause should use this
122615 ** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
122616 ** the first cursor in an array of cursors for all indices.  iIdxCur should
122617 ** be used to compute the appropriate cursor depending on which index is
122618 ** used.
122619 */
122620 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
122621   Parse *pParse,        /* The parser context */
122622   SrcList *pTabList,    /* FROM clause: A list of all tables to be scanned */
122623   Expr *pWhere,         /* The WHERE clause */
122624   ExprList *pOrderBy,   /* An ORDER BY (or GROUP BY) clause, or NULL */
122625   ExprList *pResultSet, /* Result set of the query */
122626   u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
122627   int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
122628 ){
122629   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
122630   int nTabList;              /* Number of elements in pTabList */
122631   WhereInfo *pWInfo;         /* Will become the return value of this function */
122632   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
122633   Bitmask notReady;          /* Cursors that are not yet positioned */
122634   WhereLoopBuilder sWLB;     /* The WhereLoop builder */
122635   WhereMaskSet *pMaskSet;    /* The expression mask set */
122636   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
122637   WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
122638   int ii;                    /* Loop counter */
122639   sqlite3 *db;               /* Database connection */
122640   int rc;                    /* Return code */
122641 
122642 
122643   /* Variable initialization */
122644   db = pParse->db;
122645   memset(&sWLB, 0, sizeof(sWLB));
122646 
122647   /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
122648   testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
122649   if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
122650   sWLB.pOrderBy = pOrderBy;
122651 
122652   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
122653   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
122654   if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
122655     wctrlFlags &= ~WHERE_WANT_DISTINCT;
122656   }
122657 
122658   /* The number of tables in the FROM clause is limited by the number of
122659   ** bits in a Bitmask
122660   */
122661   testcase( pTabList->nSrc==BMS );
122662   if( pTabList->nSrc>BMS ){
122663     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
122664     return 0;
122665   }
122666 
122667   /* This function normally generates a nested loop for all tables in
122668   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
122669   ** only generate code for the first table in pTabList and assume that
122670   ** any cursors associated with subsequent tables are uninitialized.
122671   */
122672   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
122673 
122674   /* Allocate and initialize the WhereInfo structure that will become the
122675   ** return value. A single allocation is used to store the WhereInfo
122676   ** struct, the contents of WhereInfo.a[], the WhereClause structure
122677   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
122678   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
122679   ** some architectures. Hence the ROUND8() below.
122680   */
122681   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
122682   pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
122683   if( db->mallocFailed ){
122684     sqlite3DbFree(db, pWInfo);
122685     pWInfo = 0;
122686     goto whereBeginError;
122687   }
122688   pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
122689   pWInfo->nLevel = nTabList;
122690   pWInfo->pParse = pParse;
122691   pWInfo->pTabList = pTabList;
122692   pWInfo->pOrderBy = pOrderBy;
122693   pWInfo->pResultSet = pResultSet;
122694   pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
122695   pWInfo->wctrlFlags = wctrlFlags;
122696   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
122697   pMaskSet = &pWInfo->sMaskSet;
122698   sWLB.pWInfo = pWInfo;
122699   sWLB.pWC = &pWInfo->sWC;
122700   sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
122701   assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
122702   whereLoopInit(sWLB.pNew);
122703 #ifdef SQLITE_DEBUG
122704   sWLB.pNew->cId = '*';
122705 #endif
122706 
122707   /* Split the WHERE clause into separate subexpressions where each
122708   ** subexpression is separated by an AND operator.
122709   */
122710   initMaskSet(pMaskSet);
122711   whereClauseInit(&pWInfo->sWC, pWInfo);
122712   whereSplit(&pWInfo->sWC, pWhere, TK_AND);
122713 
122714   /* Special case: a WHERE clause that is constant.  Evaluate the
122715   ** expression and either jump over all of the code or fall thru.
122716   */
122717   for(ii=0; ii<sWLB.pWC->nTerm; ii++){
122718     if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
122719       sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
122720                          SQLITE_JUMPIFNULL);
122721       sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
122722     }
122723   }
122724 
122725   /* Special case: No FROM clause
122726   */
122727   if( nTabList==0 ){
122728     if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
122729     if( wctrlFlags & WHERE_WANT_DISTINCT ){
122730       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
122731     }
122732   }
122733 
122734   /* Assign a bit from the bitmask to every term in the FROM clause.
122735   **
122736   ** When assigning bitmask values to FROM clause cursors, it must be
122737   ** the case that if X is the bitmask for the N-th FROM clause term then
122738   ** the bitmask for all FROM clause terms to the left of the N-th term
122739   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
122740   ** its Expr.iRightJoinTable value to find the bitmask of the right table
122741   ** of the join.  Subtracting one from the right table bitmask gives a
122742   ** bitmask for all tables to the left of the join.  Knowing the bitmask
122743   ** for all tables to the left of a left join is important.  Ticket #3015.
122744   **
122745   ** Note that bitmasks are created for all pTabList->nSrc tables in
122746   ** pTabList, not just the first nTabList tables.  nTabList is normally
122747   ** equal to pTabList->nSrc but might be shortened to 1 if the
122748   ** WHERE_ONETABLE_ONLY flag is set.
122749   */
122750   for(ii=0; ii<pTabList->nSrc; ii++){
122751     createMask(pMaskSet, pTabList->a[ii].iCursor);
122752   }
122753 #ifndef NDEBUG
122754   {
122755     Bitmask toTheLeft = 0;
122756     for(ii=0; ii<pTabList->nSrc; ii++){
122757       Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
122758       assert( (m-1)==toTheLeft );
122759       toTheLeft |= m;
122760     }
122761   }
122762 #endif
122763 
122764   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
122765   ** add new virtual terms onto the end of the WHERE clause.  We do not
122766   ** want to analyze these virtual terms, so start analyzing at the end
122767   ** and work forward so that the added virtual terms are never processed.
122768   */
122769   exprAnalyzeAll(pTabList, &pWInfo->sWC);
122770   if( db->mallocFailed ){
122771     goto whereBeginError;
122772   }
122773 
122774   if( wctrlFlags & WHERE_WANT_DISTINCT ){
122775     if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
122776       /* The DISTINCT marking is pointless.  Ignore it. */
122777       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
122778     }else if( pOrderBy==0 ){
122779       /* Try to ORDER BY the result set to make distinct processing easier */
122780       pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
122781       pWInfo->pOrderBy = pResultSet;
122782     }
122783   }
122784 
122785   /* Construct the WhereLoop objects */
122786   WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
122787 #if defined(WHERETRACE_ENABLED)
122788   /* Display all terms of the WHERE clause */
122789   if( sqlite3WhereTrace & 0x100 ){
122790     int i;
122791     for(i=0; i<sWLB.pWC->nTerm; i++){
122792       whereTermPrint(&sWLB.pWC->a[i], i);
122793     }
122794   }
122795 #endif
122796 
122797   if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
122798     rc = whereLoopAddAll(&sWLB);
122799     if( rc ) goto whereBeginError;
122800 
122801     /* Display all of the WhereLoop objects if wheretrace is enabled */
122802 #ifdef WHERETRACE_ENABLED /* !=0 */
122803     if( sqlite3WhereTrace ){
122804       WhereLoop *p;
122805       int i;
122806       static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
122807                                        "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
122808       for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
122809         p->cId = zLabel[i%sizeof(zLabel)];
122810         whereLoopPrint(p, sWLB.pWC);
122811       }
122812     }
122813 #endif
122814 
122815     wherePathSolver(pWInfo, 0);
122816     if( db->mallocFailed ) goto whereBeginError;
122817     if( pWInfo->pOrderBy ){
122818        wherePathSolver(pWInfo, pWInfo->nRowOut+1);
122819        if( db->mallocFailed ) goto whereBeginError;
122820     }
122821   }
122822   if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
122823      pWInfo->revMask = (Bitmask)(-1);
122824   }
122825   if( pParse->nErr || NEVER(db->mallocFailed) ){
122826     goto whereBeginError;
122827   }
122828 #ifdef WHERETRACE_ENABLED /* !=0 */
122829   if( sqlite3WhereTrace ){
122830     sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
122831     if( pWInfo->nOBSat>0 ){
122832       sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
122833     }
122834     switch( pWInfo->eDistinct ){
122835       case WHERE_DISTINCT_UNIQUE: {
122836         sqlite3DebugPrintf("  DISTINCT=unique");
122837         break;
122838       }
122839       case WHERE_DISTINCT_ORDERED: {
122840         sqlite3DebugPrintf("  DISTINCT=ordered");
122841         break;
122842       }
122843       case WHERE_DISTINCT_UNORDERED: {
122844         sqlite3DebugPrintf("  DISTINCT=unordered");
122845         break;
122846       }
122847     }
122848     sqlite3DebugPrintf("\n");
122849     for(ii=0; ii<pWInfo->nLevel; ii++){
122850       whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
122851     }
122852   }
122853 #endif
122854   /* Attempt to omit tables from the join that do not effect the result */
122855   if( pWInfo->nLevel>=2
122856    && pResultSet!=0
122857    && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
122858   ){
122859     Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
122860     if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
122861     while( pWInfo->nLevel>=2 ){
122862       WhereTerm *pTerm, *pEnd;
122863       pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
122864       if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
122865       if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
122866        && (pLoop->wsFlags & WHERE_ONEROW)==0
122867       ){
122868         break;
122869       }
122870       if( (tabUsed & pLoop->maskSelf)!=0 ) break;
122871       pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
122872       for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
122873         if( (pTerm->prereqAll & pLoop->maskSelf)!=0
122874          && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
122875         ){
122876           break;
122877         }
122878       }
122879       if( pTerm<pEnd ) break;
122880       WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
122881       pWInfo->nLevel--;
122882       nTabList--;
122883     }
122884   }
122885   WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
122886   pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
122887 
122888   /* If the caller is an UPDATE or DELETE statement that is requesting
122889   ** to use a one-pass algorithm, determine if this is appropriate.
122890   ** The one-pass algorithm only works if the WHERE clause constrains
122891   ** the statement to update a single row.
122892   */
122893   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
122894   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
122895    && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
122896     pWInfo->okOnePass = 1;
122897     if( HasRowid(pTabList->a[0].pTab) ){
122898       pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
122899     }
122900   }
122901 
122902   /* Open all tables in the pTabList and any indices selected for
122903   ** searching those tables.
122904   */
122905   notReady = ~(Bitmask)0;
122906   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
122907     Table *pTab;     /* Table to open */
122908     int iDb;         /* Index of database containing table/index */
122909     struct SrcList_item *pTabItem;
122910 
122911     pTabItem = &pTabList->a[pLevel->iFrom];
122912     pTab = pTabItem->pTab;
122913     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
122914     pLoop = pLevel->pWLoop;
122915     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
122916       /* Do nothing */
122917     }else
122918 #ifndef SQLITE_OMIT_VIRTUALTABLE
122919     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
122920       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
122921       int iCur = pTabItem->iCursor;
122922       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
122923     }else if( IsVirtual(pTab) ){
122924       /* noop */
122925     }else
122926 #endif
122927     if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
122928          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
122929       int op = OP_OpenRead;
122930       if( pWInfo->okOnePass ){
122931         op = OP_OpenWrite;
122932         pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
122933       };
122934       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
122935       assert( pTabItem->iCursor==pLevel->iTabCur );
122936       testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
122937       testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
122938       if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
122939         Bitmask b = pTabItem->colUsed;
122940         int n = 0;
122941         for(; b; b=b>>1, n++){}
122942         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
122943                             SQLITE_INT_TO_PTR(n), P4_INT32);
122944         assert( n<=pTab->nCol );
122945       }
122946     }else{
122947       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
122948     }
122949     if( pLoop->wsFlags & WHERE_INDEXED ){
122950       Index *pIx = pLoop->u.btree.pIndex;
122951       int iIndexCur;
122952       int op = OP_OpenRead;
122953       /* iIdxCur is always set if to a positive value if ONEPASS is possible */
122954       assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
122955       if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
122956        && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
122957       ){
122958         /* This is one term of an OR-optimization using the PRIMARY KEY of a
122959         ** WITHOUT ROWID table.  No need for a separate index */
122960         iIndexCur = pLevel->iTabCur;
122961         op = 0;
122962       }else if( pWInfo->okOnePass ){
122963         Index *pJ = pTabItem->pTab->pIndex;
122964         iIndexCur = iIdxCur;
122965         assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
122966         while( ALWAYS(pJ) && pJ!=pIx ){
122967           iIndexCur++;
122968           pJ = pJ->pNext;
122969         }
122970         op = OP_OpenWrite;
122971         pWInfo->aiCurOnePass[1] = iIndexCur;
122972       }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
122973         iIndexCur = iIdxCur;
122974         if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
122975       }else{
122976         iIndexCur = pParse->nTab++;
122977       }
122978       pLevel->iIdxCur = iIndexCur;
122979       assert( pIx->pSchema==pTab->pSchema );
122980       assert( iIndexCur>=0 );
122981       if( op ){
122982         sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
122983         sqlite3VdbeSetP4KeyInfo(pParse, pIx);
122984         if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
122985          && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
122986          && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
122987         ){
122988           sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
122989         }
122990         VdbeComment((v, "%s", pIx->zName));
122991       }
122992     }
122993     if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
122994     notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
122995   }
122996   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
122997   if( db->mallocFailed ) goto whereBeginError;
122998 
122999   /* Generate the code to do the search.  Each iteration of the for
123000   ** loop below generates code for a single nested loop of the VM
123001   ** program.
123002   */
123003   notReady = ~(Bitmask)0;
123004   for(ii=0; ii<nTabList; ii++){
123005     int addrExplain;
123006     int wsFlags;
123007     pLevel = &pWInfo->a[ii];
123008     wsFlags = pLevel->pWLoop->wsFlags;
123009 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
123010     if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
123011       constructAutomaticIndex(pParse, &pWInfo->sWC,
123012                 &pTabList->a[pLevel->iFrom], notReady, pLevel);
123013       if( db->mallocFailed ) goto whereBeginError;
123014     }
123015 #endif
123016     addrExplain = explainOneScan(
123017         pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
123018     );
123019     pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
123020     notReady = codeOneLoopStart(pWInfo, ii, notReady);
123021     pWInfo->iContinue = pLevel->addrCont;
123022     if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
123023       addScanStatus(v, pTabList, pLevel, addrExplain);
123024     }
123025   }
123026 
123027   /* Done. */
123028   VdbeModuleComment((v, "Begin WHERE-core"));
123029   return pWInfo;
123030 
123031   /* Jump here if malloc fails */
123032 whereBeginError:
123033   if( pWInfo ){
123034     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
123035     whereInfoFree(db, pWInfo);
123036   }
123037   return 0;
123038 }
123039 
123040 /*
123041 ** Generate the end of the WHERE loop.  See comments on
123042 ** sqlite3WhereBegin() for additional information.
123043 */
123044 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
123045   Parse *pParse = pWInfo->pParse;
123046   Vdbe *v = pParse->pVdbe;
123047   int i;
123048   WhereLevel *pLevel;
123049   WhereLoop *pLoop;
123050   SrcList *pTabList = pWInfo->pTabList;
123051   sqlite3 *db = pParse->db;
123052 
123053   /* Generate loop termination code.
123054   */
123055   VdbeModuleComment((v, "End WHERE-core"));
123056   sqlite3ExprCacheClear(pParse);
123057   for(i=pWInfo->nLevel-1; i>=0; i--){
123058     int addr;
123059     pLevel = &pWInfo->a[i];
123060     pLoop = pLevel->pWLoop;
123061     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
123062     if( pLevel->op!=OP_Noop ){
123063       sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
123064       sqlite3VdbeChangeP5(v, pLevel->p5);
123065       VdbeCoverage(v);
123066       VdbeCoverageIf(v, pLevel->op==OP_Next);
123067       VdbeCoverageIf(v, pLevel->op==OP_Prev);
123068       VdbeCoverageIf(v, pLevel->op==OP_VNext);
123069     }
123070     if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
123071       struct InLoop *pIn;
123072       int j;
123073       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
123074       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
123075         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
123076         sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
123077         VdbeCoverage(v);
123078         VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
123079         VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
123080         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
123081       }
123082     }
123083     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
123084     if( pLevel->addrSkip ){
123085       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
123086       VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
123087       sqlite3VdbeJumpHere(v, pLevel->addrSkip);
123088       sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
123089     }
123090     if( pLevel->addrLikeRep ){
123091       int op;
123092       if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
123093         op = OP_DecrJumpZero;
123094       }else{
123095         op = OP_JumpZeroIncr;
123096       }
123097       sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
123098       VdbeCoverage(v);
123099     }
123100     if( pLevel->iLeftJoin ){
123101       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
123102       assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
123103            || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
123104       if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
123105         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
123106       }
123107       if( pLoop->wsFlags & WHERE_INDEXED ){
123108         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
123109       }
123110       if( pLevel->op==OP_Return ){
123111         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
123112       }else{
123113         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
123114       }
123115       sqlite3VdbeJumpHere(v, addr);
123116     }
123117     VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
123118                      pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
123119   }
123120 
123121   /* The "break" point is here, just past the end of the outer loop.
123122   ** Set it.
123123   */
123124   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
123125 
123126   assert( pWInfo->nLevel<=pTabList->nSrc );
123127   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
123128     int k, last;
123129     VdbeOp *pOp;
123130     Index *pIdx = 0;
123131     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
123132     Table *pTab = pTabItem->pTab;
123133     assert( pTab!=0 );
123134     pLoop = pLevel->pWLoop;
123135 
123136     /* For a co-routine, change all OP_Column references to the table of
123137     ** the co-routine into OP_SCopy of result contained in a register.
123138     ** OP_Rowid becomes OP_Null.
123139     */
123140     if( pTabItem->viaCoroutine && !db->mallocFailed ){
123141       last = sqlite3VdbeCurrentAddr(v);
123142       k = pLevel->addrBody;
123143       pOp = sqlite3VdbeGetOp(v, k);
123144       for(; k<last; k++, pOp++){
123145         if( pOp->p1!=pLevel->iTabCur ) continue;
123146         if( pOp->opcode==OP_Column ){
123147           pOp->opcode = OP_Copy;
123148           pOp->p1 = pOp->p2 + pTabItem->regResult;
123149           pOp->p2 = pOp->p3;
123150           pOp->p3 = 0;
123151         }else if( pOp->opcode==OP_Rowid ){
123152           pOp->opcode = OP_Null;
123153           pOp->p1 = 0;
123154           pOp->p3 = 0;
123155         }
123156       }
123157       continue;
123158     }
123159 
123160     /* Close all of the cursors that were opened by sqlite3WhereBegin.
123161     ** Except, do not close cursors that will be reused by the OR optimization
123162     ** (WHERE_OMIT_OPEN_CLOSE).  And do not close the OP_OpenWrite cursors
123163     ** created for the ONEPASS optimization.
123164     */
123165     if( (pTab->tabFlags & TF_Ephemeral)==0
123166      && pTab->pSelect==0
123167      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
123168     ){
123169       int ws = pLoop->wsFlags;
123170       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
123171         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
123172       }
123173       if( (ws & WHERE_INDEXED)!=0
123174        && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
123175        && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
123176       ){
123177         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
123178       }
123179     }
123180 
123181     /* If this scan uses an index, make VDBE code substitutions to read data
123182     ** from the index instead of from the table where possible.  In some cases
123183     ** this optimization prevents the table from ever being read, which can
123184     ** yield a significant performance boost.
123185     **
123186     ** Calls to the code generator in between sqlite3WhereBegin and
123187     ** sqlite3WhereEnd will have created code that references the table
123188     ** directly.  This loop scans all that code looking for opcodes
123189     ** that reference the table and converts them into opcodes that
123190     ** reference the index.
123191     */
123192     if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
123193       pIdx = pLoop->u.btree.pIndex;
123194     }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
123195       pIdx = pLevel->u.pCovidx;
123196     }
123197     if( pIdx && !db->mallocFailed ){
123198       last = sqlite3VdbeCurrentAddr(v);
123199       k = pLevel->addrBody;
123200       pOp = sqlite3VdbeGetOp(v, k);
123201       for(; k<last; k++, pOp++){
123202         if( pOp->p1!=pLevel->iTabCur ) continue;
123203         if( pOp->opcode==OP_Column ){
123204           int x = pOp->p2;
123205           assert( pIdx->pTable==pTab );
123206           if( !HasRowid(pTab) ){
123207             Index *pPk = sqlite3PrimaryKeyIndex(pTab);
123208             x = pPk->aiColumn[x];
123209           }
123210           x = sqlite3ColumnOfIndex(pIdx, x);
123211           if( x>=0 ){
123212             pOp->p2 = x;
123213             pOp->p1 = pLevel->iIdxCur;
123214           }
123215           assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
123216         }else if( pOp->opcode==OP_Rowid ){
123217           pOp->p1 = pLevel->iIdxCur;
123218           pOp->opcode = OP_IdxRowid;
123219         }
123220       }
123221     }
123222   }
123223 
123224   /* Final cleanup
123225   */
123226   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
123227   whereInfoFree(db, pWInfo);
123228   return;
123229 }
123230 
123231 /************** End of where.c ***********************************************/
123232 /************** Begin file parse.c *******************************************/
123233 /* Driver template for the LEMON parser generator.
123234 ** The author disclaims copyright to this source code.
123235 **
123236 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
123237 ** The only modifications are the addition of a couple of NEVER()
123238 ** macros to disable tests that are needed in the case of a general
123239 ** LALR(1) grammar but which are always false in the
123240 ** specific grammar used by SQLite.
123241 */
123242 /* First off, code is included that follows the "include" declaration
123243 ** in the input grammar file. */
123244 /* #include <stdio.h> */
123245 
123246 
123247 /*
123248 ** Disable all error recovery processing in the parser push-down
123249 ** automaton.
123250 */
123251 #define YYNOERRORRECOVERY 1
123252 
123253 /*
123254 ** Make yytestcase() the same as testcase()
123255 */
123256 #define yytestcase(X) testcase(X)
123257 
123258 /*
123259 ** An instance of this structure holds information about the
123260 ** LIMIT clause of a SELECT statement.
123261 */
123262 struct LimitVal {
123263   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
123264   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
123265 };
123266 
123267 /*
123268 ** An instance of this structure is used to store the LIKE,
123269 ** GLOB, NOT LIKE, and NOT GLOB operators.
123270 */
123271 struct LikeOp {
123272   Token eOperator;  /* "like" or "glob" or "regexp" */
123273   int bNot;         /* True if the NOT keyword is present */
123274 };
123275 
123276 /*
123277 ** An instance of the following structure describes the event of a
123278 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
123279 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
123280 **
123281 **      UPDATE ON (a,b,c)
123282 **
123283 ** Then the "b" IdList records the list "a,b,c".
123284 */
123285 struct TrigEvent { int a; IdList * b; };
123286 
123287 /*
123288 ** An instance of this structure holds the ATTACH key and the key type.
123289 */
123290 struct AttachKey { int type;  Token key; };
123291 
123292 
123293   /*
123294   ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
123295   ** all elements in the list.  And make sure list length does not exceed
123296   ** SQLITE_LIMIT_COMPOUND_SELECT.
123297   */
123298   static void parserDoubleLinkSelect(Parse *pParse, Select *p){
123299     if( p->pPrior ){
123300       Select *pNext = 0, *pLoop;
123301       int mxSelect, cnt = 0;
123302       for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
123303         pLoop->pNext = pNext;
123304         pLoop->selFlags |= SF_Compound;
123305       }
123306       if( (p->selFlags & SF_MultiValue)==0 &&
123307         (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
123308         cnt>mxSelect
123309       ){
123310         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
123311       }
123312     }
123313   }
123314 
123315   /* This is a utility routine used to set the ExprSpan.zStart and
123316   ** ExprSpan.zEnd values of pOut so that the span covers the complete
123317   ** range of text beginning with pStart and going to the end of pEnd.
123318   */
123319   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
123320     pOut->zStart = pStart->z;
123321     pOut->zEnd = &pEnd->z[pEnd->n];
123322   }
123323 
123324   /* Construct a new Expr object from a single identifier.  Use the
123325   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
123326   ** that created the expression.
123327   */
123328   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
123329     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
123330     pOut->zStart = pValue->z;
123331     pOut->zEnd = &pValue->z[pValue->n];
123332   }
123333 
123334   /* This routine constructs a binary expression node out of two ExprSpan
123335   ** objects and uses the result to populate a new ExprSpan object.
123336   */
123337   static void spanBinaryExpr(
123338     ExprSpan *pOut,     /* Write the result here */
123339     Parse *pParse,      /* The parsing context.  Errors accumulate here */
123340     int op,             /* The binary operation */
123341     ExprSpan *pLeft,    /* The left operand */
123342     ExprSpan *pRight    /* The right operand */
123343   ){
123344     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
123345     pOut->zStart = pLeft->zStart;
123346     pOut->zEnd = pRight->zEnd;
123347   }
123348 
123349   /* Construct an expression node for a unary postfix operator
123350   */
123351   static void spanUnaryPostfix(
123352     ExprSpan *pOut,        /* Write the new expression node here */
123353     Parse *pParse,         /* Parsing context to record errors */
123354     int op,                /* The operator */
123355     ExprSpan *pOperand,    /* The operand */
123356     Token *pPostOp         /* The operand token for setting the span */
123357   ){
123358     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
123359     pOut->zStart = pOperand->zStart;
123360     pOut->zEnd = &pPostOp->z[pPostOp->n];
123361   }
123362 
123363   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
123364   ** unary TK_ISNULL or TK_NOTNULL expression. */
123365   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
123366     sqlite3 *db = pParse->db;
123367     if( pY && pA && pY->op==TK_NULL ){
123368       pA->op = (u8)op;
123369       sqlite3ExprDelete(db, pA->pRight);
123370       pA->pRight = 0;
123371     }
123372   }
123373 
123374   /* Construct an expression node for a unary prefix operator
123375   */
123376   static void spanUnaryPrefix(
123377     ExprSpan *pOut,        /* Write the new expression node here */
123378     Parse *pParse,         /* Parsing context to record errors */
123379     int op,                /* The operator */
123380     ExprSpan *pOperand,    /* The operand */
123381     Token *pPreOp         /* The operand token for setting the span */
123382   ){
123383     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
123384     pOut->zStart = pPreOp->z;
123385     pOut->zEnd = pOperand->zEnd;
123386   }
123387 /* Next is all token values, in a form suitable for use by makeheaders.
123388 ** This section will be null unless lemon is run with the -m switch.
123389 */
123390 /*
123391 ** These constants (all generated automatically by the parser generator)
123392 ** specify the various kinds of tokens (terminals) that the parser
123393 ** understands.
123394 **
123395 ** Each symbol here is a terminal symbol in the grammar.
123396 */
123397 /* Make sure the INTERFACE macro is defined.
123398 */
123399 #ifndef INTERFACE
123400 # define INTERFACE 1
123401 #endif
123402 /* The next thing included is series of defines which control
123403 ** various aspects of the generated parser.
123404 **    YYCODETYPE         is the data type used for storing terminal
123405 **                       and nonterminal numbers.  "unsigned char" is
123406 **                       used if there are fewer than 250 terminals
123407 **                       and nonterminals.  "int" is used otherwise.
123408 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
123409 **                       to no legal terminal or nonterminal number.  This
123410 **                       number is used to fill in empty slots of the hash
123411 **                       table.
123412 **    YYFALLBACK         If defined, this indicates that one or more tokens
123413 **                       have fall-back values which should be used if the
123414 **                       original value of the token will not parse.
123415 **    YYACTIONTYPE       is the data type used for storing terminal
123416 **                       and nonterminal numbers.  "unsigned char" is
123417 **                       used if there are fewer than 250 rules and
123418 **                       states combined.  "int" is used otherwise.
123419 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
123420 **                       directly to the parser from the tokenizer.
123421 **    YYMINORTYPE        is the data type used for all minor tokens.
123422 **                       This is typically a union of many types, one of
123423 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
123424 **                       for base tokens is called "yy0".
123425 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
123426 **                       zero the stack is dynamically sized using realloc()
123427 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
123428 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
123429 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
123430 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
123431 **    YYNSTATE           the combined number of states.
123432 **    YYNRULE            the number of rules in the grammar
123433 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
123434 **                       defined, then do no error processing.
123435 */
123436 #define YYCODETYPE unsigned char
123437 #define YYNOCODE 254
123438 #define YYACTIONTYPE unsigned short int
123439 #define YYWILDCARD 70
123440 #define sqlite3ParserTOKENTYPE Token
123441 typedef union {
123442   int yyinit;
123443   sqlite3ParserTOKENTYPE yy0;
123444   Select* yy3;
123445   ExprList* yy14;
123446   With* yy59;
123447   SrcList* yy65;
123448   struct LikeOp yy96;
123449   Expr* yy132;
123450   u8 yy186;
123451   int yy328;
123452   ExprSpan yy346;
123453   struct TrigEvent yy378;
123454   u16 yy381;
123455   IdList* yy408;
123456   struct {int value; int mask;} yy429;
123457   TriggerStep* yy473;
123458   struct LimitVal yy476;
123459 } YYMINORTYPE;
123460 #ifndef YYSTACKDEPTH
123461 #define YYSTACKDEPTH 100
123462 #endif
123463 #define sqlite3ParserARG_SDECL Parse *pParse;
123464 #define sqlite3ParserARG_PDECL ,Parse *pParse
123465 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
123466 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
123467 #define YYNSTATE 642
123468 #define YYNRULE 327
123469 #define YYFALLBACK 1
123470 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
123471 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
123472 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
123473 
123474 /* The yyzerominor constant is used to initialize instances of
123475 ** YYMINORTYPE objects to zero. */
123476 static const YYMINORTYPE yyzerominor = { 0 };
123477 
123478 /* Define the yytestcase() macro to be a no-op if is not already defined
123479 ** otherwise.
123480 **
123481 ** Applications can choose to define yytestcase() in the %include section
123482 ** to a macro that can assist in verifying code coverage.  For production
123483 ** code the yytestcase() macro should be turned off.  But it is useful
123484 ** for testing.
123485 */
123486 #ifndef yytestcase
123487 # define yytestcase(X)
123488 #endif
123489 
123490 
123491 /* Next are the tables used to determine what action to take based on the
123492 ** current state and lookahead token.  These tables are used to implement
123493 ** functions that take a state number and lookahead value and return an
123494 ** action integer.
123495 **
123496 ** Suppose the action integer is N.  Then the action is determined as
123497 ** follows
123498 **
123499 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
123500 **                                      token onto the stack and goto state N.
123501 **
123502 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
123503 **
123504 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
123505 **
123506 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
123507 **
123508 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
123509 **                                      slots in the yy_action[] table.
123510 **
123511 ** The action table is constructed as a single large table named yy_action[].
123512 ** Given state S and lookahead X, the action is computed as
123513 **
123514 **      yy_action[ yy_shift_ofst[S] + X ]
123515 **
123516 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
123517 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
123518 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
123519 ** and that yy_default[S] should be used instead.
123520 **
123521 ** The formula above is for computing the action when the lookahead is
123522 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
123523 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
123524 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
123525 ** YY_SHIFT_USE_DFLT.
123526 **
123527 ** The following are the tables generated in this section:
123528 **
123529 **  yy_action[]        A single table containing all actions.
123530 **  yy_lookahead[]     A table containing the lookahead for each entry in
123531 **                     yy_action.  Used to detect hash collisions.
123532 **  yy_shift_ofst[]    For each state, the offset into yy_action for
123533 **                     shifting terminals.
123534 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
123535 **                     shifting non-terminals after a reduce.
123536 **  yy_default[]       Default action for each state.
123537 */
123538 #define YY_ACTTAB_COUNT (1497)
123539 static const YYACTIONTYPE yy_action[] = {
123540  /*     0 */   306,  212,  432,  955,  639,  191,  955,  295,  559,   88,
123541  /*    10 */    88,   88,   88,   81,   86,   86,   86,   86,   85,   85,
123542  /*    20 */    84,   84,   84,   83,  330,  185,  184,  183,  635,  635,
123543  /*    30 */   292,  606,  606,   88,   88,   88,   88,  683,   86,   86,
123544  /*    40 */    86,   86,   85,   85,   84,   84,   84,   83,  330,   16,
123545  /*    50 */   436,  597,   89,   90,   80,  600,  599,  601,  601,   87,
123546  /*    60 */    87,   88,   88,   88,   88,  684,   86,   86,   86,   86,
123547  /*    70 */    85,   85,   84,   84,   84,   83,  330,  306,  559,   84,
123548  /*    80 */    84,   84,   83,  330,   65,   86,   86,   86,   86,   85,
123549  /*    90 */    85,   84,   84,   84,   83,  330,  635,  635,  634,  633,
123550  /*   100 */   182,  682,  550,  379,  376,  375,   17,  322,  606,  606,
123551  /*   110 */   371,  198,  479,   91,  374,   82,   79,  165,   85,   85,
123552  /*   120 */    84,   84,   84,   83,  330,  598,  635,  635,  107,   89,
123553  /*   130 */    90,   80,  600,  599,  601,  601,   87,   87,   88,   88,
123554  /*   140 */    88,   88,  186,   86,   86,   86,   86,   85,   85,   84,
123555  /*   150 */    84,   84,   83,  330,  306,  594,  594,  142,  328,  327,
123556  /*   160 */   484,  249,  344,  238,  635,  635,  634,  633,  585,  448,
123557  /*   170 */   526,  525,  229,  388,    1,  394,  450,  584,  449,  635,
123558  /*   180 */   635,  635,  635,  319,  395,  606,  606,  199,  157,  273,
123559  /*   190 */   382,  268,  381,  187,  635,  635,  634,  633,  311,  555,
123560  /*   200 */   266,  593,  593,  266,  347,  588,   89,   90,   80,  600,
123561  /*   210 */   599,  601,  601,   87,   87,   88,   88,   88,   88,  478,
123562  /*   220 */    86,   86,   86,   86,   85,   85,   84,   84,   84,   83,
123563  /*   230 */   330,  306,  272,  536,  634,  633,  146,  610,  197,  310,
123564  /*   240 */   575,  182,  482,  271,  379,  376,  375,  506,   21,  634,
123565  /*   250 */   633,  634,  633,  635,  635,  374,  611,  574,  548,  440,
123566  /*   260 */   111,  563,  606,  606,  634,  633,  324,  479,  608,  608,
123567  /*   270 */   608,  300,  435,  573,  119,  407,  210,  162,  562,  883,
123568  /*   280 */   592,  592,  306,   89,   90,   80,  600,  599,  601,  601,
123569  /*   290 */    87,   87,   88,   88,   88,   88,  506,   86,   86,   86,
123570  /*   300 */    86,   85,   85,   84,   84,   84,   83,  330,  620,  111,
123571  /*   310 */   635,  635,  361,  606,  606,  358,  249,  349,  248,  433,
123572  /*   320 */   243,  479,  586,  634,  633,  195,  611,   93,  119,  221,
123573  /*   330 */   575,  497,  534,  534,   89,   90,   80,  600,  599,  601,
123574  /*   340 */   601,   87,   87,   88,   88,   88,   88,  574,   86,   86,
123575  /*   350 */    86,   86,   85,   85,   84,   84,   84,   83,  330,  306,
123576  /*   360 */    77,  429,  638,  573,  589,  530,  240,  230,  242,  105,
123577  /*   370 */   249,  349,  248,  515,  588,  208,  460,  529,  564,  173,
123578  /*   380 */   634,  633,  970,  144,  430,    2,  424,  228,  380,  557,
123579  /*   390 */   606,  606,  190,  153,  159,  158,  514,   51,  632,  631,
123580  /*   400 */   630,   71,  536,  432,  954,  196,  610,  954,  614,   45,
123581  /*   410 */    18,   89,   90,   80,  600,  599,  601,  601,   87,   87,
123582  /*   420 */    88,   88,   88,   88,  261,   86,   86,   86,   86,   85,
123583  /*   430 */    85,   84,   84,   84,   83,  330,  306,  608,  608,  608,
123584  /*   440 */   542,  424,  402,  385,  241,  506,  451,  320,  211,  543,
123585  /*   450 */   164,  436,  386,  293,  451,  587,  108,  496,  111,  334,
123586  /*   460 */   391,  591,  424,  614,   27,  452,  453,  606,  606,   72,
123587  /*   470 */   257,   70,  259,  452,  339,  342,  564,  582,   68,  415,
123588  /*   480 */   469,  328,  327,   62,  614,   45,  110,  393,   89,   90,
123589  /*   490 */    80,  600,  599,  601,  601,   87,   87,   88,   88,   88,
123590  /*   500 */    88,  152,   86,   86,   86,   86,   85,   85,   84,   84,
123591  /*   510 */    84,   83,  330,  306,  110,  499,  520,  538,  402,  389,
123592  /*   520 */   424,  110,  566,  500,  593,  593,  454,   82,   79,  165,
123593  /*   530 */   424,  591,  384,  564,  340,  615,  188,  162,  424,  350,
123594  /*   540 */   616,  424,  614,   44,  606,  606,  445,  582,  300,  434,
123595  /*   550 */   151,   19,  614,    9,  568,  580,  348,  615,  469,  567,
123596  /*   560 */   614,   26,  616,  614,   45,   89,   90,   80,  600,  599,
123597  /*   570 */   601,  601,   87,   87,   88,   88,   88,   88,  411,   86,
123598  /*   580 */    86,   86,   86,   85,   85,   84,   84,   84,   83,  330,
123599  /*   590 */   306,  579,  110,  578,  521,  282,  433,  398,  400,  255,
123600  /*   600 */   486,   82,   79,  165,  487,  164,   82,   79,  165,  488,
123601  /*   610 */   488,  364,  387,  424,  544,  544,  509,  350,  362,  155,
123602  /*   620 */   191,  606,  606,  559,  642,  640,  333,   82,   79,  165,
123603  /*   630 */   305,  564,  507,  312,  357,  614,   45,  329,  596,  595,
123604  /*   640 */   194,  337,   89,   90,   80,  600,  599,  601,  601,   87,
123605  /*   650 */    87,   88,   88,   88,   88,  424,   86,   86,   86,   86,
123606  /*   660 */    85,   85,   84,   84,   84,   83,  330,  306,   20,  323,
123607  /*   670 */   150,  263,  211,  543,  421,  596,  595,  614,   22,  424,
123608  /*   680 */   193,  424,  284,  424,  391,  424,  509,  424,  577,  424,
123609  /*   690 */   186,  335,  424,  559,  424,  313,  120,  546,  606,  606,
123610  /*   700 */    67,  614,   47,  614,   50,  614,   48,  614,  100,  614,
123611  /*   710 */    99,  614,  101,  576,  614,  102,  614,  109,  326,   89,
123612  /*   720 */    90,   80,  600,  599,  601,  601,   87,   87,   88,   88,
123613  /*   730 */    88,   88,  424,   86,   86,   86,   86,   85,   85,   84,
123614  /*   740 */    84,   84,   83,  330,  306,  424,  311,  424,  585,   54,
123615  /*   750 */   424,  516,  517,  590,  614,  112,  424,  584,  424,  572,
123616  /*   760 */   424,  195,  424,  571,  424,   67,  424,  614,   94,  614,
123617  /*   770 */    98,  424,  614,   97,  264,  606,  606,  195,  614,   46,
123618  /*   780 */   614,   96,  614,   30,  614,   49,  614,  115,  614,  114,
123619  /*   790 */   418,  229,  388,  614,  113,  306,   89,   90,   80,  600,
123620  /*   800 */   599,  601,  601,   87,   87,   88,   88,   88,   88,  424,
123621  /*   810 */    86,   86,   86,   86,   85,   85,   84,   84,   84,   83,
123622  /*   820 */   330,  119,  424,  590,  110,  372,  606,  606,  195,   53,
123623  /*   830 */   250,  614,   29,  195,  472,  438,  729,  190,  302,  498,
123624  /*   840 */    14,  523,  641,    2,  614,   43,  306,   89,   90,   80,
123625  /*   850 */   600,  599,  601,  601,   87,   87,   88,   88,   88,   88,
123626  /*   860 */   424,   86,   86,   86,   86,   85,   85,   84,   84,   84,
123627  /*   870 */    83,  330,  424,  613,  964,  964,  354,  606,  606,  420,
123628  /*   880 */   312,   64,  614,   42,  391,  355,  283,  437,  301,  255,
123629  /*   890 */   414,  410,  495,  492,  614,   28,  471,  306,   89,   90,
123630  /*   900 */    80,  600,  599,  601,  601,   87,   87,   88,   88,   88,
123631  /*   910 */    88,  424,   86,   86,   86,   86,   85,   85,   84,   84,
123632  /*   920 */    84,   83,  330,  424,  110,  110,  110,  110,  606,  606,
123633  /*   930 */   110,  254,   13,  614,   41,  532,  531,  283,  481,  531,
123634  /*   940 */   457,  284,  119,  561,  356,  614,   40,  284,  306,   89,
123635  /*   950 */    78,   80,  600,  599,  601,  601,   87,   87,   88,   88,
123636  /*   960 */    88,   88,  424,   86,   86,   86,   86,   85,   85,   84,
123637  /*   970 */    84,   84,   83,  330,  110,  424,  341,  220,  555,  606,
123638  /*   980 */   606,  351,  555,  318,  614,   95,  413,  255,   83,  330,
123639  /*   990 */   284,  284,  255,  640,  333,  356,  255,  614,   39,  306,
123640  /*  1000 */   356,   90,   80,  600,  599,  601,  601,   87,   87,   88,
123641  /*  1010 */    88,   88,   88,  424,   86,   86,   86,   86,   85,   85,
123642  /*  1020 */    84,   84,   84,   83,  330,  424,  317,  316,  141,  465,
123643  /*  1030 */   606,  606,  219,  619,  463,  614,   10,  417,  462,  255,
123644  /*  1040 */   189,  510,  553,  351,  207,  363,  161,  614,   38,  315,
123645  /*  1050 */   218,  255,  255,   80,  600,  599,  601,  601,   87,   87,
123646  /*  1060 */    88,   88,   88,   88,  424,   86,   86,   86,   86,   85,
123647  /*  1070 */    85,   84,   84,   84,   83,  330,   76,  419,  255,    3,
123648  /*  1080 */   878,  461,  424,  247,  331,  331,  614,   37,  217,   76,
123649  /*  1090 */   419,  390,    3,  216,  215,  422,    4,  331,  331,  424,
123650  /*  1100 */   547,   12,  424,  545,  614,   36,  424,  541,  422,  424,
123651  /*  1110 */   540,  424,  214,  424,  408,  424,  539,  403,  605,  605,
123652  /*  1120 */   237,  614,   25,  119,  614,   24,  588,  408,  614,   45,
123653  /*  1130 */   118,  614,   35,  614,   34,  614,   33,  614,   23,  588,
123654  /*  1140 */    60,  223,  603,  602,  513,  378,   73,   74,  140,  139,
123655  /*  1150 */   424,  110,  265,   75,  426,  425,   59,  424,  610,   73,
123656  /*  1160 */    74,  549,  402,  404,  424,  373,   75,  426,  425,  604,
123657  /*  1170 */   138,  610,  614,   11,  392,   76,  419,  181,    3,  614,
123658  /*  1180 */    32,  271,  369,  331,  331,  493,  614,   31,  149,  608,
123659  /*  1190 */   608,  608,  607,   15,  422,  365,  614,    8,  137,  489,
123660  /*  1200 */   136,  190,  608,  608,  608,  607,   15,  485,  176,  135,
123661  /*  1210 */     7,  252,  477,  408,  174,  133,  175,  474,   57,   56,
123662  /*  1220 */   132,  130,  119,   76,  419,  588,    3,  468,  245,  464,
123663  /*  1230 */   171,  331,  331,  125,  123,  456,  447,  122,  446,  104,
123664  /*  1240 */   336,  231,  422,  166,  154,   73,   74,  332,  116,  431,
123665  /*  1250 */   121,  309,   75,  426,  425,  222,  106,  610,  308,  637,
123666  /*  1260 */   204,  408,  629,  627,  628,    6,  200,  428,  427,  290,
123667  /*  1270 */   203,  622,  201,  588,   62,   63,  289,   66,  419,  399,
123668  /*  1280 */     3,  401,  288,   92,  143,  331,  331,  287,  608,  608,
123669  /*  1290 */   608,  607,   15,   73,   74,  227,  422,  325,   69,  416,
123670  /*  1300 */    75,  426,  425,  612,  412,  610,  192,   61,  569,  209,
123671  /*  1310 */   396,  226,  278,  225,  383,  408,  527,  558,  276,  533,
123672  /*  1320 */   552,  528,  321,  523,  370,  508,  180,  588,  494,  179,
123673  /*  1330 */   366,  117,  253,  269,  522,  503,  608,  608,  608,  607,
123674  /*  1340 */    15,  551,  502,   58,  274,  524,  178,   73,   74,  304,
123675  /*  1350 */   501,  368,  303,  206,   75,  426,  425,  491,  360,  610,
123676  /*  1360 */   213,  177,  483,  131,  345,  298,  297,  296,  202,  294,
123677  /*  1370 */   480,  490,  466,  134,  172,  129,  444,  346,  470,  128,
123678  /*  1380 */   314,  459,  103,  127,  126,  148,  124,  167,  443,  235,
123679  /*  1390 */   608,  608,  608,  607,   15,  442,  439,  623,  234,  299,
123680  /*  1400 */   145,  583,  291,  377,  581,  160,  119,  156,  270,  636,
123681  /*  1410 */   971,  169,  279,  626,  520,  625,  473,  624,  170,  621,
123682  /*  1420 */   618,  119,  168,   55,  409,  423,  537,  609,  286,  285,
123683  /*  1430 */   405,  570,  560,  556,    5,   52,  458,  554,  147,  267,
123684  /*  1440 */   519,  504,  518,  406,  262,  239,  260,  512,  343,  511,
123685  /*  1450 */   258,  353,  565,  256,  224,  251,  359,  277,  275,  476,
123686  /*  1460 */   475,  246,  352,  244,  467,  455,  236,  233,  232,  307,
123687  /*  1470 */   441,  281,  205,  163,  397,  280,  535,  505,  330,  617,
123688  /*  1480 */   971,  971,  971,  971,  367,  971,  971,  971,  971,  971,
123689  /*  1490 */   971,  971,  971,  971,  971,  971,  338,
123690 };
123691 static const YYCODETYPE yy_lookahead[] = {
123692  /*     0 */    19,   22,   22,   23,    1,   24,   26,   15,   27,   80,
123693  /*    10 */    81,   82,   83,   84,   85,   86,   87,   88,   89,   90,
123694  /*    20 */    91,   92,   93,   94,   95,  108,  109,  110,   27,   28,
123695  /*    30 */    23,   50,   51,   80,   81,   82,   83,  122,   85,   86,
123696  /*    40 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   22,
123697  /*    50 */    70,   23,   71,   72,   73,   74,   75,   76,   77,   78,
123698  /*    60 */    79,   80,   81,   82,   83,  122,   85,   86,   87,   88,
123699  /*    70 */    89,   90,   91,   92,   93,   94,   95,   19,   97,   91,
123700  /*    80 */    92,   93,   94,   95,   26,   85,   86,   87,   88,   89,
123701  /*    90 */    90,   91,   92,   93,   94,   95,   27,   28,   97,   98,
123702  /*   100 */    99,  122,  211,  102,  103,  104,   79,   19,   50,   51,
123703  /*   110 */    19,  122,   59,   55,  113,  224,  225,  226,   89,   90,
123704  /*   120 */    91,   92,   93,   94,   95,   23,   27,   28,   26,   71,
123705  /*   130 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
123706  /*   140 */    82,   83,   51,   85,   86,   87,   88,   89,   90,   91,
123707  /*   150 */    92,   93,   94,   95,   19,  132,  133,   58,   89,   90,
123708  /*   160 */    21,  108,  109,  110,   27,   28,   97,   98,   33,  100,
123709  /*   170 */     7,    8,  119,  120,   22,   19,  107,   42,  109,   27,
123710  /*   180 */    28,   27,   28,   95,   28,   50,   51,   99,  100,  101,
123711  /*   190 */   102,  103,  104,  105,   27,   28,   97,   98,  107,  152,
123712  /*   200 */   112,  132,  133,  112,   65,   69,   71,   72,   73,   74,
123713  /*   210 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   11,
123714  /*   220 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
123715  /*   230 */    95,   19,  101,   97,   97,   98,   24,  101,  122,  157,
123716  /*   240 */    12,   99,  103,  112,  102,  103,  104,  152,   22,   97,
123717  /*   250 */    98,   97,   98,   27,   28,  113,   27,   29,   91,  164,
123718  /*   260 */   165,  124,   50,   51,   97,   98,  219,   59,  132,  133,
123719  /*   270 */   134,   22,   23,   45,   66,   47,  212,  213,  124,  140,
123720  /*   280 */   132,  133,   19,   71,   72,   73,   74,   75,   76,   77,
123721  /*   290 */    78,   79,   80,   81,   82,   83,  152,   85,   86,   87,
123722  /*   300 */    88,   89,   90,   91,   92,   93,   94,   95,  164,  165,
123723  /*   310 */    27,   28,  230,   50,   51,  233,  108,  109,  110,   70,
123724  /*   320 */    16,   59,   23,   97,   98,   26,   97,   22,   66,  185,
123725  /*   330 */    12,  187,   27,   28,   71,   72,   73,   74,   75,   76,
123726  /*   340 */    77,   78,   79,   80,   81,   82,   83,   29,   85,   86,
123727  /*   350 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   19,
123728  /*   360 */    22,  148,  149,   45,   23,   47,   62,  154,   64,  156,
123729  /*   370 */   108,  109,  110,   37,   69,   23,  163,   59,   26,   26,
123730  /*   380 */    97,   98,  144,  145,  146,  147,  152,  200,   52,   23,
123731  /*   390 */    50,   51,   26,   22,   89,   90,   60,  210,    7,    8,
123732  /*   400 */     9,  138,   97,   22,   23,   26,  101,   26,  174,  175,
123733  /*   410 */   197,   71,   72,   73,   74,   75,   76,   77,   78,   79,
123734  /*   420 */    80,   81,   82,   83,   16,   85,   86,   87,   88,   89,
123735  /*   430 */    90,   91,   92,   93,   94,   95,   19,  132,  133,  134,
123736  /*   440 */    23,  152,  208,  209,  140,  152,  152,  111,  195,  196,
123737  /*   450 */    98,   70,  163,  160,  152,   23,   22,  164,  165,  246,
123738  /*   460 */   207,   27,  152,  174,  175,  171,  172,   50,   51,  137,
123739  /*   470 */    62,  139,   64,  171,  172,  222,  124,   27,  138,   24,
123740  /*   480 */   163,   89,   90,  130,  174,  175,  197,  163,   71,   72,
123741  /*   490 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
123742  /*   500 */    83,   22,   85,   86,   87,   88,   89,   90,   91,   92,
123743  /*   510 */    93,   94,   95,   19,  197,  181,  182,   23,  208,  209,
123744  /*   520 */   152,  197,   26,  189,  132,  133,  232,  224,  225,  226,
123745  /*   530 */   152,   97,   91,   26,  232,  116,  212,  213,  152,  222,
123746  /*   540 */   121,  152,  174,  175,   50,   51,  243,   97,   22,   23,
123747  /*   550 */    22,  234,  174,  175,  177,   23,  239,  116,  163,  177,
123748  /*   560 */   174,  175,  121,  174,  175,   71,   72,   73,   74,   75,
123749  /*   570 */    76,   77,   78,   79,   80,   81,   82,   83,   24,   85,
123750  /*   580 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   95,
123751  /*   590 */    19,   23,  197,   11,   23,  227,   70,  208,  220,  152,
123752  /*   600 */    31,  224,  225,  226,   35,   98,  224,  225,  226,  108,
123753  /*   610 */   109,  110,  115,  152,  117,  118,   27,  222,   49,  123,
123754  /*   620 */    24,   50,   51,   27,    0,    1,    2,  224,  225,  226,
123755  /*   630 */   166,  124,  168,  169,  239,  174,  175,  170,  171,  172,
123756  /*   640 */    22,  194,   71,   72,   73,   74,   75,   76,   77,   78,
123757  /*   650 */    79,   80,   81,   82,   83,  152,   85,   86,   87,   88,
123758  /*   660 */    89,   90,   91,   92,   93,   94,   95,   19,   22,  208,
123759  /*   670 */    24,   23,  195,  196,  170,  171,  172,  174,  175,  152,
123760  /*   680 */    26,  152,  152,  152,  207,  152,   97,  152,   23,  152,
123761  /*   690 */    51,  244,  152,   97,  152,  247,  248,   23,   50,   51,
123762  /*   700 */    26,  174,  175,  174,  175,  174,  175,  174,  175,  174,
123763  /*   710 */   175,  174,  175,   23,  174,  175,  174,  175,  188,   71,
123764  /*   720 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
123765  /*   730 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
123766  /*   740 */    92,   93,   94,   95,   19,  152,  107,  152,   33,   24,
123767  /*   750 */   152,  100,  101,   27,  174,  175,  152,   42,  152,   23,
123768  /*   760 */   152,   26,  152,   23,  152,   26,  152,  174,  175,  174,
123769  /*   770 */   175,  152,  174,  175,   23,   50,   51,   26,  174,  175,
123770  /*   780 */   174,  175,  174,  175,  174,  175,  174,  175,  174,  175,
123771  /*   790 */   163,  119,  120,  174,  175,   19,   71,   72,   73,   74,
123772  /*   800 */    75,   76,   77,   78,   79,   80,   81,   82,   83,  152,
123773  /*   810 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
123774  /*   820 */    95,   66,  152,   97,  197,   23,   50,   51,   26,   53,
123775  /*   830 */    23,  174,  175,   26,   23,   23,   23,   26,   26,   26,
123776  /*   840 */    36,  106,  146,  147,  174,  175,   19,   71,   72,   73,
123777  /*   850 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
123778  /*   860 */   152,   85,   86,   87,   88,   89,   90,   91,   92,   93,
123779  /*   870 */    94,   95,  152,  196,  119,  120,   19,   50,   51,  168,
123780  /*   880 */   169,   26,  174,  175,  207,   28,  152,  249,  250,  152,
123781  /*   890 */   163,  163,  163,  163,  174,  175,  163,   19,   71,   72,
123782  /*   900 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
123783  /*   910 */    83,  152,   85,   86,   87,   88,   89,   90,   91,   92,
123784  /*   920 */    93,   94,   95,  152,  197,  197,  197,  197,   50,   51,
123785  /*   930 */   197,  194,   36,  174,  175,  191,  192,  152,  191,  192,
123786  /*   940 */   163,  152,   66,  124,  152,  174,  175,  152,   19,   71,
123787  /*   950 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
123788  /*   960 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
123789  /*   970 */    92,   93,   94,   95,  197,  152,  100,  188,  152,   50,
123790  /*   980 */    51,  152,  152,  188,  174,  175,  252,  152,   94,   95,
123791  /*   990 */   152,  152,  152,    1,    2,  152,  152,  174,  175,   19,
123792  /*  1000 */   152,   72,   73,   74,   75,   76,   77,   78,   79,   80,
123793  /*  1010 */    81,   82,   83,  152,   85,   86,   87,   88,   89,   90,
123794  /*  1020 */    91,   92,   93,   94,   95,  152,  188,  188,   22,  194,
123795  /*  1030 */    50,   51,  240,  173,  194,  174,  175,  252,  194,  152,
123796  /*  1040 */    36,  181,   28,  152,   23,  219,  122,  174,  175,  219,
123797  /*  1050 */   221,  152,  152,   73,   74,   75,   76,   77,   78,   79,
123798  /*  1060 */    80,   81,   82,   83,  152,   85,   86,   87,   88,   89,
123799  /*  1070 */    90,   91,   92,   93,   94,   95,   19,   20,  152,   22,
123800  /*  1080 */    23,  194,  152,  240,   27,   28,  174,  175,  240,   19,
123801  /*  1090 */    20,   26,   22,  194,  194,   38,   22,   27,   28,  152,
123802  /*  1100 */    23,   22,  152,  116,  174,  175,  152,   23,   38,  152,
123803  /*  1110 */    23,  152,  221,  152,   57,  152,   23,  163,   50,   51,
123804  /*  1120 */   194,  174,  175,   66,  174,  175,   69,   57,  174,  175,
123805  /*  1130 */    40,  174,  175,  174,  175,  174,  175,  174,  175,   69,
123806  /*  1140 */    22,   53,   74,   75,   30,   53,   89,   90,   22,   22,
123807  /*  1150 */   152,  197,   23,   96,   97,   98,   22,  152,  101,   89,
123808  /*  1160 */    90,   91,  208,  209,  152,   53,   96,   97,   98,  101,
123809  /*  1170 */    22,  101,  174,  175,  152,   19,   20,  105,   22,  174,
123810  /*  1180 */   175,  112,   19,   27,   28,   20,  174,  175,   24,  132,
123811  /*  1190 */   133,  134,  135,  136,   38,   44,  174,  175,  107,   61,
123812  /*  1200 */    54,   26,  132,  133,  134,  135,  136,   54,  107,   22,
123813  /*  1210 */     5,  140,    1,   57,   36,  111,  122,   28,   79,   79,
123814  /*  1220 */   131,  123,   66,   19,   20,   69,   22,    1,   16,   20,
123815  /*  1230 */   125,   27,   28,  123,  111,  120,   23,  131,   23,   16,
123816  /*  1240 */    68,  142,   38,   15,   22,   89,   90,    3,  167,    4,
123817  /*  1250 */   248,  251,   96,   97,   98,  180,  180,  101,  251,  151,
123818  /*  1260 */     6,   57,  151,   13,  151,   26,   25,  151,  161,  202,
123819  /*  1270 */   153,  162,  153,   69,  130,  128,  203,   19,   20,  127,
123820  /*  1280 */    22,  126,  204,  129,   22,   27,   28,  205,  132,  133,
123821  /*  1290 */   134,  135,  136,   89,   90,  231,   38,   95,  137,  179,
123822  /*  1300 */    96,   97,   98,  206,  179,  101,  122,  107,  159,  159,
123823  /*  1310 */   125,  231,  216,  228,  107,   57,  184,  217,  216,  176,
123824  /*  1320 */   217,  176,   48,  106,   18,  184,  158,   69,  159,  158,
123825  /*  1330 */    46,   71,  237,  176,  176,  176,  132,  133,  134,  135,
123826  /*  1340 */   136,  217,  176,  137,  216,  178,  158,   89,   90,  179,
123827  /*  1350 */   176,  159,  179,  159,   96,   97,   98,  159,  159,  101,
123828  /*  1360 */     5,  158,  202,   22,   18,   10,   11,   12,   13,   14,
123829  /*  1370 */   190,  238,   17,  190,  158,  193,   41,  159,  202,  193,
123830  /*  1380 */   159,  202,  245,  193,  193,  223,  190,   32,  159,   34,
123831  /*  1390 */   132,  133,  134,  135,  136,  159,   39,  155,   43,  150,
123832  /*  1400 */   223,  177,  201,  178,  177,  186,   66,  199,  177,  152,
123833  /*  1410 */   253,   56,  215,  152,  182,  152,  202,  152,   63,  152,
123834  /*  1420 */   152,   66,   67,  242,  229,  152,  174,  152,  152,  152,
123835  /*  1430 */   152,  152,  152,  152,  199,  242,  202,  152,  198,  152,
123836  /*  1440 */   152,  152,  183,  192,  152,  215,  152,  183,  215,  183,
123837  /*  1450 */   152,  241,  214,  152,  211,  152,  152,  211,  211,  152,
123838  /*  1460 */   152,  241,  152,  152,  152,  152,  152,  152,  152,  114,
123839  /*  1470 */   152,  152,  235,  152,  152,  152,  174,  187,   95,  174,
123840  /*  1480 */   253,  253,  253,  253,  236,  253,  253,  253,  253,  253,
123841  /*  1490 */   253,  253,  253,  253,  253,  253,  141,
123842 };
123843 #define YY_SHIFT_USE_DFLT (-86)
123844 #define YY_SHIFT_COUNT (429)
123845 #define YY_SHIFT_MIN   (-85)
123846 #define YY_SHIFT_MAX   (1383)
123847 static const short yy_shift_ofst[] = {
123848  /*     0 */   992, 1057, 1355, 1156, 1204, 1204,    1,  262,  -19,  135,
123849  /*    10 */   135,  776, 1204, 1204, 1204, 1204,   69,   69,   53,  208,
123850  /*    20 */   283,  755,   58,  725,  648,  571,  494,  417,  340,  263,
123851  /*    30 */   212,  827,  827,  827,  827,  827,  827,  827,  827,  827,
123852  /*    40 */   827,  827,  827,  827,  827,  827,  878,  827,  929,  980,
123853  /*    50 */   980, 1070, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
123854  /*    60 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
123855  /*    70 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
123856  /*    80 */  1258, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
123857  /*    90 */  1204, 1204, 1204, 1204,  -71,  -47,  -47,  -47,  -47,  -47,
123858  /*   100 */     0,   29,  -12,  283,  283,  139,   91,  392,  392,  894,
123859  /*   110 */   672,  726, 1383,  -86,  -86,  -86,   88,  318,  318,   99,
123860  /*   120 */   381,  -20,  283,  283,  283,  283,  283,  283,  283,  283,
123861  /*   130 */   283,  283,  283,  283,  283,  283,  283,  283,  283,  283,
123862  /*   140 */   283,  283,  283,  283,  624,  876,  726,  672, 1340, 1340,
123863  /*   150 */  1340, 1340, 1340, 1340,  -86,  -86,  -86,  305,  136,  136,
123864  /*   160 */   142,  167,  226,  154,  137,  152,  283,  283,  283,  283,
123865  /*   170 */   283,  283,  283,  283,  283,  283,  283,  283,  283,  283,
123866  /*   180 */   283,  283,  283,  336,  336,  336,  283,  283,  352,  283,
123867  /*   190 */   283,  283,  283,  283,  228,  283,  283,  283,  283,  283,
123868  /*   200 */   283,  283,  283,  283,  283,  501,  569,  596,  596,  596,
123869  /*   210 */   507,  497,  441,  391,  353,  156,  156,  857,  353,  857,
123870  /*   220 */   735,  813,  639,  715,  156,  332,  715,  715,  496,  419,
123871  /*   230 */   646, 1357, 1184, 1184, 1335, 1335, 1184, 1341, 1260, 1144,
123872  /*   240 */  1346, 1346, 1346, 1346, 1184, 1306, 1144, 1341, 1260, 1260,
123873  /*   250 */  1144, 1184, 1306, 1206, 1284, 1184, 1184, 1306, 1184, 1306,
123874  /*   260 */  1184, 1306, 1262, 1207, 1207, 1207, 1274, 1262, 1207, 1217,
123875  /*   270 */  1207, 1274, 1207, 1207, 1185, 1200, 1185, 1200, 1185, 1200,
123876  /*   280 */  1184, 1184, 1161, 1262, 1202, 1202, 1262, 1154, 1155, 1147,
123877  /*   290 */  1152, 1144, 1241, 1239, 1250, 1250, 1254, 1254, 1254, 1254,
123878  /*   300 */   -86,  -86,  -86,  -86,  -86,  -86, 1068,  304,  526,  249,
123879  /*   310 */   408,  -83,  434,  812,   27,  811,  807,  802,  751,  589,
123880  /*   320 */   651,  163,  131,  674,  366,  450,  299,  148,   23,  102,
123881  /*   330 */   229,  -21, 1245, 1244, 1222, 1099, 1228, 1172, 1223, 1215,
123882  /*   340 */  1213, 1115, 1106, 1123, 1110, 1209, 1105, 1212, 1226, 1098,
123883  /*   350 */  1089, 1140, 1139, 1104, 1189, 1178, 1094, 1211, 1205, 1187,
123884  /*   360 */  1101, 1071, 1153, 1175, 1146, 1138, 1151, 1091, 1164, 1165,
123885  /*   370 */  1163, 1069, 1072, 1148, 1112, 1134, 1127, 1129, 1126, 1092,
123886  /*   380 */  1114, 1118, 1088, 1090, 1093, 1087, 1084,  987, 1079, 1077,
123887  /*   390 */  1074, 1065,  924, 1021, 1014, 1004, 1006,  819,  739,  896,
123888  /*   400 */   855,  804,  739,  740,  736,  690,  654,  665,  618,  582,
123889  /*   410 */   568,  528,  554,  379,  532,  479,  455,  379,  432,  371,
123890  /*   420 */   341,   28,  338,  116,  -11,  -57,  -85,    7,   -8,    3,
123891 };
123892 #define YY_REDUCE_USE_DFLT (-110)
123893 #define YY_REDUCE_COUNT (305)
123894 #define YY_REDUCE_MIN   (-109)
123895 #define YY_REDUCE_MAX   (1323)
123896 static const short yy_reduce_ofst[] = {
123897  /*     0 */   238,  954,  213,  289,  310,  234,  144,  317, -109,  382,
123898  /*    10 */   377,  303,  461,  389,  378,  368,  302,  294,  253,  395,
123899  /*    20 */   293,  324,  403,  403,  403,  403,  403,  403,  403,  403,
123900  /*    30 */   403,  403,  403,  403,  403,  403,  403,  403,  403,  403,
123901  /*    40 */   403,  403,  403,  403,  403,  403,  403,  403,  403,  403,
123902  /*    50 */   403, 1022, 1012, 1005,  998,  963,  961,  959,  957,  950,
123903  /*    60 */   947,  930,  912,  873,  861,  823,  810,  771,  759,  720,
123904  /*    70 */   708,  670,  657,  619,  614,  612,  610,  608,  606,  604,
123905  /*    80 */   598,  595,  593,  580,  542,  540,  537,  535,  533,  531,
123906  /*    90 */   529,  527,  503,  386,  403,  403,  403,  403,  403,  403,
123907  /*   100 */   403,  403,  403,   95,  447,   82,  334,  504,  467,  403,
123908  /*   110 */   477,  464,  403,  403,  403,  403,  860,  747,  744,  785,
123909  /*   120 */   638,  638,  926,  891,  900,  899,  887,  844,  840,  835,
123910  /*   130 */   848,  830,  843,  829,  792,  839,  826,  737,  838,  795,
123911  /*   140 */   789,   47,  734,  530,  696,  777,  711,  677,  733,  730,
123912  /*   150 */   729,  728,  727,  627,  448,   64,  187, 1305, 1302, 1252,
123913  /*   160 */  1290, 1273, 1323, 1322, 1321, 1319, 1318, 1316, 1315, 1314,
123914  /*   170 */  1313, 1312, 1311, 1310, 1308, 1307, 1304, 1303, 1301, 1298,
123915  /*   180 */  1294, 1292, 1289, 1266, 1264, 1259, 1288, 1287, 1238, 1285,
123916  /*   190 */  1281, 1280, 1279, 1278, 1251, 1277, 1276, 1275, 1273, 1268,
123917  /*   200 */  1267, 1265, 1263, 1261, 1257, 1248, 1237, 1247, 1246, 1243,
123918  /*   210 */  1238, 1240, 1235, 1249, 1234, 1233, 1230, 1220, 1214, 1210,
123919  /*   220 */  1225, 1219, 1232, 1231, 1197, 1195, 1227, 1224, 1201, 1208,
123920  /*   230 */  1242, 1137, 1236, 1229, 1193, 1181, 1221, 1177, 1196, 1179,
123921  /*   240 */  1191, 1190, 1186, 1182, 1218, 1216, 1176, 1162, 1183, 1180,
123922  /*   250 */  1160, 1199, 1203, 1133, 1095, 1198, 1194, 1188, 1192, 1171,
123923  /*   260 */  1169, 1168, 1173, 1174, 1166, 1159, 1141, 1170, 1158, 1167,
123924  /*   270 */  1157, 1132, 1145, 1143, 1124, 1128, 1103, 1102, 1100, 1096,
123925  /*   280 */  1150, 1149, 1085, 1125, 1080, 1064, 1120, 1097, 1082, 1078,
123926  /*   290 */  1073, 1067, 1109, 1107, 1119, 1117, 1116, 1113, 1111, 1108,
123927  /*   300 */  1007, 1000, 1002, 1076, 1075, 1081,
123928 };
123929 static const YYACTIONTYPE yy_default[] = {
123930  /*     0 */   647,  964,  964,  964,  878,  878,  969,  964,  774,  802,
123931  /*    10 */   802,  938,  969,  969,  969,  876,  969,  969,  969,  964,
123932  /*    20 */   969,  778,  808,  969,  969,  969,  969,  969,  969,  969,
123933  /*    30 */   969,  937,  939,  816,  815,  918,  789,  813,  806,  810,
123934  /*    40 */   879,  872,  873,  871,  875,  880,  969,  809,  841,  856,
123935  /*    50 */   840,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123936  /*    60 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123937  /*    70 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123938  /*    80 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123939  /*    90 */   969,  969,  969,  969,  850,  855,  862,  854,  851,  843,
123940  /*   100 */   842,  844,  845,  969,  969,  673,  739,  969,  969,  846,
123941  /*   110 */   969,  685,  847,  859,  858,  857,  680,  969,  969,  969,
123942  /*   120 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123943  /*   130 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123944  /*   140 */   969,  969,  969,  969,  647,  964,  969,  969,  964,  964,
123945  /*   150 */   964,  964,  964,  964,  956,  778,  768,  969,  969,  969,
123946  /*   160 */   969,  969,  969,  969,  969,  969,  969,  944,  942,  969,
123947  /*   170 */   891,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123948  /*   180 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123949  /*   190 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123950  /*   200 */   969,  969,  969,  969,  653,  969,  911,  774,  774,  774,
123951  /*   210 */   776,  754,  766,  655,  812,  791,  791,  923,  812,  923,
123952  /*   220 */   710,  733,  707,  802,  791,  874,  802,  802,  775,  766,
123953  /*   230 */   969,  949,  782,  782,  941,  941,  782,  821,  743,  812,
123954  /*   240 */   750,  750,  750,  750,  782,  670,  812,  821,  743,  743,
123955  /*   250 */   812,  782,  670,  917,  915,  782,  782,  670,  782,  670,
123956  /*   260 */   782,  670,  884,  741,  741,  741,  725,  884,  741,  710,
123957  /*   270 */   741,  725,  741,  741,  795,  790,  795,  790,  795,  790,
123958  /*   280 */   782,  782,  969,  884,  888,  888,  884,  807,  796,  805,
123959  /*   290 */   803,  812,  676,  728,  663,  663,  652,  652,  652,  652,
123960  /*   300 */   961,  961,  956,  712,  712,  695,  969,  969,  969,  969,
123961  /*   310 */   969,  969,  687,  969,  893,  969,  969,  969,  969,  969,
123962  /*   320 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123963  /*   330 */   969,  828,  969,  648,  951,  969,  969,  948,  969,  969,
123964  /*   340 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123965  /*   350 */   969,  969,  969,  969,  969,  969,  921,  969,  969,  969,
123966  /*   360 */   969,  969,  969,  914,  913,  969,  969,  969,  969,  969,
123967  /*   370 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123968  /*   380 */   969,  969,  969,  969,  969,  969,  969,  757,  969,  969,
123969  /*   390 */   969,  761,  969,  969,  969,  969,  969,  969,  804,  969,
123970  /*   400 */   797,  969,  877,  969,  969,  969,  969,  969,  969,  969,
123971  /*   410 */   969,  969,  969,  966,  969,  969,  969,  965,  969,  969,
123972  /*   420 */   969,  969,  969,  830,  969,  829,  833,  969,  661,  969,
123973  /*   430 */   644,  649,  960,  963,  962,  959,  958,  957,  952,  950,
123974  /*   440 */   947,  946,  945,  943,  940,  936,  897,  895,  902,  901,
123975  /*   450 */   900,  899,  898,  896,  894,  892,  818,  817,  814,  811,
123976  /*   460 */   753,  935,  890,  752,  749,  748,  669,  953,  920,  929,
123977  /*   470 */   928,  927,  822,  926,  925,  924,  922,  919,  906,  820,
123978  /*   480 */   819,  744,  882,  881,  672,  910,  909,  908,  912,  916,
123979  /*   490 */   907,  784,  751,  671,  668,  675,  679,  731,  732,  740,
123980  /*   500 */   738,  737,  736,  735,  734,  730,  681,  686,  724,  709,
123981  /*   510 */   708,  717,  716,  722,  721,  720,  719,  718,  715,  714,
123982  /*   520 */   713,  706,  705,  711,  704,  727,  726,  723,  703,  747,
123983  /*   530 */   746,  745,  742,  702,  701,  700,  833,  699,  698,  838,
123984  /*   540 */   837,  866,  826,  755,  759,  758,  762,  763,  771,  770,
123985  /*   550 */   769,  780,  781,  793,  792,  824,  823,  794,  779,  773,
123986  /*   560 */   772,  788,  787,  786,  785,  777,  767,  799,  798,  868,
123987  /*   570 */   783,  867,  865,  934,  933,  932,  931,  930,  870,  967,
123988  /*   580 */   968,  887,  889,  886,  801,  800,  885,  869,  839,  836,
123989  /*   590 */   690,  691,  905,  904,  903,  693,  692,  689,  688,  863,
123990  /*   600 */   860,  852,  864,  861,  853,  849,  848,  834,  832,  831,
123991  /*   610 */   827,  835,  760,  756,  825,  765,  764,  697,  696,  694,
123992  /*   620 */   678,  677,  674,  667,  665,  664,  666,  662,  660,  659,
123993  /*   630 */   658,  657,  656,  684,  683,  682,  654,  651,  650,  646,
123994  /*   640 */   645,  643,
123995 };
123996 
123997 /* The next table maps tokens into fallback tokens.  If a construct
123998 ** like the following:
123999 **
124000 **      %fallback ID X Y Z.
124001 **
124002 ** appears in the grammar, then ID becomes a fallback token for X, Y,
124003 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
124004 ** but it does not parse, the type of the token is changed to ID and
124005 ** the parse is retried before an error is thrown.
124006 */
124007 #ifdef YYFALLBACK
124008 static const YYCODETYPE yyFallback[] = {
124009     0,  /*          $ => nothing */
124010     0,  /*       SEMI => nothing */
124011    27,  /*    EXPLAIN => ID */
124012    27,  /*      QUERY => ID */
124013    27,  /*       PLAN => ID */
124014    27,  /*      BEGIN => ID */
124015     0,  /* TRANSACTION => nothing */
124016    27,  /*   DEFERRED => ID */
124017    27,  /*  IMMEDIATE => ID */
124018    27,  /*  EXCLUSIVE => ID */
124019     0,  /*     COMMIT => nothing */
124020    27,  /*        END => ID */
124021    27,  /*   ROLLBACK => ID */
124022    27,  /*  SAVEPOINT => ID */
124023    27,  /*    RELEASE => ID */
124024     0,  /*         TO => nothing */
124025     0,  /*      TABLE => nothing */
124026     0,  /*     CREATE => nothing */
124027    27,  /*         IF => ID */
124028     0,  /*        NOT => nothing */
124029     0,  /*     EXISTS => nothing */
124030    27,  /*       TEMP => ID */
124031     0,  /*         LP => nothing */
124032     0,  /*         RP => nothing */
124033     0,  /*         AS => nothing */
124034    27,  /*    WITHOUT => ID */
124035     0,  /*      COMMA => nothing */
124036     0,  /*         ID => nothing */
124037     0,  /*    INDEXED => nothing */
124038    27,  /*      ABORT => ID */
124039    27,  /*     ACTION => ID */
124040    27,  /*      AFTER => ID */
124041    27,  /*    ANALYZE => ID */
124042    27,  /*        ASC => ID */
124043    27,  /*     ATTACH => ID */
124044    27,  /*     BEFORE => ID */
124045    27,  /*         BY => ID */
124046    27,  /*    CASCADE => ID */
124047    27,  /*       CAST => ID */
124048    27,  /*   COLUMNKW => ID */
124049    27,  /*   CONFLICT => ID */
124050    27,  /*   DATABASE => ID */
124051    27,  /*       DESC => ID */
124052    27,  /*     DETACH => ID */
124053    27,  /*       EACH => ID */
124054    27,  /*       FAIL => ID */
124055    27,  /*        FOR => ID */
124056    27,  /*     IGNORE => ID */
124057    27,  /*  INITIALLY => ID */
124058    27,  /*    INSTEAD => ID */
124059    27,  /*    LIKE_KW => ID */
124060    27,  /*      MATCH => ID */
124061    27,  /*         NO => ID */
124062    27,  /*        KEY => ID */
124063    27,  /*         OF => ID */
124064    27,  /*     OFFSET => ID */
124065    27,  /*     PRAGMA => ID */
124066    27,  /*      RAISE => ID */
124067    27,  /*  RECURSIVE => ID */
124068    27,  /*    REPLACE => ID */
124069    27,  /*   RESTRICT => ID */
124070    27,  /*        ROW => ID */
124071    27,  /*    TRIGGER => ID */
124072    27,  /*     VACUUM => ID */
124073    27,  /*       VIEW => ID */
124074    27,  /*    VIRTUAL => ID */
124075    27,  /*       WITH => ID */
124076    27,  /*    REINDEX => ID */
124077    27,  /*     RENAME => ID */
124078    27,  /*   CTIME_KW => ID */
124079 };
124080 #endif /* YYFALLBACK */
124081 
124082 /* The following structure represents a single element of the
124083 ** parser's stack.  Information stored includes:
124084 **
124085 **   +  The state number for the parser at this level of the stack.
124086 **
124087 **   +  The value of the token stored at this level of the stack.
124088 **      (In other words, the "major" token.)
124089 **
124090 **   +  The semantic value stored at this level of the stack.  This is
124091 **      the information used by the action routines in the grammar.
124092 **      It is sometimes called the "minor" token.
124093 */
124094 struct yyStackEntry {
124095   YYACTIONTYPE stateno;  /* The state-number */
124096   YYCODETYPE major;      /* The major token value.  This is the code
124097                          ** number for the token at this stack level */
124098   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
124099                          ** is the value of the token  */
124100 };
124101 typedef struct yyStackEntry yyStackEntry;
124102 
124103 /* The state of the parser is completely contained in an instance of
124104 ** the following structure */
124105 struct yyParser {
124106   int yyidx;                    /* Index of top element in stack */
124107 #ifdef YYTRACKMAXSTACKDEPTH
124108   int yyidxMax;                 /* Maximum value of yyidx */
124109 #endif
124110   int yyerrcnt;                 /* Shifts left before out of the error */
124111   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
124112 #if YYSTACKDEPTH<=0
124113   int yystksz;                  /* Current side of the stack */
124114   yyStackEntry *yystack;        /* The parser's stack */
124115 #else
124116   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
124117 #endif
124118 };
124119 typedef struct yyParser yyParser;
124120 
124121 #ifndef NDEBUG
124122 /* #include <stdio.h> */
124123 static FILE *yyTraceFILE = 0;
124124 static char *yyTracePrompt = 0;
124125 #endif /* NDEBUG */
124126 
124127 #ifndef NDEBUG
124128 /*
124129 ** Turn parser tracing on by giving a stream to which to write the trace
124130 ** and a prompt to preface each trace message.  Tracing is turned off
124131 ** by making either argument NULL
124132 **
124133 ** Inputs:
124134 ** <ul>
124135 ** <li> A FILE* to which trace output should be written.
124136 **      If NULL, then tracing is turned off.
124137 ** <li> A prefix string written at the beginning of every
124138 **      line of trace output.  If NULL, then tracing is
124139 **      turned off.
124140 ** </ul>
124141 **
124142 ** Outputs:
124143 ** None.
124144 */
124145 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
124146   yyTraceFILE = TraceFILE;
124147   yyTracePrompt = zTracePrompt;
124148   if( yyTraceFILE==0 ) yyTracePrompt = 0;
124149   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
124150 }
124151 #endif /* NDEBUG */
124152 
124153 #ifndef NDEBUG
124154 /* For tracing shifts, the names of all terminals and nonterminals
124155 ** are required.  The following table supplies these names */
124156 static const char *const yyTokenName[] = {
124157   "$",             "SEMI",          "EXPLAIN",       "QUERY",
124158   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
124159   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
124160   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
124161   "TABLE",         "CREATE",        "IF",            "NOT",
124162   "EXISTS",        "TEMP",          "LP",            "RP",
124163   "AS",            "WITHOUT",       "COMMA",         "ID",
124164   "INDEXED",       "ABORT",         "ACTION",        "AFTER",
124165   "ANALYZE",       "ASC",           "ATTACH",        "BEFORE",
124166   "BY",            "CASCADE",       "CAST",          "COLUMNKW",
124167   "CONFLICT",      "DATABASE",      "DESC",          "DETACH",
124168   "EACH",          "FAIL",          "FOR",           "IGNORE",
124169   "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",
124170   "NO",            "KEY",           "OF",            "OFFSET",
124171   "PRAGMA",        "RAISE",         "RECURSIVE",     "REPLACE",
124172   "RESTRICT",      "ROW",           "TRIGGER",       "VACUUM",
124173   "VIEW",          "VIRTUAL",       "WITH",          "REINDEX",
124174   "RENAME",        "CTIME_KW",      "ANY",           "OR",
124175   "AND",           "IS",            "BETWEEN",       "IN",
124176   "ISNULL",        "NOTNULL",       "NE",            "EQ",
124177   "GT",            "LE",            "LT",            "GE",
124178   "ESCAPE",        "BITAND",        "BITOR",         "LSHIFT",
124179   "RSHIFT",        "PLUS",          "MINUS",         "STAR",
124180   "SLASH",         "REM",           "CONCAT",        "COLLATE",
124181   "BITNOT",        "STRING",        "JOIN_KW",       "CONSTRAINT",
124182   "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",
124183   "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",
124184   "INSERT",        "DELETE",        "UPDATE",        "SET",
124185   "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",
124186   "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",
124187   "VALUES",        "DISTINCT",      "DOT",           "FROM",
124188   "JOIN",          "USING",         "ORDER",         "GROUP",
124189   "HAVING",        "LIMIT",         "WHERE",         "INTO",
124190   "INTEGER",       "FLOAT",         "BLOB",          "VARIABLE",
124191   "CASE",          "WHEN",          "THEN",          "ELSE",
124192   "INDEX",         "ALTER",         "ADD",           "error",
124193   "input",         "cmdlist",       "ecmd",          "explain",
124194   "cmdx",          "cmd",           "transtype",     "trans_opt",
124195   "nm",            "savepoint_opt",  "create_table",  "create_table_args",
124196   "createkw",      "temp",          "ifnotexists",   "dbnm",
124197   "columnlist",    "conslist_opt",  "table_options",  "select",
124198   "column",        "columnid",      "type",          "carglist",
124199   "typetoken",     "typename",      "signed",        "plus_num",
124200   "minus_num",     "ccons",         "term",          "expr",
124201   "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
124202   "refargs",       "defer_subclause",  "refarg",        "refact",
124203   "init_deferred_pred_opt",  "conslist",      "tconscomma",    "tcons",
124204   "idxlist",       "defer_subclause_opt",  "orconf",        "resolvetype",
124205   "raisetype",     "ifexists",      "fullname",      "selectnowith",
124206   "oneselect",     "with",          "multiselect_op",  "distinct",
124207   "selcollist",    "from",          "where_opt",     "groupby_opt",
124208   "having_opt",    "orderby_opt",   "limit_opt",     "values",
124209   "nexprlist",     "exprlist",      "sclp",          "as",
124210   "seltablist",    "stl_prefix",    "joinop",        "indexed_opt",
124211   "on_opt",        "using_opt",     "joinop2",       "idlist",
124212   "sortlist",      "setlist",       "insert_cmd",    "inscollist_opt",
124213   "likeop",        "between_op",    "in_op",         "case_operand",
124214   "case_exprlist",  "case_else",     "uniqueflag",    "collate",
124215   "nmnum",         "trigger_decl",  "trigger_cmd_list",  "trigger_time",
124216   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd",
124217   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",
124218   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist",
124219   "vtabarg",       "vtabargtoken",  "lp",            "anylist",
124220   "wqlist",
124221 };
124222 #endif /* NDEBUG */
124223 
124224 #ifndef NDEBUG
124225 /* For tracing reduce actions, the names of all rules are required.
124226 */
124227 static const char *const yyRuleName[] = {
124228  /*   0 */ "input ::= cmdlist",
124229  /*   1 */ "cmdlist ::= cmdlist ecmd",
124230  /*   2 */ "cmdlist ::= ecmd",
124231  /*   3 */ "ecmd ::= SEMI",
124232  /*   4 */ "ecmd ::= explain cmdx SEMI",
124233  /*   5 */ "explain ::=",
124234  /*   6 */ "explain ::= EXPLAIN",
124235  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
124236  /*   8 */ "cmdx ::= cmd",
124237  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
124238  /*  10 */ "trans_opt ::=",
124239  /*  11 */ "trans_opt ::= TRANSACTION",
124240  /*  12 */ "trans_opt ::= TRANSACTION nm",
124241  /*  13 */ "transtype ::=",
124242  /*  14 */ "transtype ::= DEFERRED",
124243  /*  15 */ "transtype ::= IMMEDIATE",
124244  /*  16 */ "transtype ::= EXCLUSIVE",
124245  /*  17 */ "cmd ::= COMMIT trans_opt",
124246  /*  18 */ "cmd ::= END trans_opt",
124247  /*  19 */ "cmd ::= ROLLBACK trans_opt",
124248  /*  20 */ "savepoint_opt ::= SAVEPOINT",
124249  /*  21 */ "savepoint_opt ::=",
124250  /*  22 */ "cmd ::= SAVEPOINT nm",
124251  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
124252  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
124253  /*  25 */ "cmd ::= create_table create_table_args",
124254  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
124255  /*  27 */ "createkw ::= CREATE",
124256  /*  28 */ "ifnotexists ::=",
124257  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
124258  /*  30 */ "temp ::= TEMP",
124259  /*  31 */ "temp ::=",
124260  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
124261  /*  33 */ "create_table_args ::= AS select",
124262  /*  34 */ "table_options ::=",
124263  /*  35 */ "table_options ::= WITHOUT nm",
124264  /*  36 */ "columnlist ::= columnlist COMMA column",
124265  /*  37 */ "columnlist ::= column",
124266  /*  38 */ "column ::= columnid type carglist",
124267  /*  39 */ "columnid ::= nm",
124268  /*  40 */ "nm ::= ID|INDEXED",
124269  /*  41 */ "nm ::= STRING",
124270  /*  42 */ "nm ::= JOIN_KW",
124271  /*  43 */ "type ::=",
124272  /*  44 */ "type ::= typetoken",
124273  /*  45 */ "typetoken ::= typename",
124274  /*  46 */ "typetoken ::= typename LP signed RP",
124275  /*  47 */ "typetoken ::= typename LP signed COMMA signed RP",
124276  /*  48 */ "typename ::= ID|STRING",
124277  /*  49 */ "typename ::= typename ID|STRING",
124278  /*  50 */ "signed ::= plus_num",
124279  /*  51 */ "signed ::= minus_num",
124280  /*  52 */ "carglist ::= carglist ccons",
124281  /*  53 */ "carglist ::=",
124282  /*  54 */ "ccons ::= CONSTRAINT nm",
124283  /*  55 */ "ccons ::= DEFAULT term",
124284  /*  56 */ "ccons ::= DEFAULT LP expr RP",
124285  /*  57 */ "ccons ::= DEFAULT PLUS term",
124286  /*  58 */ "ccons ::= DEFAULT MINUS term",
124287  /*  59 */ "ccons ::= DEFAULT ID|INDEXED",
124288  /*  60 */ "ccons ::= NULL onconf",
124289  /*  61 */ "ccons ::= NOT NULL onconf",
124290  /*  62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
124291  /*  63 */ "ccons ::= UNIQUE onconf",
124292  /*  64 */ "ccons ::= CHECK LP expr RP",
124293  /*  65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
124294  /*  66 */ "ccons ::= defer_subclause",
124295  /*  67 */ "ccons ::= COLLATE ID|STRING",
124296  /*  68 */ "autoinc ::=",
124297  /*  69 */ "autoinc ::= AUTOINCR",
124298  /*  70 */ "refargs ::=",
124299  /*  71 */ "refargs ::= refargs refarg",
124300  /*  72 */ "refarg ::= MATCH nm",
124301  /*  73 */ "refarg ::= ON INSERT refact",
124302  /*  74 */ "refarg ::= ON DELETE refact",
124303  /*  75 */ "refarg ::= ON UPDATE refact",
124304  /*  76 */ "refact ::= SET NULL",
124305  /*  77 */ "refact ::= SET DEFAULT",
124306  /*  78 */ "refact ::= CASCADE",
124307  /*  79 */ "refact ::= RESTRICT",
124308  /*  80 */ "refact ::= NO ACTION",
124309  /*  81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
124310  /*  82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
124311  /*  83 */ "init_deferred_pred_opt ::=",
124312  /*  84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
124313  /*  85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
124314  /*  86 */ "conslist_opt ::=",
124315  /*  87 */ "conslist_opt ::= COMMA conslist",
124316  /*  88 */ "conslist ::= conslist tconscomma tcons",
124317  /*  89 */ "conslist ::= tcons",
124318  /*  90 */ "tconscomma ::= COMMA",
124319  /*  91 */ "tconscomma ::=",
124320  /*  92 */ "tcons ::= CONSTRAINT nm",
124321  /*  93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
124322  /*  94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
124323  /*  95 */ "tcons ::= CHECK LP expr RP onconf",
124324  /*  96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
124325  /*  97 */ "defer_subclause_opt ::=",
124326  /*  98 */ "defer_subclause_opt ::= defer_subclause",
124327  /*  99 */ "onconf ::=",
124328  /* 100 */ "onconf ::= ON CONFLICT resolvetype",
124329  /* 101 */ "orconf ::=",
124330  /* 102 */ "orconf ::= OR resolvetype",
124331  /* 103 */ "resolvetype ::= raisetype",
124332  /* 104 */ "resolvetype ::= IGNORE",
124333  /* 105 */ "resolvetype ::= REPLACE",
124334  /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
124335  /* 107 */ "ifexists ::= IF EXISTS",
124336  /* 108 */ "ifexists ::=",
124337  /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
124338  /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
124339  /* 111 */ "cmd ::= select",
124340  /* 112 */ "select ::= with selectnowith",
124341  /* 113 */ "selectnowith ::= oneselect",
124342  /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
124343  /* 115 */ "multiselect_op ::= UNION",
124344  /* 116 */ "multiselect_op ::= UNION ALL",
124345  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
124346  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
124347  /* 119 */ "oneselect ::= values",
124348  /* 120 */ "values ::= VALUES LP nexprlist RP",
124349  /* 121 */ "values ::= values COMMA LP exprlist RP",
124350  /* 122 */ "distinct ::= DISTINCT",
124351  /* 123 */ "distinct ::= ALL",
124352  /* 124 */ "distinct ::=",
124353  /* 125 */ "sclp ::= selcollist COMMA",
124354  /* 126 */ "sclp ::=",
124355  /* 127 */ "selcollist ::= sclp expr as",
124356  /* 128 */ "selcollist ::= sclp STAR",
124357  /* 129 */ "selcollist ::= sclp nm DOT STAR",
124358  /* 130 */ "as ::= AS nm",
124359  /* 131 */ "as ::= ID|STRING",
124360  /* 132 */ "as ::=",
124361  /* 133 */ "from ::=",
124362  /* 134 */ "from ::= FROM seltablist",
124363  /* 135 */ "stl_prefix ::= seltablist joinop",
124364  /* 136 */ "stl_prefix ::=",
124365  /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
124366  /* 138 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
124367  /* 139 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
124368  /* 140 */ "dbnm ::=",
124369  /* 141 */ "dbnm ::= DOT nm",
124370  /* 142 */ "fullname ::= nm dbnm",
124371  /* 143 */ "joinop ::= COMMA|JOIN",
124372  /* 144 */ "joinop ::= JOIN_KW JOIN",
124373  /* 145 */ "joinop ::= JOIN_KW nm JOIN",
124374  /* 146 */ "joinop ::= JOIN_KW nm nm JOIN",
124375  /* 147 */ "on_opt ::= ON expr",
124376  /* 148 */ "on_opt ::=",
124377  /* 149 */ "indexed_opt ::=",
124378  /* 150 */ "indexed_opt ::= INDEXED BY nm",
124379  /* 151 */ "indexed_opt ::= NOT INDEXED",
124380  /* 152 */ "using_opt ::= USING LP idlist RP",
124381  /* 153 */ "using_opt ::=",
124382  /* 154 */ "orderby_opt ::=",
124383  /* 155 */ "orderby_opt ::= ORDER BY sortlist",
124384  /* 156 */ "sortlist ::= sortlist COMMA expr sortorder",
124385  /* 157 */ "sortlist ::= expr sortorder",
124386  /* 158 */ "sortorder ::= ASC",
124387  /* 159 */ "sortorder ::= DESC",
124388  /* 160 */ "sortorder ::=",
124389  /* 161 */ "groupby_opt ::=",
124390  /* 162 */ "groupby_opt ::= GROUP BY nexprlist",
124391  /* 163 */ "having_opt ::=",
124392  /* 164 */ "having_opt ::= HAVING expr",
124393  /* 165 */ "limit_opt ::=",
124394  /* 166 */ "limit_opt ::= LIMIT expr",
124395  /* 167 */ "limit_opt ::= LIMIT expr OFFSET expr",
124396  /* 168 */ "limit_opt ::= LIMIT expr COMMA expr",
124397  /* 169 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
124398  /* 170 */ "where_opt ::=",
124399  /* 171 */ "where_opt ::= WHERE expr",
124400  /* 172 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
124401  /* 173 */ "setlist ::= setlist COMMA nm EQ expr",
124402  /* 174 */ "setlist ::= nm EQ expr",
124403  /* 175 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt select",
124404  /* 176 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
124405  /* 177 */ "insert_cmd ::= INSERT orconf",
124406  /* 178 */ "insert_cmd ::= REPLACE",
124407  /* 179 */ "inscollist_opt ::=",
124408  /* 180 */ "inscollist_opt ::= LP idlist RP",
124409  /* 181 */ "idlist ::= idlist COMMA nm",
124410  /* 182 */ "idlist ::= nm",
124411  /* 183 */ "expr ::= term",
124412  /* 184 */ "expr ::= LP expr RP",
124413  /* 185 */ "term ::= NULL",
124414  /* 186 */ "expr ::= ID|INDEXED",
124415  /* 187 */ "expr ::= JOIN_KW",
124416  /* 188 */ "expr ::= nm DOT nm",
124417  /* 189 */ "expr ::= nm DOT nm DOT nm",
124418  /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
124419  /* 191 */ "term ::= STRING",
124420  /* 192 */ "expr ::= VARIABLE",
124421  /* 193 */ "expr ::= expr COLLATE ID|STRING",
124422  /* 194 */ "expr ::= CAST LP expr AS typetoken RP",
124423  /* 195 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
124424  /* 196 */ "expr ::= ID|INDEXED LP STAR RP",
124425  /* 197 */ "term ::= CTIME_KW",
124426  /* 198 */ "expr ::= expr AND expr",
124427  /* 199 */ "expr ::= expr OR expr",
124428  /* 200 */ "expr ::= expr LT|GT|GE|LE expr",
124429  /* 201 */ "expr ::= expr EQ|NE expr",
124430  /* 202 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
124431  /* 203 */ "expr ::= expr PLUS|MINUS expr",
124432  /* 204 */ "expr ::= expr STAR|SLASH|REM expr",
124433  /* 205 */ "expr ::= expr CONCAT expr",
124434  /* 206 */ "likeop ::= LIKE_KW|MATCH",
124435  /* 207 */ "likeop ::= NOT LIKE_KW|MATCH",
124436  /* 208 */ "expr ::= expr likeop expr",
124437  /* 209 */ "expr ::= expr likeop expr ESCAPE expr",
124438  /* 210 */ "expr ::= expr ISNULL|NOTNULL",
124439  /* 211 */ "expr ::= expr NOT NULL",
124440  /* 212 */ "expr ::= expr IS expr",
124441  /* 213 */ "expr ::= expr IS NOT expr",
124442  /* 214 */ "expr ::= NOT expr",
124443  /* 215 */ "expr ::= BITNOT expr",
124444  /* 216 */ "expr ::= MINUS expr",
124445  /* 217 */ "expr ::= PLUS expr",
124446  /* 218 */ "between_op ::= BETWEEN",
124447  /* 219 */ "between_op ::= NOT BETWEEN",
124448  /* 220 */ "expr ::= expr between_op expr AND expr",
124449  /* 221 */ "in_op ::= IN",
124450  /* 222 */ "in_op ::= NOT IN",
124451  /* 223 */ "expr ::= expr in_op LP exprlist RP",
124452  /* 224 */ "expr ::= LP select RP",
124453  /* 225 */ "expr ::= expr in_op LP select RP",
124454  /* 226 */ "expr ::= expr in_op nm dbnm",
124455  /* 227 */ "expr ::= EXISTS LP select RP",
124456  /* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
124457  /* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
124458  /* 230 */ "case_exprlist ::= WHEN expr THEN expr",
124459  /* 231 */ "case_else ::= ELSE expr",
124460  /* 232 */ "case_else ::=",
124461  /* 233 */ "case_operand ::= expr",
124462  /* 234 */ "case_operand ::=",
124463  /* 235 */ "exprlist ::= nexprlist",
124464  /* 236 */ "exprlist ::=",
124465  /* 237 */ "nexprlist ::= nexprlist COMMA expr",
124466  /* 238 */ "nexprlist ::= expr",
124467  /* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
124468  /* 240 */ "uniqueflag ::= UNIQUE",
124469  /* 241 */ "uniqueflag ::=",
124470  /* 242 */ "idxlist_opt ::=",
124471  /* 243 */ "idxlist_opt ::= LP idxlist RP",
124472  /* 244 */ "idxlist ::= idxlist COMMA nm collate sortorder",
124473  /* 245 */ "idxlist ::= nm collate sortorder",
124474  /* 246 */ "collate ::=",
124475  /* 247 */ "collate ::= COLLATE ID|STRING",
124476  /* 248 */ "cmd ::= DROP INDEX ifexists fullname",
124477  /* 249 */ "cmd ::= VACUUM",
124478  /* 250 */ "cmd ::= VACUUM nm",
124479  /* 251 */ "cmd ::= PRAGMA nm dbnm",
124480  /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
124481  /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
124482  /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
124483  /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
124484  /* 256 */ "nmnum ::= plus_num",
124485  /* 257 */ "nmnum ::= nm",
124486  /* 258 */ "nmnum ::= ON",
124487  /* 259 */ "nmnum ::= DELETE",
124488  /* 260 */ "nmnum ::= DEFAULT",
124489  /* 261 */ "plus_num ::= PLUS INTEGER|FLOAT",
124490  /* 262 */ "plus_num ::= INTEGER|FLOAT",
124491  /* 263 */ "minus_num ::= MINUS INTEGER|FLOAT",
124492  /* 264 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
124493  /* 265 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
124494  /* 266 */ "trigger_time ::= BEFORE",
124495  /* 267 */ "trigger_time ::= AFTER",
124496  /* 268 */ "trigger_time ::= INSTEAD OF",
124497  /* 269 */ "trigger_time ::=",
124498  /* 270 */ "trigger_event ::= DELETE|INSERT",
124499  /* 271 */ "trigger_event ::= UPDATE",
124500  /* 272 */ "trigger_event ::= UPDATE OF idlist",
124501  /* 273 */ "foreach_clause ::=",
124502  /* 274 */ "foreach_clause ::= FOR EACH ROW",
124503  /* 275 */ "when_clause ::=",
124504  /* 276 */ "when_clause ::= WHEN expr",
124505  /* 277 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
124506  /* 278 */ "trigger_cmd_list ::= trigger_cmd SEMI",
124507  /* 279 */ "trnm ::= nm",
124508  /* 280 */ "trnm ::= nm DOT nm",
124509  /* 281 */ "tridxby ::=",
124510  /* 282 */ "tridxby ::= INDEXED BY nm",
124511  /* 283 */ "tridxby ::= NOT INDEXED",
124512  /* 284 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
124513  /* 285 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
124514  /* 286 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
124515  /* 287 */ "trigger_cmd ::= select",
124516  /* 288 */ "expr ::= RAISE LP IGNORE RP",
124517  /* 289 */ "expr ::= RAISE LP raisetype COMMA nm RP",
124518  /* 290 */ "raisetype ::= ROLLBACK",
124519  /* 291 */ "raisetype ::= ABORT",
124520  /* 292 */ "raisetype ::= FAIL",
124521  /* 293 */ "cmd ::= DROP TRIGGER ifexists fullname",
124522  /* 294 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
124523  /* 295 */ "cmd ::= DETACH database_kw_opt expr",
124524  /* 296 */ "key_opt ::=",
124525  /* 297 */ "key_opt ::= KEY expr",
124526  /* 298 */ "database_kw_opt ::= DATABASE",
124527  /* 299 */ "database_kw_opt ::=",
124528  /* 300 */ "cmd ::= REINDEX",
124529  /* 301 */ "cmd ::= REINDEX nm dbnm",
124530  /* 302 */ "cmd ::= ANALYZE",
124531  /* 303 */ "cmd ::= ANALYZE nm dbnm",
124532  /* 304 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
124533  /* 305 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
124534  /* 306 */ "add_column_fullname ::= fullname",
124535  /* 307 */ "kwcolumn_opt ::=",
124536  /* 308 */ "kwcolumn_opt ::= COLUMNKW",
124537  /* 309 */ "cmd ::= create_vtab",
124538  /* 310 */ "cmd ::= create_vtab LP vtabarglist RP",
124539  /* 311 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
124540  /* 312 */ "vtabarglist ::= vtabarg",
124541  /* 313 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
124542  /* 314 */ "vtabarg ::=",
124543  /* 315 */ "vtabarg ::= vtabarg vtabargtoken",
124544  /* 316 */ "vtabargtoken ::= ANY",
124545  /* 317 */ "vtabargtoken ::= lp anylist RP",
124546  /* 318 */ "lp ::= LP",
124547  /* 319 */ "anylist ::=",
124548  /* 320 */ "anylist ::= anylist LP anylist RP",
124549  /* 321 */ "anylist ::= anylist ANY",
124550  /* 322 */ "with ::=",
124551  /* 323 */ "with ::= WITH wqlist",
124552  /* 324 */ "with ::= WITH RECURSIVE wqlist",
124553  /* 325 */ "wqlist ::= nm idxlist_opt AS LP select RP",
124554  /* 326 */ "wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP",
124555 };
124556 #endif /* NDEBUG */
124557 
124558 
124559 #if YYSTACKDEPTH<=0
124560 /*
124561 ** Try to increase the size of the parser stack.
124562 */
124563 static void yyGrowStack(yyParser *p){
124564   int newSize;
124565   yyStackEntry *pNew;
124566 
124567   newSize = p->yystksz*2 + 100;
124568   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
124569   if( pNew ){
124570     p->yystack = pNew;
124571     p->yystksz = newSize;
124572 #ifndef NDEBUG
124573     if( yyTraceFILE ){
124574       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
124575               yyTracePrompt, p->yystksz);
124576     }
124577 #endif
124578   }
124579 }
124580 #endif
124581 
124582 /*
124583 ** This function allocates a new parser.
124584 ** The only argument is a pointer to a function which works like
124585 ** malloc.
124586 **
124587 ** Inputs:
124588 ** A pointer to the function used to allocate memory.
124589 **
124590 ** Outputs:
124591 ** A pointer to a parser.  This pointer is used in subsequent calls
124592 ** to sqlite3Parser and sqlite3ParserFree.
124593 */
124594 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(u64)){
124595   yyParser *pParser;
124596   pParser = (yyParser*)(*mallocProc)( (u64)sizeof(yyParser) );
124597   if( pParser ){
124598     pParser->yyidx = -1;
124599 #ifdef YYTRACKMAXSTACKDEPTH
124600     pParser->yyidxMax = 0;
124601 #endif
124602 #if YYSTACKDEPTH<=0
124603     pParser->yystack = NULL;
124604     pParser->yystksz = 0;
124605     yyGrowStack(pParser);
124606 #endif
124607   }
124608   return pParser;
124609 }
124610 
124611 /* The following function deletes the value associated with a
124612 ** symbol.  The symbol can be either a terminal or nonterminal.
124613 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
124614 ** the value.
124615 */
124616 static void yy_destructor(
124617   yyParser *yypParser,    /* The parser */
124618   YYCODETYPE yymajor,     /* Type code for object to destroy */
124619   YYMINORTYPE *yypminor   /* The object to be destroyed */
124620 ){
124621   sqlite3ParserARG_FETCH;
124622   switch( yymajor ){
124623     /* Here is inserted the actions which take place when a
124624     ** terminal or non-terminal is destroyed.  This can happen
124625     ** when the symbol is popped from the stack during a
124626     ** reduce or during error processing or when a parser is
124627     ** being destroyed before it is finished parsing.
124628     **
124629     ** Note: during a reduce, the only symbols destroyed are those
124630     ** which appear on the RHS of the rule, but which are not used
124631     ** inside the C code.
124632     */
124633     case 163: /* select */
124634     case 195: /* selectnowith */
124635     case 196: /* oneselect */
124636     case 207: /* values */
124637 {
124638 sqlite3SelectDelete(pParse->db, (yypminor->yy3));
124639 }
124640       break;
124641     case 174: /* term */
124642     case 175: /* expr */
124643 {
124644 sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
124645 }
124646       break;
124647     case 179: /* idxlist_opt */
124648     case 188: /* idxlist */
124649     case 200: /* selcollist */
124650     case 203: /* groupby_opt */
124651     case 205: /* orderby_opt */
124652     case 208: /* nexprlist */
124653     case 209: /* exprlist */
124654     case 210: /* sclp */
124655     case 220: /* sortlist */
124656     case 221: /* setlist */
124657     case 228: /* case_exprlist */
124658 {
124659 sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
124660 }
124661       break;
124662     case 194: /* fullname */
124663     case 201: /* from */
124664     case 212: /* seltablist */
124665     case 213: /* stl_prefix */
124666 {
124667 sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
124668 }
124669       break;
124670     case 197: /* with */
124671     case 252: /* wqlist */
124672 {
124673 sqlite3WithDelete(pParse->db, (yypminor->yy59));
124674 }
124675       break;
124676     case 202: /* where_opt */
124677     case 204: /* having_opt */
124678     case 216: /* on_opt */
124679     case 227: /* case_operand */
124680     case 229: /* case_else */
124681     case 238: /* when_clause */
124682     case 243: /* key_opt */
124683 {
124684 sqlite3ExprDelete(pParse->db, (yypminor->yy132));
124685 }
124686       break;
124687     case 217: /* using_opt */
124688     case 219: /* idlist */
124689     case 223: /* inscollist_opt */
124690 {
124691 sqlite3IdListDelete(pParse->db, (yypminor->yy408));
124692 }
124693       break;
124694     case 234: /* trigger_cmd_list */
124695     case 239: /* trigger_cmd */
124696 {
124697 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
124698 }
124699       break;
124700     case 236: /* trigger_event */
124701 {
124702 sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
124703 }
124704       break;
124705     default:  break;   /* If no destructor action specified: do nothing */
124706   }
124707 }
124708 
124709 /*
124710 ** Pop the parser's stack once.
124711 **
124712 ** If there is a destructor routine associated with the token which
124713 ** is popped from the stack, then call it.
124714 **
124715 ** Return the major token number for the symbol popped.
124716 */
124717 static int yy_pop_parser_stack(yyParser *pParser){
124718   YYCODETYPE yymajor;
124719   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
124720 
124721   /* There is no mechanism by which the parser stack can be popped below
124722   ** empty in SQLite.  */
124723   if( NEVER(pParser->yyidx<0) ) return 0;
124724 #ifndef NDEBUG
124725   if( yyTraceFILE && pParser->yyidx>=0 ){
124726     fprintf(yyTraceFILE,"%sPopping %s\n",
124727       yyTracePrompt,
124728       yyTokenName[yytos->major]);
124729   }
124730 #endif
124731   yymajor = yytos->major;
124732   yy_destructor(pParser, yymajor, &yytos->minor);
124733   pParser->yyidx--;
124734   return yymajor;
124735 }
124736 
124737 /*
124738 ** Deallocate and destroy a parser.  Destructors are all called for
124739 ** all stack elements before shutting the parser down.
124740 **
124741 ** Inputs:
124742 ** <ul>
124743 ** <li>  A pointer to the parser.  This should be a pointer
124744 **       obtained from sqlite3ParserAlloc.
124745 ** <li>  A pointer to a function used to reclaim memory obtained
124746 **       from malloc.
124747 ** </ul>
124748 */
124749 SQLITE_PRIVATE void sqlite3ParserFree(
124750   void *p,                    /* The parser to be deleted */
124751   void (*freeProc)(void*)     /* Function used to reclaim memory */
124752 ){
124753   yyParser *pParser = (yyParser*)p;
124754   /* In SQLite, we never try to destroy a parser that was not successfully
124755   ** created in the first place. */
124756   if( NEVER(pParser==0) ) return;
124757   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
124758 #if YYSTACKDEPTH<=0
124759   free(pParser->yystack);
124760 #endif
124761   (*freeProc)((void*)pParser);
124762 }
124763 
124764 /*
124765 ** Return the peak depth of the stack for a parser.
124766 */
124767 #ifdef YYTRACKMAXSTACKDEPTH
124768 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
124769   yyParser *pParser = (yyParser*)p;
124770   return pParser->yyidxMax;
124771 }
124772 #endif
124773 
124774 /*
124775 ** Find the appropriate action for a parser given the terminal
124776 ** look-ahead token iLookAhead.
124777 **
124778 ** If the look-ahead token is YYNOCODE, then check to see if the action is
124779 ** independent of the look-ahead.  If it is, return the action, otherwise
124780 ** return YY_NO_ACTION.
124781 */
124782 static int yy_find_shift_action(
124783   yyParser *pParser,        /* The parser */
124784   YYCODETYPE iLookAhead     /* The look-ahead token */
124785 ){
124786   int i;
124787   int stateno = pParser->yystack[pParser->yyidx].stateno;
124788 
124789   if( stateno>YY_SHIFT_COUNT
124790    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
124791     return yy_default[stateno];
124792   }
124793   assert( iLookAhead!=YYNOCODE );
124794   i += iLookAhead;
124795   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
124796     if( iLookAhead>0 ){
124797 #ifdef YYFALLBACK
124798       YYCODETYPE iFallback;            /* Fallback token */
124799       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
124800              && (iFallback = yyFallback[iLookAhead])!=0 ){
124801 #ifndef NDEBUG
124802         if( yyTraceFILE ){
124803           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
124804              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
124805         }
124806 #endif
124807         return yy_find_shift_action(pParser, iFallback);
124808       }
124809 #endif
124810 #ifdef YYWILDCARD
124811       {
124812         int j = i - iLookAhead + YYWILDCARD;
124813         if(
124814 #if YY_SHIFT_MIN+YYWILDCARD<0
124815           j>=0 &&
124816 #endif
124817 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
124818           j<YY_ACTTAB_COUNT &&
124819 #endif
124820           yy_lookahead[j]==YYWILDCARD
124821         ){
124822 #ifndef NDEBUG
124823           if( yyTraceFILE ){
124824             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
124825                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
124826           }
124827 #endif /* NDEBUG */
124828           return yy_action[j];
124829         }
124830       }
124831 #endif /* YYWILDCARD */
124832     }
124833     return yy_default[stateno];
124834   }else{
124835     return yy_action[i];
124836   }
124837 }
124838 
124839 /*
124840 ** Find the appropriate action for a parser given the non-terminal
124841 ** look-ahead token iLookAhead.
124842 **
124843 ** If the look-ahead token is YYNOCODE, then check to see if the action is
124844 ** independent of the look-ahead.  If it is, return the action, otherwise
124845 ** return YY_NO_ACTION.
124846 */
124847 static int yy_find_reduce_action(
124848   int stateno,              /* Current state number */
124849   YYCODETYPE iLookAhead     /* The look-ahead token */
124850 ){
124851   int i;
124852 #ifdef YYERRORSYMBOL
124853   if( stateno>YY_REDUCE_COUNT ){
124854     return yy_default[stateno];
124855   }
124856 #else
124857   assert( stateno<=YY_REDUCE_COUNT );
124858 #endif
124859   i = yy_reduce_ofst[stateno];
124860   assert( i!=YY_REDUCE_USE_DFLT );
124861   assert( iLookAhead!=YYNOCODE );
124862   i += iLookAhead;
124863 #ifdef YYERRORSYMBOL
124864   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
124865     return yy_default[stateno];
124866   }
124867 #else
124868   assert( i>=0 && i<YY_ACTTAB_COUNT );
124869   assert( yy_lookahead[i]==iLookAhead );
124870 #endif
124871   return yy_action[i];
124872 }
124873 
124874 /*
124875 ** The following routine is called if the stack overflows.
124876 */
124877 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
124878    sqlite3ParserARG_FETCH;
124879    yypParser->yyidx--;
124880 #ifndef NDEBUG
124881    if( yyTraceFILE ){
124882      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
124883    }
124884 #endif
124885    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
124886    /* Here code is inserted which will execute if the parser
124887    ** stack every overflows */
124888 
124889   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
124890   sqlite3ErrorMsg(pParse, "parser stack overflow");
124891    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
124892 }
124893 
124894 /*
124895 ** Perform a shift action.
124896 */
124897 static void yy_shift(
124898   yyParser *yypParser,          /* The parser to be shifted */
124899   int yyNewState,               /* The new state to shift in */
124900   int yyMajor,                  /* The major token to shift in */
124901   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
124902 ){
124903   yyStackEntry *yytos;
124904   yypParser->yyidx++;
124905 #ifdef YYTRACKMAXSTACKDEPTH
124906   if( yypParser->yyidx>yypParser->yyidxMax ){
124907     yypParser->yyidxMax = yypParser->yyidx;
124908   }
124909 #endif
124910 #if YYSTACKDEPTH>0
124911   if( yypParser->yyidx>=YYSTACKDEPTH ){
124912     yyStackOverflow(yypParser, yypMinor);
124913     return;
124914   }
124915 #else
124916   if( yypParser->yyidx>=yypParser->yystksz ){
124917     yyGrowStack(yypParser);
124918     if( yypParser->yyidx>=yypParser->yystksz ){
124919       yyStackOverflow(yypParser, yypMinor);
124920       return;
124921     }
124922   }
124923 #endif
124924   yytos = &yypParser->yystack[yypParser->yyidx];
124925   yytos->stateno = (YYACTIONTYPE)yyNewState;
124926   yytos->major = (YYCODETYPE)yyMajor;
124927   yytos->minor = *yypMinor;
124928 #ifndef NDEBUG
124929   if( yyTraceFILE && yypParser->yyidx>0 ){
124930     int i;
124931     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
124932     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
124933     for(i=1; i<=yypParser->yyidx; i++)
124934       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
124935     fprintf(yyTraceFILE,"\n");
124936   }
124937 #endif
124938 }
124939 
124940 /* The following table contains information about every rule that
124941 ** is used during the reduce.
124942 */
124943 static const struct {
124944   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
124945   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
124946 } yyRuleInfo[] = {
124947   { 144, 1 },
124948   { 145, 2 },
124949   { 145, 1 },
124950   { 146, 1 },
124951   { 146, 3 },
124952   { 147, 0 },
124953   { 147, 1 },
124954   { 147, 3 },
124955   { 148, 1 },
124956   { 149, 3 },
124957   { 151, 0 },
124958   { 151, 1 },
124959   { 151, 2 },
124960   { 150, 0 },
124961   { 150, 1 },
124962   { 150, 1 },
124963   { 150, 1 },
124964   { 149, 2 },
124965   { 149, 2 },
124966   { 149, 2 },
124967   { 153, 1 },
124968   { 153, 0 },
124969   { 149, 2 },
124970   { 149, 3 },
124971   { 149, 5 },
124972   { 149, 2 },
124973   { 154, 6 },
124974   { 156, 1 },
124975   { 158, 0 },
124976   { 158, 3 },
124977   { 157, 1 },
124978   { 157, 0 },
124979   { 155, 5 },
124980   { 155, 2 },
124981   { 162, 0 },
124982   { 162, 2 },
124983   { 160, 3 },
124984   { 160, 1 },
124985   { 164, 3 },
124986   { 165, 1 },
124987   { 152, 1 },
124988   { 152, 1 },
124989   { 152, 1 },
124990   { 166, 0 },
124991   { 166, 1 },
124992   { 168, 1 },
124993   { 168, 4 },
124994   { 168, 6 },
124995   { 169, 1 },
124996   { 169, 2 },
124997   { 170, 1 },
124998   { 170, 1 },
124999   { 167, 2 },
125000   { 167, 0 },
125001   { 173, 2 },
125002   { 173, 2 },
125003   { 173, 4 },
125004   { 173, 3 },
125005   { 173, 3 },
125006   { 173, 2 },
125007   { 173, 2 },
125008   { 173, 3 },
125009   { 173, 5 },
125010   { 173, 2 },
125011   { 173, 4 },
125012   { 173, 4 },
125013   { 173, 1 },
125014   { 173, 2 },
125015   { 178, 0 },
125016   { 178, 1 },
125017   { 180, 0 },
125018   { 180, 2 },
125019   { 182, 2 },
125020   { 182, 3 },
125021   { 182, 3 },
125022   { 182, 3 },
125023   { 183, 2 },
125024   { 183, 2 },
125025   { 183, 1 },
125026   { 183, 1 },
125027   { 183, 2 },
125028   { 181, 3 },
125029   { 181, 2 },
125030   { 184, 0 },
125031   { 184, 2 },
125032   { 184, 2 },
125033   { 161, 0 },
125034   { 161, 2 },
125035   { 185, 3 },
125036   { 185, 1 },
125037   { 186, 1 },
125038   { 186, 0 },
125039   { 187, 2 },
125040   { 187, 7 },
125041   { 187, 5 },
125042   { 187, 5 },
125043   { 187, 10 },
125044   { 189, 0 },
125045   { 189, 1 },
125046   { 176, 0 },
125047   { 176, 3 },
125048   { 190, 0 },
125049   { 190, 2 },
125050   { 191, 1 },
125051   { 191, 1 },
125052   { 191, 1 },
125053   { 149, 4 },
125054   { 193, 2 },
125055   { 193, 0 },
125056   { 149, 8 },
125057   { 149, 4 },
125058   { 149, 1 },
125059   { 163, 2 },
125060   { 195, 1 },
125061   { 195, 3 },
125062   { 198, 1 },
125063   { 198, 2 },
125064   { 198, 1 },
125065   { 196, 9 },
125066   { 196, 1 },
125067   { 207, 4 },
125068   { 207, 5 },
125069   { 199, 1 },
125070   { 199, 1 },
125071   { 199, 0 },
125072   { 210, 2 },
125073   { 210, 0 },
125074   { 200, 3 },
125075   { 200, 2 },
125076   { 200, 4 },
125077   { 211, 2 },
125078   { 211, 1 },
125079   { 211, 0 },
125080   { 201, 0 },
125081   { 201, 2 },
125082   { 213, 2 },
125083   { 213, 0 },
125084   { 212, 7 },
125085   { 212, 7 },
125086   { 212, 7 },
125087   { 159, 0 },
125088   { 159, 2 },
125089   { 194, 2 },
125090   { 214, 1 },
125091   { 214, 2 },
125092   { 214, 3 },
125093   { 214, 4 },
125094   { 216, 2 },
125095   { 216, 0 },
125096   { 215, 0 },
125097   { 215, 3 },
125098   { 215, 2 },
125099   { 217, 4 },
125100   { 217, 0 },
125101   { 205, 0 },
125102   { 205, 3 },
125103   { 220, 4 },
125104   { 220, 2 },
125105   { 177, 1 },
125106   { 177, 1 },
125107   { 177, 0 },
125108   { 203, 0 },
125109   { 203, 3 },
125110   { 204, 0 },
125111   { 204, 2 },
125112   { 206, 0 },
125113   { 206, 2 },
125114   { 206, 4 },
125115   { 206, 4 },
125116   { 149, 6 },
125117   { 202, 0 },
125118   { 202, 2 },
125119   { 149, 8 },
125120   { 221, 5 },
125121   { 221, 3 },
125122   { 149, 6 },
125123   { 149, 7 },
125124   { 222, 2 },
125125   { 222, 1 },
125126   { 223, 0 },
125127   { 223, 3 },
125128   { 219, 3 },
125129   { 219, 1 },
125130   { 175, 1 },
125131   { 175, 3 },
125132   { 174, 1 },
125133   { 175, 1 },
125134   { 175, 1 },
125135   { 175, 3 },
125136   { 175, 5 },
125137   { 174, 1 },
125138   { 174, 1 },
125139   { 175, 1 },
125140   { 175, 3 },
125141   { 175, 6 },
125142   { 175, 5 },
125143   { 175, 4 },
125144   { 174, 1 },
125145   { 175, 3 },
125146   { 175, 3 },
125147   { 175, 3 },
125148   { 175, 3 },
125149   { 175, 3 },
125150   { 175, 3 },
125151   { 175, 3 },
125152   { 175, 3 },
125153   { 224, 1 },
125154   { 224, 2 },
125155   { 175, 3 },
125156   { 175, 5 },
125157   { 175, 2 },
125158   { 175, 3 },
125159   { 175, 3 },
125160   { 175, 4 },
125161   { 175, 2 },
125162   { 175, 2 },
125163   { 175, 2 },
125164   { 175, 2 },
125165   { 225, 1 },
125166   { 225, 2 },
125167   { 175, 5 },
125168   { 226, 1 },
125169   { 226, 2 },
125170   { 175, 5 },
125171   { 175, 3 },
125172   { 175, 5 },
125173   { 175, 4 },
125174   { 175, 4 },
125175   { 175, 5 },
125176   { 228, 5 },
125177   { 228, 4 },
125178   { 229, 2 },
125179   { 229, 0 },
125180   { 227, 1 },
125181   { 227, 0 },
125182   { 209, 1 },
125183   { 209, 0 },
125184   { 208, 3 },
125185   { 208, 1 },
125186   { 149, 12 },
125187   { 230, 1 },
125188   { 230, 0 },
125189   { 179, 0 },
125190   { 179, 3 },
125191   { 188, 5 },
125192   { 188, 3 },
125193   { 231, 0 },
125194   { 231, 2 },
125195   { 149, 4 },
125196   { 149, 1 },
125197   { 149, 2 },
125198   { 149, 3 },
125199   { 149, 5 },
125200   { 149, 6 },
125201   { 149, 5 },
125202   { 149, 6 },
125203   { 232, 1 },
125204   { 232, 1 },
125205   { 232, 1 },
125206   { 232, 1 },
125207   { 232, 1 },
125208   { 171, 2 },
125209   { 171, 1 },
125210   { 172, 2 },
125211   { 149, 5 },
125212   { 233, 11 },
125213   { 235, 1 },
125214   { 235, 1 },
125215   { 235, 2 },
125216   { 235, 0 },
125217   { 236, 1 },
125218   { 236, 1 },
125219   { 236, 3 },
125220   { 237, 0 },
125221   { 237, 3 },
125222   { 238, 0 },
125223   { 238, 2 },
125224   { 234, 3 },
125225   { 234, 2 },
125226   { 240, 1 },
125227   { 240, 3 },
125228   { 241, 0 },
125229   { 241, 3 },
125230   { 241, 2 },
125231   { 239, 7 },
125232   { 239, 5 },
125233   { 239, 5 },
125234   { 239, 1 },
125235   { 175, 4 },
125236   { 175, 6 },
125237   { 192, 1 },
125238   { 192, 1 },
125239   { 192, 1 },
125240   { 149, 4 },
125241   { 149, 6 },
125242   { 149, 3 },
125243   { 243, 0 },
125244   { 243, 2 },
125245   { 242, 1 },
125246   { 242, 0 },
125247   { 149, 1 },
125248   { 149, 3 },
125249   { 149, 1 },
125250   { 149, 3 },
125251   { 149, 6 },
125252   { 149, 6 },
125253   { 244, 1 },
125254   { 245, 0 },
125255   { 245, 1 },
125256   { 149, 1 },
125257   { 149, 4 },
125258   { 246, 8 },
125259   { 247, 1 },
125260   { 247, 3 },
125261   { 248, 0 },
125262   { 248, 2 },
125263   { 249, 1 },
125264   { 249, 3 },
125265   { 250, 1 },
125266   { 251, 0 },
125267   { 251, 4 },
125268   { 251, 2 },
125269   { 197, 0 },
125270   { 197, 2 },
125271   { 197, 3 },
125272   { 252, 6 },
125273   { 252, 8 },
125274 };
125275 
125276 static void yy_accept(yyParser*);  /* Forward Declaration */
125277 
125278 /*
125279 ** Perform a reduce action and the shift that must immediately
125280 ** follow the reduce.
125281 */
125282 static void yy_reduce(
125283   yyParser *yypParser,         /* The parser */
125284   int yyruleno                 /* Number of the rule by which to reduce */
125285 ){
125286   int yygoto;                     /* The next state */
125287   int yyact;                      /* The next action */
125288   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
125289   yyStackEntry *yymsp;            /* The top of the parser's stack */
125290   int yysize;                     /* Amount to pop the stack */
125291   sqlite3ParserARG_FETCH;
125292   yymsp = &yypParser->yystack[yypParser->yyidx];
125293 #ifndef NDEBUG
125294   if( yyTraceFILE && yyruleno>=0
125295         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
125296     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
125297       yyRuleName[yyruleno]);
125298   }
125299 #endif /* NDEBUG */
125300 
125301   /* Silence complaints from purify about yygotominor being uninitialized
125302   ** in some cases when it is copied into the stack after the following
125303   ** switch.  yygotominor is uninitialized when a rule reduces that does
125304   ** not set the value of its left-hand side nonterminal.  Leaving the
125305   ** value of the nonterminal uninitialized is utterly harmless as long
125306   ** as the value is never used.  So really the only thing this code
125307   ** accomplishes is to quieten purify.
125308   **
125309   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
125310   ** without this code, their parser segfaults.  I'm not sure what there
125311   ** parser is doing to make this happen.  This is the second bug report
125312   ** from wireshark this week.  Clearly they are stressing Lemon in ways
125313   ** that it has not been previously stressed...  (SQLite ticket #2172)
125314   */
125315   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
125316   yygotominor = yyzerominor;
125317 
125318 
125319   switch( yyruleno ){
125320   /* Beginning here are the reduction cases.  A typical example
125321   ** follows:
125322   **   case 0:
125323   **  #line <lineno> <grammarfile>
125324   **     { ... }           // User supplied code
125325   **  #line <lineno> <thisfile>
125326   **     break;
125327   */
125328       case 5: /* explain ::= */
125329 { sqlite3BeginParse(pParse, 0); }
125330         break;
125331       case 6: /* explain ::= EXPLAIN */
125332 { sqlite3BeginParse(pParse, 1); }
125333         break;
125334       case 7: /* explain ::= EXPLAIN QUERY PLAN */
125335 { sqlite3BeginParse(pParse, 2); }
125336         break;
125337       case 8: /* cmdx ::= cmd */
125338 { sqlite3FinishCoding(pParse); }
125339         break;
125340       case 9: /* cmd ::= BEGIN transtype trans_opt */
125341 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
125342         break;
125343       case 13: /* transtype ::= */
125344 {yygotominor.yy328 = TK_DEFERRED;}
125345         break;
125346       case 14: /* transtype ::= DEFERRED */
125347       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
125348       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
125349       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
125350       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
125351 {yygotominor.yy328 = yymsp[0].major;}
125352         break;
125353       case 17: /* cmd ::= COMMIT trans_opt */
125354       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
125355 {sqlite3CommitTransaction(pParse);}
125356         break;
125357       case 19: /* cmd ::= ROLLBACK trans_opt */
125358 {sqlite3RollbackTransaction(pParse);}
125359         break;
125360       case 22: /* cmd ::= SAVEPOINT nm */
125361 {
125362   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
125363 }
125364         break;
125365       case 23: /* cmd ::= RELEASE savepoint_opt nm */
125366 {
125367   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
125368 }
125369         break;
125370       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
125371 {
125372   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
125373 }
125374         break;
125375       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
125376 {
125377    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
125378 }
125379         break;
125380       case 27: /* createkw ::= CREATE */
125381 {
125382   pParse->db->lookaside.bEnabled = 0;
125383   yygotominor.yy0 = yymsp[0].minor.yy0;
125384 }
125385         break;
125386       case 28: /* ifnotexists ::= */
125387       case 31: /* temp ::= */ yytestcase(yyruleno==31);
125388       case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
125389       case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
125390       case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
125391       case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
125392       case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
125393       case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
125394       case 218: /* between_op ::= BETWEEN */ yytestcase(yyruleno==218);
125395       case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
125396 {yygotominor.yy328 = 0;}
125397         break;
125398       case 29: /* ifnotexists ::= IF NOT EXISTS */
125399       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
125400       case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
125401       case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
125402       case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
125403       case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
125404       case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
125405 {yygotominor.yy328 = 1;}
125406         break;
125407       case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
125408 {
125409   sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
125410 }
125411         break;
125412       case 33: /* create_table_args ::= AS select */
125413 {
125414   sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
125415   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
125416 }
125417         break;
125418       case 34: /* table_options ::= */
125419 {yygotominor.yy186 = 0;}
125420         break;
125421       case 35: /* table_options ::= WITHOUT nm */
125422 {
125423   if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
125424     yygotominor.yy186 = TF_WithoutRowid;
125425   }else{
125426     yygotominor.yy186 = 0;
125427     sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
125428   }
125429 }
125430         break;
125431       case 38: /* column ::= columnid type carglist */
125432 {
125433   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
125434   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
125435 }
125436         break;
125437       case 39: /* columnid ::= nm */
125438 {
125439   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
125440   yygotominor.yy0 = yymsp[0].minor.yy0;
125441   pParse->constraintName.n = 0;
125442 }
125443         break;
125444       case 40: /* nm ::= ID|INDEXED */
125445       case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
125446       case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
125447       case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
125448       case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
125449       case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
125450       case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
125451       case 141: /* dbnm ::= DOT nm */ yytestcase(yyruleno==141);
125452       case 150: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==150);
125453       case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
125454       case 256: /* nmnum ::= plus_num */ yytestcase(yyruleno==256);
125455       case 257: /* nmnum ::= nm */ yytestcase(yyruleno==257);
125456       case 258: /* nmnum ::= ON */ yytestcase(yyruleno==258);
125457       case 259: /* nmnum ::= DELETE */ yytestcase(yyruleno==259);
125458       case 260: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==260);
125459       case 261: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==261);
125460       case 262: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==262);
125461       case 263: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==263);
125462       case 279: /* trnm ::= nm */ yytestcase(yyruleno==279);
125463 {yygotominor.yy0 = yymsp[0].minor.yy0;}
125464         break;
125465       case 44: /* type ::= typetoken */
125466 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
125467         break;
125468       case 46: /* typetoken ::= typename LP signed RP */
125469 {
125470   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
125471   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
125472 }
125473         break;
125474       case 47: /* typetoken ::= typename LP signed COMMA signed RP */
125475 {
125476   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
125477   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
125478 }
125479         break;
125480       case 49: /* typename ::= typename ID|STRING */
125481 {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);}
125482         break;
125483       case 54: /* ccons ::= CONSTRAINT nm */
125484       case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
125485 {pParse->constraintName = yymsp[0].minor.yy0;}
125486         break;
125487       case 55: /* ccons ::= DEFAULT term */
125488       case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
125489 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
125490         break;
125491       case 56: /* ccons ::= DEFAULT LP expr RP */
125492 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
125493         break;
125494       case 58: /* ccons ::= DEFAULT MINUS term */
125495 {
125496   ExprSpan v;
125497   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
125498   v.zStart = yymsp[-1].minor.yy0.z;
125499   v.zEnd = yymsp[0].minor.yy346.zEnd;
125500   sqlite3AddDefaultValue(pParse,&v);
125501 }
125502         break;
125503       case 59: /* ccons ::= DEFAULT ID|INDEXED */
125504 {
125505   ExprSpan v;
125506   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
125507   sqlite3AddDefaultValue(pParse,&v);
125508 }
125509         break;
125510       case 61: /* ccons ::= NOT NULL onconf */
125511 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
125512         break;
125513       case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
125514 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
125515         break;
125516       case 63: /* ccons ::= UNIQUE onconf */
125517 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
125518         break;
125519       case 64: /* ccons ::= CHECK LP expr RP */
125520 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
125521         break;
125522       case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
125523 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
125524         break;
125525       case 66: /* ccons ::= defer_subclause */
125526 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
125527         break;
125528       case 67: /* ccons ::= COLLATE ID|STRING */
125529 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
125530         break;
125531       case 70: /* refargs ::= */
125532 { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
125533         break;
125534       case 71: /* refargs ::= refargs refarg */
125535 { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
125536         break;
125537       case 72: /* refarg ::= MATCH nm */
125538       case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
125539 { yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
125540         break;
125541       case 74: /* refarg ::= ON DELETE refact */
125542 { yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
125543         break;
125544       case 75: /* refarg ::= ON UPDATE refact */
125545 { yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
125546         break;
125547       case 76: /* refact ::= SET NULL */
125548 { yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
125549         break;
125550       case 77: /* refact ::= SET DEFAULT */
125551 { yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
125552         break;
125553       case 78: /* refact ::= CASCADE */
125554 { yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
125555         break;
125556       case 79: /* refact ::= RESTRICT */
125557 { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
125558         break;
125559       case 80: /* refact ::= NO ACTION */
125560 { yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
125561         break;
125562       case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
125563       case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
125564       case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
125565       case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
125566 {yygotominor.yy328 = yymsp[0].minor.yy328;}
125567         break;
125568       case 86: /* conslist_opt ::= */
125569 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
125570         break;
125571       case 87: /* conslist_opt ::= COMMA conslist */
125572 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
125573         break;
125574       case 90: /* tconscomma ::= COMMA */
125575 {pParse->constraintName.n = 0;}
125576         break;
125577       case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
125578 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
125579         break;
125580       case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
125581 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
125582         break;
125583       case 95: /* tcons ::= CHECK LP expr RP onconf */
125584 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
125585         break;
125586       case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
125587 {
125588     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
125589     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
125590 }
125591         break;
125592       case 99: /* onconf ::= */
125593 {yygotominor.yy328 = OE_Default;}
125594         break;
125595       case 101: /* orconf ::= */
125596 {yygotominor.yy186 = OE_Default;}
125597         break;
125598       case 102: /* orconf ::= OR resolvetype */
125599 {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
125600         break;
125601       case 104: /* resolvetype ::= IGNORE */
125602 {yygotominor.yy328 = OE_Ignore;}
125603         break;
125604       case 105: /* resolvetype ::= REPLACE */
125605 {yygotominor.yy328 = OE_Replace;}
125606         break;
125607       case 106: /* cmd ::= DROP TABLE ifexists fullname */
125608 {
125609   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
125610 }
125611         break;
125612       case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
125613 {
125614   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);
125615 }
125616         break;
125617       case 110: /* cmd ::= DROP VIEW ifexists fullname */
125618 {
125619   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
125620 }
125621         break;
125622       case 111: /* cmd ::= select */
125623 {
125624   SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
125625   sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
125626   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
125627 }
125628         break;
125629       case 112: /* select ::= with selectnowith */
125630 {
125631   Select *p = yymsp[0].minor.yy3;
125632   if( p ){
125633     p->pWith = yymsp[-1].minor.yy59;
125634     parserDoubleLinkSelect(pParse, p);
125635   }else{
125636     sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
125637   }
125638   yygotominor.yy3 = p;
125639 }
125640         break;
125641       case 113: /* selectnowith ::= oneselect */
125642       case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
125643 {yygotominor.yy3 = yymsp[0].minor.yy3;}
125644         break;
125645       case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
125646 {
125647   Select *pRhs = yymsp[0].minor.yy3;
125648   if( pRhs && pRhs->pPrior ){
125649     SrcList *pFrom;
125650     Token x;
125651     x.n = 0;
125652     parserDoubleLinkSelect(pParse, pRhs);
125653     pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
125654     pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
125655   }
125656   if( pRhs ){
125657     pRhs->op = (u8)yymsp[-1].minor.yy328;
125658     pRhs->pPrior = yymsp[-2].minor.yy3;
125659     pRhs->selFlags &= ~SF_MultiValue;
125660     if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
125661   }else{
125662     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
125663   }
125664   yygotominor.yy3 = pRhs;
125665 }
125666         break;
125667       case 116: /* multiselect_op ::= UNION ALL */
125668 {yygotominor.yy328 = TK_ALL;}
125669         break;
125670       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
125671 {
125672   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);
125673 #if SELECTTRACE_ENABLED
125674   /* Populate the Select.zSelName[] string that is used to help with
125675   ** query planner debugging, to differentiate between multiple Select
125676   ** objects in a complex query.
125677   **
125678   ** If the SELECT keyword is immediately followed by a C-style comment
125679   ** then extract the first few alphanumeric characters from within that
125680   ** comment to be the zSelName value.  Otherwise, the label is #N where
125681   ** is an integer that is incremented with each SELECT statement seen.
125682   */
125683   if( yygotominor.yy3!=0 ){
125684     const char *z = yymsp[-8].minor.yy0.z+6;
125685     int i;
125686     sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "#%d",
125687                      ++pParse->nSelect);
125688     while( z[0]==' ' ) z++;
125689     if( z[0]=='/' && z[1]=='*' ){
125690       z += 2;
125691       while( z[0]==' ' ) z++;
125692       for(i=0; sqlite3Isalnum(z[i]); i++){}
125693       sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "%.*s", i, z);
125694     }
125695   }
125696 #endif /* SELECTRACE_ENABLED */
125697 }
125698         break;
125699       case 120: /* values ::= VALUES LP nexprlist RP */
125700 {
125701   yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
125702 }
125703         break;
125704       case 121: /* values ::= values COMMA LP exprlist RP */
125705 {
125706   Select *pRight, *pLeft = yymsp[-4].minor.yy3;
125707   pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
125708   if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
125709   if( pRight ){
125710     pRight->op = TK_ALL;
125711     pLeft = yymsp[-4].minor.yy3;
125712     pRight->pPrior = pLeft;
125713     yygotominor.yy3 = pRight;
125714   }else{
125715     yygotominor.yy3 = pLeft;
125716   }
125717 }
125718         break;
125719       case 122: /* distinct ::= DISTINCT */
125720 {yygotominor.yy381 = SF_Distinct;}
125721         break;
125722       case 123: /* distinct ::= ALL */
125723       case 124: /* distinct ::= */ yytestcase(yyruleno==124);
125724 {yygotominor.yy381 = 0;}
125725         break;
125726       case 125: /* sclp ::= selcollist COMMA */
125727       case 243: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==243);
125728 {yygotominor.yy14 = yymsp[-1].minor.yy14;}
125729         break;
125730       case 126: /* sclp ::= */
125731       case 154: /* orderby_opt ::= */ yytestcase(yyruleno==154);
125732       case 161: /* groupby_opt ::= */ yytestcase(yyruleno==161);
125733       case 236: /* exprlist ::= */ yytestcase(yyruleno==236);
125734       case 242: /* idxlist_opt ::= */ yytestcase(yyruleno==242);
125735 {yygotominor.yy14 = 0;}
125736         break;
125737       case 127: /* selcollist ::= sclp expr as */
125738 {
125739    yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
125740    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
125741    sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
125742 }
125743         break;
125744       case 128: /* selcollist ::= sclp STAR */
125745 {
125746   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
125747   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
125748 }
125749         break;
125750       case 129: /* selcollist ::= sclp nm DOT STAR */
125751 {
125752   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
125753   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
125754   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
125755   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
125756 }
125757         break;
125758       case 132: /* as ::= */
125759 {yygotominor.yy0.n = 0;}
125760         break;
125761       case 133: /* from ::= */
125762 {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
125763         break;
125764       case 134: /* from ::= FROM seltablist */
125765 {
125766   yygotominor.yy65 = yymsp[0].minor.yy65;
125767   sqlite3SrcListShiftJoinType(yygotominor.yy65);
125768 }
125769         break;
125770       case 135: /* stl_prefix ::= seltablist joinop */
125771 {
125772    yygotominor.yy65 = yymsp[-1].minor.yy65;
125773    if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
125774 }
125775         break;
125776       case 136: /* stl_prefix ::= */
125777 {yygotominor.yy65 = 0;}
125778         break;
125779       case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
125780 {
125781   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);
125782   sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
125783 }
125784         break;
125785       case 138: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
125786 {
125787     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);
125788   }
125789         break;
125790       case 139: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
125791 {
125792     if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
125793       yygotominor.yy65 = yymsp[-4].minor.yy65;
125794     }else if( yymsp[-4].minor.yy65->nSrc==1 ){
125795       yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
125796       if( yygotominor.yy65 ){
125797         struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
125798         struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
125799         pNew->zName = pOld->zName;
125800         pNew->zDatabase = pOld->zDatabase;
125801         pNew->pSelect = pOld->pSelect;
125802         pOld->zName = pOld->zDatabase = 0;
125803         pOld->pSelect = 0;
125804       }
125805       sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
125806     }else{
125807       Select *pSubquery;
125808       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
125809       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
125810       yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
125811     }
125812   }
125813         break;
125814       case 140: /* dbnm ::= */
125815       case 149: /* indexed_opt ::= */ yytestcase(yyruleno==149);
125816 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
125817         break;
125818       case 142: /* fullname ::= nm dbnm */
125819 {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
125820         break;
125821       case 143: /* joinop ::= COMMA|JOIN */
125822 { yygotominor.yy328 = JT_INNER; }
125823         break;
125824       case 144: /* joinop ::= JOIN_KW JOIN */
125825 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
125826         break;
125827       case 145: /* joinop ::= JOIN_KW nm JOIN */
125828 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
125829         break;
125830       case 146: /* joinop ::= JOIN_KW nm nm JOIN */
125831 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
125832         break;
125833       case 147: /* on_opt ::= ON expr */
125834       case 164: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==164);
125835       case 171: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==171);
125836       case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
125837       case 233: /* case_operand ::= expr */ yytestcase(yyruleno==233);
125838 {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
125839         break;
125840       case 148: /* on_opt ::= */
125841       case 163: /* having_opt ::= */ yytestcase(yyruleno==163);
125842       case 170: /* where_opt ::= */ yytestcase(yyruleno==170);
125843       case 232: /* case_else ::= */ yytestcase(yyruleno==232);
125844       case 234: /* case_operand ::= */ yytestcase(yyruleno==234);
125845 {yygotominor.yy132 = 0;}
125846         break;
125847       case 151: /* indexed_opt ::= NOT INDEXED */
125848 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
125849         break;
125850       case 152: /* using_opt ::= USING LP idlist RP */
125851       case 180: /* inscollist_opt ::= LP idlist RP */ yytestcase(yyruleno==180);
125852 {yygotominor.yy408 = yymsp[-1].minor.yy408;}
125853         break;
125854       case 153: /* using_opt ::= */
125855       case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
125856 {yygotominor.yy408 = 0;}
125857         break;
125858       case 155: /* orderby_opt ::= ORDER BY sortlist */
125859       case 162: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==162);
125860       case 235: /* exprlist ::= nexprlist */ yytestcase(yyruleno==235);
125861 {yygotominor.yy14 = yymsp[0].minor.yy14;}
125862         break;
125863       case 156: /* sortlist ::= sortlist COMMA expr sortorder */
125864 {
125865   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
125866   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
125867 }
125868         break;
125869       case 157: /* sortlist ::= expr sortorder */
125870 {
125871   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
125872   if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
125873 }
125874         break;
125875       case 158: /* sortorder ::= ASC */
125876       case 160: /* sortorder ::= */ yytestcase(yyruleno==160);
125877 {yygotominor.yy328 = SQLITE_SO_ASC;}
125878         break;
125879       case 159: /* sortorder ::= DESC */
125880 {yygotominor.yy328 = SQLITE_SO_DESC;}
125881         break;
125882       case 165: /* limit_opt ::= */
125883 {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
125884         break;
125885       case 166: /* limit_opt ::= LIMIT expr */
125886 {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
125887         break;
125888       case 167: /* limit_opt ::= LIMIT expr OFFSET expr */
125889 {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
125890         break;
125891       case 168: /* limit_opt ::= LIMIT expr COMMA expr */
125892 {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
125893         break;
125894       case 169: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
125895 {
125896   sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
125897   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
125898   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
125899 }
125900         break;
125901       case 172: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
125902 {
125903   sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
125904   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
125905   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
125906   sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
125907 }
125908         break;
125909       case 173: /* setlist ::= setlist COMMA nm EQ expr */
125910 {
125911   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
125912   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
125913 }
125914         break;
125915       case 174: /* setlist ::= nm EQ expr */
125916 {
125917   yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
125918   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
125919 }
125920         break;
125921       case 175: /* cmd ::= with insert_cmd INTO fullname inscollist_opt select */
125922 {
125923   sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
125924   sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
125925 }
125926         break;
125927       case 176: /* cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
125928 {
125929   sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
125930   sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
125931 }
125932         break;
125933       case 177: /* insert_cmd ::= INSERT orconf */
125934 {yygotominor.yy186 = yymsp[0].minor.yy186;}
125935         break;
125936       case 178: /* insert_cmd ::= REPLACE */
125937 {yygotominor.yy186 = OE_Replace;}
125938         break;
125939       case 181: /* idlist ::= idlist COMMA nm */
125940 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
125941         break;
125942       case 182: /* idlist ::= nm */
125943 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
125944         break;
125945       case 183: /* expr ::= term */
125946 {yygotominor.yy346 = yymsp[0].minor.yy346;}
125947         break;
125948       case 184: /* expr ::= LP expr RP */
125949 {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
125950         break;
125951       case 185: /* term ::= NULL */
125952       case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
125953       case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
125954 {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
125955         break;
125956       case 186: /* expr ::= ID|INDEXED */
125957       case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
125958 {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
125959         break;
125960       case 188: /* expr ::= nm DOT nm */
125961 {
125962   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
125963   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
125964   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
125965   spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
125966 }
125967         break;
125968       case 189: /* expr ::= nm DOT nm DOT nm */
125969 {
125970   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
125971   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
125972   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
125973   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
125974   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
125975   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
125976 }
125977         break;
125978       case 192: /* expr ::= VARIABLE */
125979 {
125980   if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
125981     /* When doing a nested parse, one can include terms in an expression
125982     ** that look like this:   #1 #2 ...  These terms refer to registers
125983     ** in the virtual machine.  #N is the N-th register. */
125984     if( pParse->nested==0 ){
125985       sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
125986       yygotominor.yy346.pExpr = 0;
125987     }else{
125988       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
125989       if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
125990     }
125991   }else{
125992     spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
125993     sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
125994   }
125995   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
125996 }
125997         break;
125998       case 193: /* expr ::= expr COLLATE ID|STRING */
125999 {
126000   yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0, 1);
126001   yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
126002   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
126003 }
126004         break;
126005       case 194: /* expr ::= CAST LP expr AS typetoken RP */
126006 {
126007   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
126008   spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
126009 }
126010         break;
126011       case 195: /* expr ::= ID|INDEXED LP distinct exprlist RP */
126012 {
126013   if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
126014     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
126015   }
126016   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
126017   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
126018   if( yymsp[-2].minor.yy381 && yygotominor.yy346.pExpr ){
126019     yygotominor.yy346.pExpr->flags |= EP_Distinct;
126020   }
126021 }
126022         break;
126023       case 196: /* expr ::= ID|INDEXED LP STAR RP */
126024 {
126025   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
126026   spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
126027 }
126028         break;
126029       case 197: /* term ::= CTIME_KW */
126030 {
126031   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
126032   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
126033 }
126034         break;
126035       case 198: /* expr ::= expr AND expr */
126036       case 199: /* expr ::= expr OR expr */ yytestcase(yyruleno==199);
126037       case 200: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==200);
126038       case 201: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==201);
126039       case 202: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==202);
126040       case 203: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==203);
126041       case 204: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==204);
126042       case 205: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==205);
126043 {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
126044         break;
126045       case 206: /* likeop ::= LIKE_KW|MATCH */
126046 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
126047         break;
126048       case 207: /* likeop ::= NOT LIKE_KW|MATCH */
126049 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
126050         break;
126051       case 208: /* expr ::= expr likeop expr */
126052 {
126053   ExprList *pList;
126054   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
126055   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
126056   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
126057   if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
126058   yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
126059   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
126060   if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
126061 }
126062         break;
126063       case 209: /* expr ::= expr likeop expr ESCAPE expr */
126064 {
126065   ExprList *pList;
126066   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
126067   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
126068   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
126069   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
126070   if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
126071   yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
126072   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
126073   if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
126074 }
126075         break;
126076       case 210: /* expr ::= expr ISNULL|NOTNULL */
126077 {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
126078         break;
126079       case 211: /* expr ::= expr NOT NULL */
126080 {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
126081         break;
126082       case 212: /* expr ::= expr IS expr */
126083 {
126084   spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
126085   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
126086 }
126087         break;
126088       case 213: /* expr ::= expr IS NOT expr */
126089 {
126090   spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
126091   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
126092 }
126093         break;
126094       case 214: /* expr ::= NOT expr */
126095       case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
126096 {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
126097         break;
126098       case 216: /* expr ::= MINUS expr */
126099 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
126100         break;
126101       case 217: /* expr ::= PLUS expr */
126102 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
126103         break;
126104       case 220: /* expr ::= expr between_op expr AND expr */
126105 {
126106   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
126107   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
126108   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
126109   if( yygotominor.yy346.pExpr ){
126110     yygotominor.yy346.pExpr->x.pList = pList;
126111   }else{
126112     sqlite3ExprListDelete(pParse->db, pList);
126113   }
126114   if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
126115   yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
126116   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
126117 }
126118         break;
126119       case 223: /* expr ::= expr in_op LP exprlist RP */
126120 {
126121     if( yymsp[-1].minor.yy14==0 ){
126122       /* Expressions of the form
126123       **
126124       **      expr1 IN ()
126125       **      expr1 NOT IN ()
126126       **
126127       ** simplify to constants 0 (false) and 1 (true), respectively,
126128       ** regardless of the value of expr1.
126129       */
126130       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
126131       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
126132     }else if( yymsp[-1].minor.yy14->nExpr==1 ){
126133       /* Expressions of the form:
126134       **
126135       **      expr1 IN (?1)
126136       **      expr1 NOT IN (?2)
126137       **
126138       ** with exactly one value on the RHS can be simplified to something
126139       ** like this:
126140       **
126141       **      expr1 == ?1
126142       **      expr1 <> ?2
126143       **
126144       ** But, the RHS of the == or <> is marked with the EP_Generic flag
126145       ** so that it may not contribute to the computation of comparison
126146       ** affinity or the collating sequence to use for comparison.  Otherwise,
126147       ** the semantics would be subtly different from IN or NOT IN.
126148       */
126149       Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
126150       yymsp[-1].minor.yy14->a[0].pExpr = 0;
126151       sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
126152       /* pRHS cannot be NULL because a malloc error would have been detected
126153       ** before now and control would have never reached this point */
126154       if( ALWAYS(pRHS) ){
126155         pRHS->flags &= ~EP_Collate;
126156         pRHS->flags |= EP_Generic;
126157       }
126158       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
126159     }else{
126160       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
126161       if( yygotominor.yy346.pExpr ){
126162         yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
126163         sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
126164       }else{
126165         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
126166       }
126167       if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
126168     }
126169     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
126170     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
126171   }
126172         break;
126173       case 224: /* expr ::= LP select RP */
126174 {
126175     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
126176     if( yygotominor.yy346.pExpr ){
126177       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
126178       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
126179       sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
126180     }else{
126181       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
126182     }
126183     yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
126184     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
126185   }
126186         break;
126187       case 225: /* expr ::= expr in_op LP select RP */
126188 {
126189     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
126190     if( yygotominor.yy346.pExpr ){
126191       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
126192       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
126193       sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
126194     }else{
126195       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
126196     }
126197     if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
126198     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
126199     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
126200   }
126201         break;
126202       case 226: /* expr ::= expr in_op nm dbnm */
126203 {
126204     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
126205     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
126206     if( yygotominor.yy346.pExpr ){
126207       yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
126208       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
126209       sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
126210     }else{
126211       sqlite3SrcListDelete(pParse->db, pSrc);
126212     }
126213     if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
126214     yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
126215     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];
126216   }
126217         break;
126218       case 227: /* expr ::= EXISTS LP select RP */
126219 {
126220     Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
126221     if( p ){
126222       p->x.pSelect = yymsp[-1].minor.yy3;
126223       ExprSetProperty(p, EP_xIsSelect|EP_Subquery);
126224       sqlite3ExprSetHeightAndFlags(pParse, p);
126225     }else{
126226       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
126227     }
126228     yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
126229     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
126230   }
126231         break;
126232       case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
126233 {
126234   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
126235   if( yygotominor.yy346.pExpr ){
126236     yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
126237     sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
126238   }else{
126239     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
126240     sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
126241   }
126242   yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
126243   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
126244 }
126245         break;
126246       case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
126247 {
126248   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
126249   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
126250 }
126251         break;
126252       case 230: /* case_exprlist ::= WHEN expr THEN expr */
126253 {
126254   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
126255   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
126256 }
126257         break;
126258       case 237: /* nexprlist ::= nexprlist COMMA expr */
126259 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
126260         break;
126261       case 238: /* nexprlist ::= expr */
126262 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
126263         break;
126264       case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
126265 {
126266   sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
126267                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
126268                       &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
126269 }
126270         break;
126271       case 240: /* uniqueflag ::= UNIQUE */
126272       case 291: /* raisetype ::= ABORT */ yytestcase(yyruleno==291);
126273 {yygotominor.yy328 = OE_Abort;}
126274         break;
126275       case 241: /* uniqueflag ::= */
126276 {yygotominor.yy328 = OE_None;}
126277         break;
126278       case 244: /* idxlist ::= idxlist COMMA nm collate sortorder */
126279 {
126280   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0, 1);
126281   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
126282   sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
126283   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
126284   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
126285 }
126286         break;
126287       case 245: /* idxlist ::= nm collate sortorder */
126288 {
126289   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0, 1);
126290   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
126291   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
126292   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
126293   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
126294 }
126295         break;
126296       case 246: /* collate ::= */
126297 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
126298         break;
126299       case 248: /* cmd ::= DROP INDEX ifexists fullname */
126300 {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
126301         break;
126302       case 249: /* cmd ::= VACUUM */
126303       case 250: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==250);
126304 {sqlite3Vacuum(pParse);}
126305         break;
126306       case 251: /* cmd ::= PRAGMA nm dbnm */
126307 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
126308         break;
126309       case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
126310 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
126311         break;
126312       case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
126313 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
126314         break;
126315       case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
126316 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
126317         break;
126318       case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
126319 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
126320         break;
126321       case 264: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
126322 {
126323   Token all;
126324   all.z = yymsp[-3].minor.yy0.z;
126325   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
126326   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
126327 }
126328         break;
126329       case 265: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
126330 {
126331   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);
126332   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
126333 }
126334         break;
126335       case 266: /* trigger_time ::= BEFORE */
126336       case 269: /* trigger_time ::= */ yytestcase(yyruleno==269);
126337 { yygotominor.yy328 = TK_BEFORE; }
126338         break;
126339       case 267: /* trigger_time ::= AFTER */
126340 { yygotominor.yy328 = TK_AFTER;  }
126341         break;
126342       case 268: /* trigger_time ::= INSTEAD OF */
126343 { yygotominor.yy328 = TK_INSTEAD;}
126344         break;
126345       case 270: /* trigger_event ::= DELETE|INSERT */
126346       case 271: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==271);
126347 {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
126348         break;
126349       case 272: /* trigger_event ::= UPDATE OF idlist */
126350 {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
126351         break;
126352       case 275: /* when_clause ::= */
126353       case 296: /* key_opt ::= */ yytestcase(yyruleno==296);
126354 { yygotominor.yy132 = 0; }
126355         break;
126356       case 276: /* when_clause ::= WHEN expr */
126357       case 297: /* key_opt ::= KEY expr */ yytestcase(yyruleno==297);
126358 { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
126359         break;
126360       case 277: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
126361 {
126362   assert( yymsp[-2].minor.yy473!=0 );
126363   yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
126364   yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
126365   yygotominor.yy473 = yymsp[-2].minor.yy473;
126366 }
126367         break;
126368       case 278: /* trigger_cmd_list ::= trigger_cmd SEMI */
126369 {
126370   assert( yymsp[-1].minor.yy473!=0 );
126371   yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
126372   yygotominor.yy473 = yymsp[-1].minor.yy473;
126373 }
126374         break;
126375       case 280: /* trnm ::= nm DOT nm */
126376 {
126377   yygotominor.yy0 = yymsp[0].minor.yy0;
126378   sqlite3ErrorMsg(pParse,
126379         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
126380         "statements within triggers");
126381 }
126382         break;
126383       case 282: /* tridxby ::= INDEXED BY nm */
126384 {
126385   sqlite3ErrorMsg(pParse,
126386         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
126387         "within triggers");
126388 }
126389         break;
126390       case 283: /* tridxby ::= NOT INDEXED */
126391 {
126392   sqlite3ErrorMsg(pParse,
126393         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
126394         "within triggers");
126395 }
126396         break;
126397       case 284: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
126398 { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
126399         break;
126400       case 285: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
126401 {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
126402         break;
126403       case 286: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
126404 {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
126405         break;
126406       case 287: /* trigger_cmd ::= select */
126407 {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
126408         break;
126409       case 288: /* expr ::= RAISE LP IGNORE RP */
126410 {
126411   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
126412   if( yygotominor.yy346.pExpr ){
126413     yygotominor.yy346.pExpr->affinity = OE_Ignore;
126414   }
126415   yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
126416   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
126417 }
126418         break;
126419       case 289: /* expr ::= RAISE LP raisetype COMMA nm RP */
126420 {
126421   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
126422   if( yygotominor.yy346.pExpr ) {
126423     yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
126424   }
126425   yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
126426   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
126427 }
126428         break;
126429       case 290: /* raisetype ::= ROLLBACK */
126430 {yygotominor.yy328 = OE_Rollback;}
126431         break;
126432       case 292: /* raisetype ::= FAIL */
126433 {yygotominor.yy328 = OE_Fail;}
126434         break;
126435       case 293: /* cmd ::= DROP TRIGGER ifexists fullname */
126436 {
126437   sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
126438 }
126439         break;
126440       case 294: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
126441 {
126442   sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
126443 }
126444         break;
126445       case 295: /* cmd ::= DETACH database_kw_opt expr */
126446 {
126447   sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
126448 }
126449         break;
126450       case 300: /* cmd ::= REINDEX */
126451 {sqlite3Reindex(pParse, 0, 0);}
126452         break;
126453       case 301: /* cmd ::= REINDEX nm dbnm */
126454 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
126455         break;
126456       case 302: /* cmd ::= ANALYZE */
126457 {sqlite3Analyze(pParse, 0, 0);}
126458         break;
126459       case 303: /* cmd ::= ANALYZE nm dbnm */
126460 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
126461         break;
126462       case 304: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
126463 {
126464   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
126465 }
126466         break;
126467       case 305: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
126468 {
126469   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
126470 }
126471         break;
126472       case 306: /* add_column_fullname ::= fullname */
126473 {
126474   pParse->db->lookaside.bEnabled = 0;
126475   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
126476 }
126477         break;
126478       case 309: /* cmd ::= create_vtab */
126479 {sqlite3VtabFinishParse(pParse,0);}
126480         break;
126481       case 310: /* cmd ::= create_vtab LP vtabarglist RP */
126482 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
126483         break;
126484       case 311: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
126485 {
126486     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
126487 }
126488         break;
126489       case 314: /* vtabarg ::= */
126490 {sqlite3VtabArgInit(pParse);}
126491         break;
126492       case 316: /* vtabargtoken ::= ANY */
126493       case 317: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==317);
126494       case 318: /* lp ::= LP */ yytestcase(yyruleno==318);
126495 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
126496         break;
126497       case 322: /* with ::= */
126498 {yygotominor.yy59 = 0;}
126499         break;
126500       case 323: /* with ::= WITH wqlist */
126501       case 324: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==324);
126502 { yygotominor.yy59 = yymsp[0].minor.yy59; }
126503         break;
126504       case 325: /* wqlist ::= nm idxlist_opt AS LP select RP */
126505 {
126506   yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
126507 }
126508         break;
126509       case 326: /* wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP */
126510 {
126511   yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
126512 }
126513         break;
126514       default:
126515       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
126516       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
126517       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
126518       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
126519       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
126520       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
126521       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
126522       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
126523       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
126524       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
126525       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
126526       /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
126527       /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
126528       /* (43) type ::= */ yytestcase(yyruleno==43);
126529       /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
126530       /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
126531       /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
126532       /* (53) carglist ::= */ yytestcase(yyruleno==53);
126533       /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
126534       /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
126535       /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
126536       /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
126537       /* (273) foreach_clause ::= */ yytestcase(yyruleno==273);
126538       /* (274) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==274);
126539       /* (281) tridxby ::= */ yytestcase(yyruleno==281);
126540       /* (298) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==298);
126541       /* (299) database_kw_opt ::= */ yytestcase(yyruleno==299);
126542       /* (307) kwcolumn_opt ::= */ yytestcase(yyruleno==307);
126543       /* (308) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==308);
126544       /* (312) vtabarglist ::= vtabarg */ yytestcase(yyruleno==312);
126545       /* (313) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==313);
126546       /* (315) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==315);
126547       /* (319) anylist ::= */ yytestcase(yyruleno==319);
126548       /* (320) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==320);
126549       /* (321) anylist ::= anylist ANY */ yytestcase(yyruleno==321);
126550         break;
126551   };
126552   assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
126553   yygoto = yyRuleInfo[yyruleno].lhs;
126554   yysize = yyRuleInfo[yyruleno].nrhs;
126555   yypParser->yyidx -= yysize;
126556   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
126557   if( yyact < YYNSTATE ){
126558 #ifdef NDEBUG
126559     /* If we are not debugging and the reduce action popped at least
126560     ** one element off the stack, then we can push the new element back
126561     ** onto the stack here, and skip the stack overflow test in yy_shift().
126562     ** That gives a significant speed improvement. */
126563     if( yysize ){
126564       yypParser->yyidx++;
126565       yymsp -= yysize-1;
126566       yymsp->stateno = (YYACTIONTYPE)yyact;
126567       yymsp->major = (YYCODETYPE)yygoto;
126568       yymsp->minor = yygotominor;
126569     }else
126570 #endif
126571     {
126572       yy_shift(yypParser,yyact,yygoto,&yygotominor);
126573     }
126574   }else{
126575     assert( yyact == YYNSTATE + YYNRULE + 1 );
126576     yy_accept(yypParser);
126577   }
126578 }
126579 
126580 /*
126581 ** The following code executes when the parse fails
126582 */
126583 #ifndef YYNOERRORRECOVERY
126584 static void yy_parse_failed(
126585   yyParser *yypParser           /* The parser */
126586 ){
126587   sqlite3ParserARG_FETCH;
126588 #ifndef NDEBUG
126589   if( yyTraceFILE ){
126590     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
126591   }
126592 #endif
126593   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
126594   /* Here code is inserted which will be executed whenever the
126595   ** parser fails */
126596   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
126597 }
126598 #endif /* YYNOERRORRECOVERY */
126599 
126600 /*
126601 ** The following code executes when a syntax error first occurs.
126602 */
126603 static void yy_syntax_error(
126604   yyParser *yypParser,           /* The parser */
126605   int yymajor,                   /* The major type of the error token */
126606   YYMINORTYPE yyminor            /* The minor type of the error token */
126607 ){
126608   sqlite3ParserARG_FETCH;
126609 #define TOKEN (yyminor.yy0)
126610 
126611   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
126612   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
126613   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
126614   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
126615 }
126616 
126617 /*
126618 ** The following is executed when the parser accepts
126619 */
126620 static void yy_accept(
126621   yyParser *yypParser           /* The parser */
126622 ){
126623   sqlite3ParserARG_FETCH;
126624 #ifndef NDEBUG
126625   if( yyTraceFILE ){
126626     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
126627   }
126628 #endif
126629   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
126630   /* Here code is inserted which will be executed whenever the
126631   ** parser accepts */
126632   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
126633 }
126634 
126635 /* The main parser program.
126636 ** The first argument is a pointer to a structure obtained from
126637 ** "sqlite3ParserAlloc" which describes the current state of the parser.
126638 ** The second argument is the major token number.  The third is
126639 ** the minor token.  The fourth optional argument is whatever the
126640 ** user wants (and specified in the grammar) and is available for
126641 ** use by the action routines.
126642 **
126643 ** Inputs:
126644 ** <ul>
126645 ** <li> A pointer to the parser (an opaque structure.)
126646 ** <li> The major token number.
126647 ** <li> The minor token number.
126648 ** <li> An option argument of a grammar-specified type.
126649 ** </ul>
126650 **
126651 ** Outputs:
126652 ** None.
126653 */
126654 SQLITE_PRIVATE void sqlite3Parser(
126655   void *yyp,                   /* The parser */
126656   int yymajor,                 /* The major token code number */
126657   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
126658   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
126659 ){
126660   YYMINORTYPE yyminorunion;
126661   int yyact;            /* The parser action. */
126662 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
126663   int yyendofinput;     /* True if we are at the end of input */
126664 #endif
126665 #ifdef YYERRORSYMBOL
126666   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
126667 #endif
126668   yyParser *yypParser;  /* The parser */
126669 
126670   /* (re)initialize the parser, if necessary */
126671   yypParser = (yyParser*)yyp;
126672   if( yypParser->yyidx<0 ){
126673 #if YYSTACKDEPTH<=0
126674     if( yypParser->yystksz <=0 ){
126675       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
126676       yyminorunion = yyzerominor;
126677       yyStackOverflow(yypParser, &yyminorunion);
126678       return;
126679     }
126680 #endif
126681     yypParser->yyidx = 0;
126682     yypParser->yyerrcnt = -1;
126683     yypParser->yystack[0].stateno = 0;
126684     yypParser->yystack[0].major = 0;
126685   }
126686   yyminorunion.yy0 = yyminor;
126687 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
126688   yyendofinput = (yymajor==0);
126689 #endif
126690   sqlite3ParserARG_STORE;
126691 
126692 #ifndef NDEBUG
126693   if( yyTraceFILE ){
126694     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
126695   }
126696 #endif
126697 
126698   do{
126699     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
126700     if( yyact<YYNSTATE ){
126701       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
126702       yypParser->yyerrcnt--;
126703       yymajor = YYNOCODE;
126704     }else if( yyact < YYNSTATE + YYNRULE ){
126705       yy_reduce(yypParser,yyact-YYNSTATE);
126706     }else{
126707       assert( yyact == YY_ERROR_ACTION );
126708 #ifdef YYERRORSYMBOL
126709       int yymx;
126710 #endif
126711 #ifndef NDEBUG
126712       if( yyTraceFILE ){
126713         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
126714       }
126715 #endif
126716 #ifdef YYERRORSYMBOL
126717       /* A syntax error has occurred.
126718       ** The response to an error depends upon whether or not the
126719       ** grammar defines an error token "ERROR".
126720       **
126721       ** This is what we do if the grammar does define ERROR:
126722       **
126723       **  * Call the %syntax_error function.
126724       **
126725       **  * Begin popping the stack until we enter a state where
126726       **    it is legal to shift the error symbol, then shift
126727       **    the error symbol.
126728       **
126729       **  * Set the error count to three.
126730       **
126731       **  * Begin accepting and shifting new tokens.  No new error
126732       **    processing will occur until three tokens have been
126733       **    shifted successfully.
126734       **
126735       */
126736       if( yypParser->yyerrcnt<0 ){
126737         yy_syntax_error(yypParser,yymajor,yyminorunion);
126738       }
126739       yymx = yypParser->yystack[yypParser->yyidx].major;
126740       if( yymx==YYERRORSYMBOL || yyerrorhit ){
126741 #ifndef NDEBUG
126742         if( yyTraceFILE ){
126743           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
126744              yyTracePrompt,yyTokenName[yymajor]);
126745         }
126746 #endif
126747         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
126748         yymajor = YYNOCODE;
126749       }else{
126750          while(
126751           yypParser->yyidx >= 0 &&
126752           yymx != YYERRORSYMBOL &&
126753           (yyact = yy_find_reduce_action(
126754                         yypParser->yystack[yypParser->yyidx].stateno,
126755                         YYERRORSYMBOL)) >= YYNSTATE
126756         ){
126757           yy_pop_parser_stack(yypParser);
126758         }
126759         if( yypParser->yyidx < 0 || yymajor==0 ){
126760           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
126761           yy_parse_failed(yypParser);
126762           yymajor = YYNOCODE;
126763         }else if( yymx!=YYERRORSYMBOL ){
126764           YYMINORTYPE u2;
126765           u2.YYERRSYMDT = 0;
126766           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
126767         }
126768       }
126769       yypParser->yyerrcnt = 3;
126770       yyerrorhit = 1;
126771 #elif defined(YYNOERRORRECOVERY)
126772       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
126773       ** do any kind of error recovery.  Instead, simply invoke the syntax
126774       ** error routine and continue going as if nothing had happened.
126775       **
126776       ** Applications can set this macro (for example inside %include) if
126777       ** they intend to abandon the parse upon the first syntax error seen.
126778       */
126779       yy_syntax_error(yypParser,yymajor,yyminorunion);
126780       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
126781       yymajor = YYNOCODE;
126782 
126783 #else  /* YYERRORSYMBOL is not defined */
126784       /* This is what we do if the grammar does not define ERROR:
126785       **
126786       **  * Report an error message, and throw away the input token.
126787       **
126788       **  * If the input token is $, then fail the parse.
126789       **
126790       ** As before, subsequent error messages are suppressed until
126791       ** three input tokens have been successfully shifted.
126792       */
126793       if( yypParser->yyerrcnt<=0 ){
126794         yy_syntax_error(yypParser,yymajor,yyminorunion);
126795       }
126796       yypParser->yyerrcnt = 3;
126797       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
126798       if( yyendofinput ){
126799         yy_parse_failed(yypParser);
126800       }
126801       yymajor = YYNOCODE;
126802 #endif
126803     }
126804   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
126805   return;
126806 }
126807 
126808 /************** End of parse.c ***********************************************/
126809 /************** Begin file tokenize.c ****************************************/
126810 /*
126811 ** 2001 September 15
126812 **
126813 ** The author disclaims copyright to this source code.  In place of
126814 ** a legal notice, here is a blessing:
126815 **
126816 **    May you do good and not evil.
126817 **    May you find forgiveness for yourself and forgive others.
126818 **    May you share freely, never taking more than you give.
126819 **
126820 *************************************************************************
126821 ** An tokenizer for SQL
126822 **
126823 ** This file contains C code that splits an SQL input string up into
126824 ** individual tokens and sends those tokens one-by-one over to the
126825 ** parser for analysis.
126826 */
126827 /* #include <stdlib.h> */
126828 
126829 /*
126830 ** The charMap() macro maps alphabetic characters into their
126831 ** lower-case ASCII equivalent.  On ASCII machines, this is just
126832 ** an upper-to-lower case map.  On EBCDIC machines we also need
126833 ** to adjust the encoding.  Only alphabetic characters and underscores
126834 ** need to be translated.
126835 */
126836 #ifdef SQLITE_ASCII
126837 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
126838 #endif
126839 #ifdef SQLITE_EBCDIC
126840 # define charMap(X) ebcdicToAscii[(unsigned char)X]
126841 const unsigned char ebcdicToAscii[] = {
126842 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
126843    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
126844    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
126845    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
126846    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
126847    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
126848    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
126849    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
126850    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
126851    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
126852    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
126853    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
126854    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
126855    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
126856    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
126857    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
126858    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
126859 };
126860 #endif
126861 
126862 /*
126863 ** The sqlite3KeywordCode function looks up an identifier to determine if
126864 ** it is a keyword.  If it is a keyword, the token code of that keyword is
126865 ** returned.  If the input is not a keyword, TK_ID is returned.
126866 **
126867 ** The implementation of this routine was generated by a program,
126868 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
126869 ** The output of the mkkeywordhash.c program is written into a file
126870 ** named keywordhash.h and then included into this source file by
126871 ** the #include below.
126872 */
126873 /************** Include keywordhash.h in the middle of tokenize.c ************/
126874 /************** Begin file keywordhash.h *************************************/
126875 /***** This file contains automatically generated code ******
126876 **
126877 ** The code in this file has been automatically generated by
126878 **
126879 **   sqlite/tool/mkkeywordhash.c
126880 **
126881 ** The code in this file implements a function that determines whether
126882 ** or not a given identifier is really an SQL keyword.  The same thing
126883 ** might be implemented more directly using a hand-written hash table.
126884 ** But by using this automatically generated code, the size of the code
126885 ** is substantially reduced.  This is important for embedded applications
126886 ** on platforms with limited memory.
126887 */
126888 /* Hash score: 182 */
126889 static int keywordCode(const char *z, int n){
126890   /* zText[] encodes 834 bytes of keywords in 554 bytes */
126891   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
126892   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
126893   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
126894   /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
126895   /*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
126896   /*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
126897   /*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
126898   /*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
126899   /*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
126900   /*   VACUUMVIEWINITIALLY                                                */
126901   static const char zText[553] = {
126902     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
126903     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
126904     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
126905     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
126906     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
126907     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
126908     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
126909     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
126910     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
126911     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
126912     'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
126913     'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
126914     'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
126915     'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
126916     'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
126917     'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
126918     'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
126919     'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
126920     'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
126921     'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
126922     'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
126923     'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
126924     'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
126925     'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
126926     'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
126927     'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
126928     'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
126929     'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
126930     'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
126931     'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
126932     'V','I','E','W','I','N','I','T','I','A','L','L','Y',
126933   };
126934   static const unsigned char aHash[127] = {
126935       76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
126936       42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
126937      121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
126938        0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
126939        0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
126940       96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
126941      100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
126942       39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
126943       62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
126944       29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
126945   };
126946   static const unsigned char aNext[124] = {
126947        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
126948        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
126949        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
126950        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
126951        0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
126952        0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
126953        0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
126954       10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
126955        0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
126956       73,  83,   0,  35,  68,   0,   0,
126957   };
126958   static const unsigned char aLen[124] = {
126959        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
126960        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
126961       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
126962        4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
126963        6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
126964        7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
126965        7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
126966       13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
126967        2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
126968        3,   5,   5,   6,   4,   9,   3,
126969   };
126970   static const unsigned short int aOffset[124] = {
126971        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
126972       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
126973       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
126974      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
126975      199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
126976      250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
126977      320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
126978      387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
126979      460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
126980      521, 524, 529, 534, 540, 544, 549,
126981   };
126982   static const unsigned char aCode[124] = {
126983     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
126984     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
126985     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
126986     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
126987     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
126988     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
126989     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
126990     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
126991     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
126992     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,
126993     TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,
126994     TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,
126995     TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,
126996     TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,
126997     TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,
126998     TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,
126999     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,
127000     TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,
127001     TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,
127002     TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,
127003     TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,
127004     TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,
127005     TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,
127006     TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,
127007     TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,
127008   };
127009   int h, i;
127010   if( n<2 ) return TK_ID;
127011   h = ((charMap(z[0])*4) ^
127012       (charMap(z[n-1])*3) ^
127013       n) % 127;
127014   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
127015     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
127016       testcase( i==0 ); /* REINDEX */
127017       testcase( i==1 ); /* INDEXED */
127018       testcase( i==2 ); /* INDEX */
127019       testcase( i==3 ); /* DESC */
127020       testcase( i==4 ); /* ESCAPE */
127021       testcase( i==5 ); /* EACH */
127022       testcase( i==6 ); /* CHECK */
127023       testcase( i==7 ); /* KEY */
127024       testcase( i==8 ); /* BEFORE */
127025       testcase( i==9 ); /* FOREIGN */
127026       testcase( i==10 ); /* FOR */
127027       testcase( i==11 ); /* IGNORE */
127028       testcase( i==12 ); /* REGEXP */
127029       testcase( i==13 ); /* EXPLAIN */
127030       testcase( i==14 ); /* INSTEAD */
127031       testcase( i==15 ); /* ADD */
127032       testcase( i==16 ); /* DATABASE */
127033       testcase( i==17 ); /* AS */
127034       testcase( i==18 ); /* SELECT */
127035       testcase( i==19 ); /* TABLE */
127036       testcase( i==20 ); /* LEFT */
127037       testcase( i==21 ); /* THEN */
127038       testcase( i==22 ); /* END */
127039       testcase( i==23 ); /* DEFERRABLE */
127040       testcase( i==24 ); /* ELSE */
127041       testcase( i==25 ); /* EXCEPT */
127042       testcase( i==26 ); /* TRANSACTION */
127043       testcase( i==27 ); /* ACTION */
127044       testcase( i==28 ); /* ON */
127045       testcase( i==29 ); /* NATURAL */
127046       testcase( i==30 ); /* ALTER */
127047       testcase( i==31 ); /* RAISE */
127048       testcase( i==32 ); /* EXCLUSIVE */
127049       testcase( i==33 ); /* EXISTS */
127050       testcase( i==34 ); /* SAVEPOINT */
127051       testcase( i==35 ); /* INTERSECT */
127052       testcase( i==36 ); /* TRIGGER */
127053       testcase( i==37 ); /* REFERENCES */
127054       testcase( i==38 ); /* CONSTRAINT */
127055       testcase( i==39 ); /* INTO */
127056       testcase( i==40 ); /* OFFSET */
127057       testcase( i==41 ); /* OF */
127058       testcase( i==42 ); /* SET */
127059       testcase( i==43 ); /* TEMPORARY */
127060       testcase( i==44 ); /* TEMP */
127061       testcase( i==45 ); /* OR */
127062       testcase( i==46 ); /* UNIQUE */
127063       testcase( i==47 ); /* QUERY */
127064       testcase( i==48 ); /* WITHOUT */
127065       testcase( i==49 ); /* WITH */
127066       testcase( i==50 ); /* OUTER */
127067       testcase( i==51 ); /* RELEASE */
127068       testcase( i==52 ); /* ATTACH */
127069       testcase( i==53 ); /* HAVING */
127070       testcase( i==54 ); /* GROUP */
127071       testcase( i==55 ); /* UPDATE */
127072       testcase( i==56 ); /* BEGIN */
127073       testcase( i==57 ); /* INNER */
127074       testcase( i==58 ); /* RECURSIVE */
127075       testcase( i==59 ); /* BETWEEN */
127076       testcase( i==60 ); /* NOTNULL */
127077       testcase( i==61 ); /* NOT */
127078       testcase( i==62 ); /* NO */
127079       testcase( i==63 ); /* NULL */
127080       testcase( i==64 ); /* LIKE */
127081       testcase( i==65 ); /* CASCADE */
127082       testcase( i==66 ); /* ASC */
127083       testcase( i==67 ); /* DELETE */
127084       testcase( i==68 ); /* CASE */
127085       testcase( i==69 ); /* COLLATE */
127086       testcase( i==70 ); /* CREATE */
127087       testcase( i==71 ); /* CURRENT_DATE */
127088       testcase( i==72 ); /* DETACH */
127089       testcase( i==73 ); /* IMMEDIATE */
127090       testcase( i==74 ); /* JOIN */
127091       testcase( i==75 ); /* INSERT */
127092       testcase( i==76 ); /* MATCH */
127093       testcase( i==77 ); /* PLAN */
127094       testcase( i==78 ); /* ANALYZE */
127095       testcase( i==79 ); /* PRAGMA */
127096       testcase( i==80 ); /* ABORT */
127097       testcase( i==81 ); /* VALUES */
127098       testcase( i==82 ); /* VIRTUAL */
127099       testcase( i==83 ); /* LIMIT */
127100       testcase( i==84 ); /* WHEN */
127101       testcase( i==85 ); /* WHERE */
127102       testcase( i==86 ); /* RENAME */
127103       testcase( i==87 ); /* AFTER */
127104       testcase( i==88 ); /* REPLACE */
127105       testcase( i==89 ); /* AND */
127106       testcase( i==90 ); /* DEFAULT */
127107       testcase( i==91 ); /* AUTOINCREMENT */
127108       testcase( i==92 ); /* TO */
127109       testcase( i==93 ); /* IN */
127110       testcase( i==94 ); /* CAST */
127111       testcase( i==95 ); /* COLUMN */
127112       testcase( i==96 ); /* COMMIT */
127113       testcase( i==97 ); /* CONFLICT */
127114       testcase( i==98 ); /* CROSS */
127115       testcase( i==99 ); /* CURRENT_TIMESTAMP */
127116       testcase( i==100 ); /* CURRENT_TIME */
127117       testcase( i==101 ); /* PRIMARY */
127118       testcase( i==102 ); /* DEFERRED */
127119       testcase( i==103 ); /* DISTINCT */
127120       testcase( i==104 ); /* IS */
127121       testcase( i==105 ); /* DROP */
127122       testcase( i==106 ); /* FAIL */
127123       testcase( i==107 ); /* FROM */
127124       testcase( i==108 ); /* FULL */
127125       testcase( i==109 ); /* GLOB */
127126       testcase( i==110 ); /* BY */
127127       testcase( i==111 ); /* IF */
127128       testcase( i==112 ); /* ISNULL */
127129       testcase( i==113 ); /* ORDER */
127130       testcase( i==114 ); /* RESTRICT */
127131       testcase( i==115 ); /* RIGHT */
127132       testcase( i==116 ); /* ROLLBACK */
127133       testcase( i==117 ); /* ROW */
127134       testcase( i==118 ); /* UNION */
127135       testcase( i==119 ); /* USING */
127136       testcase( i==120 ); /* VACUUM */
127137       testcase( i==121 ); /* VIEW */
127138       testcase( i==122 ); /* INITIALLY */
127139       testcase( i==123 ); /* ALL */
127140       return aCode[i];
127141     }
127142   }
127143   return TK_ID;
127144 }
127145 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
127146   return keywordCode((char*)z, n);
127147 }
127148 #define SQLITE_N_KEYWORD 124
127149 
127150 /************** End of keywordhash.h *****************************************/
127151 /************** Continuing where we left off in tokenize.c *******************/
127152 
127153 
127154 /*
127155 ** If X is a character that can be used in an identifier then
127156 ** IdChar(X) will be true.  Otherwise it is false.
127157 **
127158 ** For ASCII, any character with the high-order bit set is
127159 ** allowed in an identifier.  For 7-bit characters,
127160 ** sqlite3IsIdChar[X] must be 1.
127161 **
127162 ** For EBCDIC, the rules are more complex but have the same
127163 ** end result.
127164 **
127165 ** Ticket #1066.  the SQL standard does not allow '$' in the
127166 ** middle of identifiers.  But many SQL implementations do.
127167 ** SQLite will allow '$' in identifiers for compatibility.
127168 ** But the feature is undocumented.
127169 */
127170 #ifdef SQLITE_ASCII
127171 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
127172 #endif
127173 #ifdef SQLITE_EBCDIC
127174 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
127175 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
127176     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
127177     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
127178     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
127179     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
127180     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
127181     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
127182     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
127183     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
127184     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
127185     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
127186     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
127187     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
127188 };
127189 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
127190 #endif
127191 SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
127192 
127193 
127194 /*
127195 ** Return the length of the token that begins at z[0].
127196 ** Store the token type in *tokenType before returning.
127197 */
127198 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
127199   int i, c;
127200   switch( *z ){
127201     case ' ': case '\t': case '\n': case '\f': case '\r': {
127202       testcase( z[0]==' ' );
127203       testcase( z[0]=='\t' );
127204       testcase( z[0]=='\n' );
127205       testcase( z[0]=='\f' );
127206       testcase( z[0]=='\r' );
127207       for(i=1; sqlite3Isspace(z[i]); i++){}
127208       *tokenType = TK_SPACE;
127209       return i;
127210     }
127211     case '-': {
127212       if( z[1]=='-' ){
127213         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
127214         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
127215         return i;
127216       }
127217       *tokenType = TK_MINUS;
127218       return 1;
127219     }
127220     case '(': {
127221       *tokenType = TK_LP;
127222       return 1;
127223     }
127224     case ')': {
127225       *tokenType = TK_RP;
127226       return 1;
127227     }
127228     case ';': {
127229       *tokenType = TK_SEMI;
127230       return 1;
127231     }
127232     case '+': {
127233       *tokenType = TK_PLUS;
127234       return 1;
127235     }
127236     case '*': {
127237       *tokenType = TK_STAR;
127238       return 1;
127239     }
127240     case '/': {
127241       if( z[1]!='*' || z[2]==0 ){
127242         *tokenType = TK_SLASH;
127243         return 1;
127244       }
127245       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
127246       if( c ) i++;
127247       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
127248       return i;
127249     }
127250     case '%': {
127251       *tokenType = TK_REM;
127252       return 1;
127253     }
127254     case '=': {
127255       *tokenType = TK_EQ;
127256       return 1 + (z[1]=='=');
127257     }
127258     case '<': {
127259       if( (c=z[1])=='=' ){
127260         *tokenType = TK_LE;
127261         return 2;
127262       }else if( c=='>' ){
127263         *tokenType = TK_NE;
127264         return 2;
127265       }else if( c=='<' ){
127266         *tokenType = TK_LSHIFT;
127267         return 2;
127268       }else{
127269         *tokenType = TK_LT;
127270         return 1;
127271       }
127272     }
127273     case '>': {
127274       if( (c=z[1])=='=' ){
127275         *tokenType = TK_GE;
127276         return 2;
127277       }else if( c=='>' ){
127278         *tokenType = TK_RSHIFT;
127279         return 2;
127280       }else{
127281         *tokenType = TK_GT;
127282         return 1;
127283       }
127284     }
127285     case '!': {
127286       if( z[1]!='=' ){
127287         *tokenType = TK_ILLEGAL;
127288         return 2;
127289       }else{
127290         *tokenType = TK_NE;
127291         return 2;
127292       }
127293     }
127294     case '|': {
127295       if( z[1]!='|' ){
127296         *tokenType = TK_BITOR;
127297         return 1;
127298       }else{
127299         *tokenType = TK_CONCAT;
127300         return 2;
127301       }
127302     }
127303     case ',': {
127304       *tokenType = TK_COMMA;
127305       return 1;
127306     }
127307     case '&': {
127308       *tokenType = TK_BITAND;
127309       return 1;
127310     }
127311     case '~': {
127312       *tokenType = TK_BITNOT;
127313       return 1;
127314     }
127315     case '`':
127316     case '\'':
127317     case '"': {
127318       int delim = z[0];
127319       testcase( delim=='`' );
127320       testcase( delim=='\'' );
127321       testcase( delim=='"' );
127322       for(i=1; (c=z[i])!=0; i++){
127323         if( c==delim ){
127324           if( z[i+1]==delim ){
127325             i++;
127326           }else{
127327             break;
127328           }
127329         }
127330       }
127331       if( c=='\'' ){
127332         *tokenType = TK_STRING;
127333         return i+1;
127334       }else if( c!=0 ){
127335         *tokenType = TK_ID;
127336         return i+1;
127337       }else{
127338         *tokenType = TK_ILLEGAL;
127339         return i;
127340       }
127341     }
127342     case '.': {
127343 #ifndef SQLITE_OMIT_FLOATING_POINT
127344       if( !sqlite3Isdigit(z[1]) )
127345 #endif
127346       {
127347         *tokenType = TK_DOT;
127348         return 1;
127349       }
127350       /* If the next character is a digit, this is a floating point
127351       ** number that begins with ".".  Fall thru into the next case */
127352     }
127353     case '0': case '1': case '2': case '3': case '4':
127354     case '5': case '6': case '7': case '8': case '9': {
127355       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
127356       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
127357       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
127358       testcase( z[0]=='9' );
127359       *tokenType = TK_INTEGER;
127360 #ifndef SQLITE_OMIT_HEX_INTEGER
127361       if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
127362         for(i=3; sqlite3Isxdigit(z[i]); i++){}
127363         return i;
127364       }
127365 #endif
127366       for(i=0; sqlite3Isdigit(z[i]); i++){}
127367 #ifndef SQLITE_OMIT_FLOATING_POINT
127368       if( z[i]=='.' ){
127369         i++;
127370         while( sqlite3Isdigit(z[i]) ){ i++; }
127371         *tokenType = TK_FLOAT;
127372       }
127373       if( (z[i]=='e' || z[i]=='E') &&
127374            ( sqlite3Isdigit(z[i+1])
127375             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
127376            )
127377       ){
127378         i += 2;
127379         while( sqlite3Isdigit(z[i]) ){ i++; }
127380         *tokenType = TK_FLOAT;
127381       }
127382 #endif
127383       while( IdChar(z[i]) ){
127384         *tokenType = TK_ILLEGAL;
127385         i++;
127386       }
127387       return i;
127388     }
127389     case '[': {
127390       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
127391       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
127392       return i;
127393     }
127394     case '?': {
127395       *tokenType = TK_VARIABLE;
127396       for(i=1; sqlite3Isdigit(z[i]); i++){}
127397       return i;
127398     }
127399 #ifndef SQLITE_OMIT_TCL_VARIABLE
127400     case '$':
127401 #endif
127402     case '@':  /* For compatibility with MS SQL Server */
127403     case '#':
127404     case ':': {
127405       int n = 0;
127406       testcase( z[0]=='$' );  testcase( z[0]=='@' );
127407       testcase( z[0]==':' );  testcase( z[0]=='#' );
127408       *tokenType = TK_VARIABLE;
127409       for(i=1; (c=z[i])!=0; i++){
127410         if( IdChar(c) ){
127411           n++;
127412 #ifndef SQLITE_OMIT_TCL_VARIABLE
127413         }else if( c=='(' && n>0 ){
127414           do{
127415             i++;
127416           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
127417           if( c==')' ){
127418             i++;
127419           }else{
127420             *tokenType = TK_ILLEGAL;
127421           }
127422           break;
127423         }else if( c==':' && z[i+1]==':' ){
127424           i++;
127425 #endif
127426         }else{
127427           break;
127428         }
127429       }
127430       if( n==0 ) *tokenType = TK_ILLEGAL;
127431       return i;
127432     }
127433 #ifndef SQLITE_OMIT_BLOB_LITERAL
127434     case 'x': case 'X': {
127435       testcase( z[0]=='x' ); testcase( z[0]=='X' );
127436       if( z[1]=='\'' ){
127437         *tokenType = TK_BLOB;
127438         for(i=2; sqlite3Isxdigit(z[i]); i++){}
127439         if( z[i]!='\'' || i%2 ){
127440           *tokenType = TK_ILLEGAL;
127441           while( z[i] && z[i]!='\'' ){ i++; }
127442         }
127443         if( z[i] ) i++;
127444         return i;
127445       }
127446       /* Otherwise fall through to the next case */
127447     }
127448 #endif
127449     default: {
127450       if( !IdChar(*z) ){
127451         break;
127452       }
127453       for(i=1; IdChar(z[i]); i++){}
127454       *tokenType = keywordCode((char*)z, i);
127455       return i;
127456     }
127457   }
127458   *tokenType = TK_ILLEGAL;
127459   return 1;
127460 }
127461 
127462 /*
127463 ** Run the parser on the given SQL string.  The parser structure is
127464 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
127465 ** then an and attempt is made to write an error message into
127466 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
127467 ** error message.
127468 */
127469 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
127470   int nErr = 0;                   /* Number of errors encountered */
127471   int i;                          /* Loop counter */
127472   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
127473   int tokenType;                  /* type of the next token */
127474   int lastTokenParsed = -1;       /* type of the previous token */
127475   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
127476   sqlite3 *db = pParse->db;       /* The database connection */
127477   int mxSqlLen;                   /* Max length of an SQL string */
127478 
127479   assert( zSql!=0 );
127480   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
127481   if( db->nVdbeActive==0 ){
127482     db->u1.isInterrupted = 0;
127483   }
127484   pParse->rc = SQLITE_OK;
127485   pParse->zTail = zSql;
127486   i = 0;
127487   assert( pzErrMsg!=0 );
127488   pEngine = sqlite3ParserAlloc(sqlite3Malloc);
127489   if( pEngine==0 ){
127490     db->mallocFailed = 1;
127491     return SQLITE_NOMEM;
127492   }
127493   assert( pParse->pNewTable==0 );
127494   assert( pParse->pNewTrigger==0 );
127495   assert( pParse->nVar==0 );
127496   assert( pParse->nzVar==0 );
127497   assert( pParse->azVar==0 );
127498   enableLookaside = db->lookaside.bEnabled;
127499   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
127500   while( !db->mallocFailed && zSql[i]!=0 ){
127501     assert( i>=0 );
127502     pParse->sLastToken.z = &zSql[i];
127503     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
127504     i += pParse->sLastToken.n;
127505     if( i>mxSqlLen ){
127506       pParse->rc = SQLITE_TOOBIG;
127507       break;
127508     }
127509     switch( tokenType ){
127510       case TK_SPACE: {
127511         if( db->u1.isInterrupted ){
127512           sqlite3ErrorMsg(pParse, "interrupt");
127513           pParse->rc = SQLITE_INTERRUPT;
127514           goto abort_parse;
127515         }
127516         break;
127517       }
127518       case TK_ILLEGAL: {
127519         sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
127520                         &pParse->sLastToken);
127521         goto abort_parse;
127522       }
127523       case TK_SEMI: {
127524         pParse->zTail = &zSql[i];
127525         /* Fall thru into the default case */
127526       }
127527       default: {
127528         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
127529         lastTokenParsed = tokenType;
127530         if( pParse->rc!=SQLITE_OK ){
127531           goto abort_parse;
127532         }
127533         break;
127534       }
127535     }
127536   }
127537 abort_parse:
127538   assert( nErr==0 );
127539   if( zSql[i]==0 && pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
127540     if( lastTokenParsed!=TK_SEMI ){
127541       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
127542       pParse->zTail = &zSql[i];
127543     }
127544     if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
127545       sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
127546     }
127547   }
127548 #ifdef YYTRACKMAXSTACKDEPTH
127549   sqlite3_mutex_enter(sqlite3MallocMutex());
127550   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
127551       sqlite3ParserStackPeak(pEngine)
127552   );
127553   sqlite3_mutex_leave(sqlite3MallocMutex());
127554 #endif /* YYDEBUG */
127555   sqlite3ParserFree(pEngine, sqlite3_free);
127556   db->lookaside.bEnabled = enableLookaside;
127557   if( db->mallocFailed ){
127558     pParse->rc = SQLITE_NOMEM;
127559   }
127560   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
127561     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
127562   }
127563   assert( pzErrMsg!=0 );
127564   if( pParse->zErrMsg ){
127565     *pzErrMsg = pParse->zErrMsg;
127566     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
127567     pParse->zErrMsg = 0;
127568     nErr++;
127569   }
127570   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
127571     sqlite3VdbeDelete(pParse->pVdbe);
127572     pParse->pVdbe = 0;
127573   }
127574 #ifndef SQLITE_OMIT_SHARED_CACHE
127575   if( pParse->nested==0 ){
127576     sqlite3DbFree(db, pParse->aTableLock);
127577     pParse->aTableLock = 0;
127578     pParse->nTableLock = 0;
127579   }
127580 #endif
127581 #ifndef SQLITE_OMIT_VIRTUALTABLE
127582   sqlite3_free(pParse->apVtabLock);
127583 #endif
127584 
127585   if( !IN_DECLARE_VTAB ){
127586     /* If the pParse->declareVtab flag is set, do not delete any table
127587     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
127588     ** will take responsibility for freeing the Table structure.
127589     */
127590     sqlite3DeleteTable(db, pParse->pNewTable);
127591   }
127592 
127593   if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
127594   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
127595   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
127596   sqlite3DbFree(db, pParse->azVar);
127597   while( pParse->pAinc ){
127598     AutoincInfo *p = pParse->pAinc;
127599     pParse->pAinc = p->pNext;
127600     sqlite3DbFree(db, p);
127601   }
127602   while( pParse->pZombieTab ){
127603     Table *p = pParse->pZombieTab;
127604     pParse->pZombieTab = p->pNextZombie;
127605     sqlite3DeleteTable(db, p);
127606   }
127607   assert( nErr==0 || pParse->rc!=SQLITE_OK );
127608   return nErr;
127609 }
127610 
127611 /************** End of tokenize.c ********************************************/
127612 /************** Begin file complete.c ****************************************/
127613 /*
127614 ** 2001 September 15
127615 **
127616 ** The author disclaims copyright to this source code.  In place of
127617 ** a legal notice, here is a blessing:
127618 **
127619 **    May you do good and not evil.
127620 **    May you find forgiveness for yourself and forgive others.
127621 **    May you share freely, never taking more than you give.
127622 **
127623 *************************************************************************
127624 ** An tokenizer for SQL
127625 **
127626 ** This file contains C code that implements the sqlite3_complete() API.
127627 ** This code used to be part of the tokenizer.c source file.  But by
127628 ** separating it out, the code will be automatically omitted from
127629 ** static links that do not use it.
127630 */
127631 #ifndef SQLITE_OMIT_COMPLETE
127632 
127633 /*
127634 ** This is defined in tokenize.c.  We just have to import the definition.
127635 */
127636 #ifndef SQLITE_AMALGAMATION
127637 #ifdef SQLITE_ASCII
127638 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
127639 #endif
127640 #ifdef SQLITE_EBCDIC
127641 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
127642 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
127643 #endif
127644 #endif /* SQLITE_AMALGAMATION */
127645 
127646 
127647 /*
127648 ** Token types used by the sqlite3_complete() routine.  See the header
127649 ** comments on that procedure for additional information.
127650 */
127651 #define tkSEMI    0
127652 #define tkWS      1
127653 #define tkOTHER   2
127654 #ifndef SQLITE_OMIT_TRIGGER
127655 #define tkEXPLAIN 3
127656 #define tkCREATE  4
127657 #define tkTEMP    5
127658 #define tkTRIGGER 6
127659 #define tkEND     7
127660 #endif
127661 
127662 /*
127663 ** Return TRUE if the given SQL string ends in a semicolon.
127664 **
127665 ** Special handling is require for CREATE TRIGGER statements.
127666 ** Whenever the CREATE TRIGGER keywords are seen, the statement
127667 ** must end with ";END;".
127668 **
127669 ** This implementation uses a state machine with 8 states:
127670 **
127671 **   (0) INVALID   We have not yet seen a non-whitespace character.
127672 **
127673 **   (1) START     At the beginning or end of an SQL statement.  This routine
127674 **                 returns 1 if it ends in the START state and 0 if it ends
127675 **                 in any other state.
127676 **
127677 **   (2) NORMAL    We are in the middle of statement which ends with a single
127678 **                 semicolon.
127679 **
127680 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
127681 **                 a statement.
127682 **
127683 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
127684 **                 statement, possibly preceded by EXPLAIN and/or followed by
127685 **                 TEMP or TEMPORARY
127686 **
127687 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
127688 **                 ended by a semicolon, the keyword END, and another semicolon.
127689 **
127690 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
127691 **                 the end of a trigger definition.
127692 **
127693 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
127694 **                 of a trigger definition.
127695 **
127696 ** Transitions between states above are determined by tokens extracted
127697 ** from the input.  The following tokens are significant:
127698 **
127699 **   (0) tkSEMI      A semicolon.
127700 **   (1) tkWS        Whitespace.
127701 **   (2) tkOTHER     Any other SQL token.
127702 **   (3) tkEXPLAIN   The "explain" keyword.
127703 **   (4) tkCREATE    The "create" keyword.
127704 **   (5) tkTEMP      The "temp" or "temporary" keyword.
127705 **   (6) tkTRIGGER   The "trigger" keyword.
127706 **   (7) tkEND       The "end" keyword.
127707 **
127708 ** Whitespace never causes a state transition and is always ignored.
127709 ** This means that a SQL string of all whitespace is invalid.
127710 **
127711 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
127712 ** to recognize the end of a trigger can be omitted.  All we have to do
127713 ** is look for a semicolon that is not part of an string or comment.
127714 */
127715 SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *zSql){
127716   u8 state = 0;   /* Current state, using numbers defined in header comment */
127717   u8 token;       /* Value of the next token */
127718 
127719 #ifndef SQLITE_OMIT_TRIGGER
127720   /* A complex statement machine used to detect the end of a CREATE TRIGGER
127721   ** statement.  This is the normal case.
127722   */
127723   static const u8 trans[8][8] = {
127724                      /* Token:                                                */
127725      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
127726      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
127727      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
127728      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
127729      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
127730      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
127731      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
127732      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
127733      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
127734   };
127735 #else
127736   /* If triggers are not supported by this compile then the statement machine
127737   ** used to detect the end of a statement is much simpler
127738   */
127739   static const u8 trans[3][3] = {
127740                      /* Token:           */
127741      /* State:       **  SEMI  WS  OTHER */
127742      /* 0 INVALID: */ {    1,  0,     2, },
127743      /* 1   START: */ {    1,  1,     2, },
127744      /* 2  NORMAL: */ {    1,  2,     2, },
127745   };
127746 #endif /* SQLITE_OMIT_TRIGGER */
127747 
127748 #ifdef SQLITE_ENABLE_API_ARMOR
127749   if( zSql==0 ){
127750     (void)SQLITE_MISUSE_BKPT;
127751     return 0;
127752   }
127753 #endif
127754 
127755   while( *zSql ){
127756     switch( *zSql ){
127757       case ';': {  /* A semicolon */
127758         token = tkSEMI;
127759         break;
127760       }
127761       case ' ':
127762       case '\r':
127763       case '\t':
127764       case '\n':
127765       case '\f': {  /* White space is ignored */
127766         token = tkWS;
127767         break;
127768       }
127769       case '/': {   /* C-style comments */
127770         if( zSql[1]!='*' ){
127771           token = tkOTHER;
127772           break;
127773         }
127774         zSql += 2;
127775         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
127776         if( zSql[0]==0 ) return 0;
127777         zSql++;
127778         token = tkWS;
127779         break;
127780       }
127781       case '-': {   /* SQL-style comments from "--" to end of line */
127782         if( zSql[1]!='-' ){
127783           token = tkOTHER;
127784           break;
127785         }
127786         while( *zSql && *zSql!='\n' ){ zSql++; }
127787         if( *zSql==0 ) return state==1;
127788         token = tkWS;
127789         break;
127790       }
127791       case '[': {   /* Microsoft-style identifiers in [...] */
127792         zSql++;
127793         while( *zSql && *zSql!=']' ){ zSql++; }
127794         if( *zSql==0 ) return 0;
127795         token = tkOTHER;
127796         break;
127797       }
127798       case '`':     /* Grave-accent quoted symbols used by MySQL */
127799       case '"':     /* single- and double-quoted strings */
127800       case '\'': {
127801         int c = *zSql;
127802         zSql++;
127803         while( *zSql && *zSql!=c ){ zSql++; }
127804         if( *zSql==0 ) return 0;
127805         token = tkOTHER;
127806         break;
127807       }
127808       default: {
127809 #ifdef SQLITE_EBCDIC
127810         unsigned char c;
127811 #endif
127812         if( IdChar((u8)*zSql) ){
127813           /* Keywords and unquoted identifiers */
127814           int nId;
127815           for(nId=1; IdChar(zSql[nId]); nId++){}
127816 #ifdef SQLITE_OMIT_TRIGGER
127817           token = tkOTHER;
127818 #else
127819           switch( *zSql ){
127820             case 'c': case 'C': {
127821               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
127822                 token = tkCREATE;
127823               }else{
127824                 token = tkOTHER;
127825               }
127826               break;
127827             }
127828             case 't': case 'T': {
127829               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
127830                 token = tkTRIGGER;
127831               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
127832                 token = tkTEMP;
127833               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
127834                 token = tkTEMP;
127835               }else{
127836                 token = tkOTHER;
127837               }
127838               break;
127839             }
127840             case 'e':  case 'E': {
127841               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
127842                 token = tkEND;
127843               }else
127844 #ifndef SQLITE_OMIT_EXPLAIN
127845               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
127846                 token = tkEXPLAIN;
127847               }else
127848 #endif
127849               {
127850                 token = tkOTHER;
127851               }
127852               break;
127853             }
127854             default: {
127855               token = tkOTHER;
127856               break;
127857             }
127858           }
127859 #endif /* SQLITE_OMIT_TRIGGER */
127860           zSql += nId-1;
127861         }else{
127862           /* Operators and special symbols */
127863           token = tkOTHER;
127864         }
127865         break;
127866       }
127867     }
127868     state = trans[state][token];
127869     zSql++;
127870   }
127871   return state==1;
127872 }
127873 
127874 #ifndef SQLITE_OMIT_UTF16
127875 /*
127876 ** This routine is the same as the sqlite3_complete() routine described
127877 ** above, except that the parameter is required to be UTF-16 encoded, not
127878 ** UTF-8.
127879 */
127880 SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *zSql){
127881   sqlite3_value *pVal;
127882   char const *zSql8;
127883   int rc;
127884 
127885 #ifndef SQLITE_OMIT_AUTOINIT
127886   rc = sqlite3_initialize();
127887   if( rc ) return rc;
127888 #endif
127889   pVal = sqlite3ValueNew(0);
127890   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
127891   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
127892   if( zSql8 ){
127893     rc = sqlite3_complete(zSql8);
127894   }else{
127895     rc = SQLITE_NOMEM;
127896   }
127897   sqlite3ValueFree(pVal);
127898   return sqlite3ApiExit(0, rc);
127899 }
127900 #endif /* SQLITE_OMIT_UTF16 */
127901 #endif /* SQLITE_OMIT_COMPLETE */
127902 
127903 /************** End of complete.c ********************************************/
127904 /************** Begin file main.c ********************************************/
127905 /*
127906 ** 2001 September 15
127907 **
127908 ** The author disclaims copyright to this source code.  In place of
127909 ** a legal notice, here is a blessing:
127910 **
127911 **    May you do good and not evil.
127912 **    May you find forgiveness for yourself and forgive others.
127913 **    May you share freely, never taking more than you give.
127914 **
127915 *************************************************************************
127916 ** Main file for the SQLite library.  The routines in this file
127917 ** implement the programmer interface to the library.  Routines in
127918 ** other files are for internal use by SQLite and should not be
127919 ** accessed by users of the library.
127920 */
127921 
127922 #ifdef SQLITE_ENABLE_FTS3
127923 /************** Include fts3.h in the middle of main.c ***********************/
127924 /************** Begin file fts3.h ********************************************/
127925 /*
127926 ** 2006 Oct 10
127927 **
127928 ** The author disclaims copyright to this source code.  In place of
127929 ** a legal notice, here is a blessing:
127930 **
127931 **    May you do good and not evil.
127932 **    May you find forgiveness for yourself and forgive others.
127933 **    May you share freely, never taking more than you give.
127934 **
127935 ******************************************************************************
127936 **
127937 ** This header file is used by programs that want to link against the
127938 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
127939 */
127940 
127941 #if 0
127942 extern "C" {
127943 #endif  /* __cplusplus */
127944 
127945 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
127946 
127947 #if 0
127948 }  /* extern "C" */
127949 #endif  /* __cplusplus */
127950 
127951 /************** End of fts3.h ************************************************/
127952 /************** Continuing where we left off in main.c ***********************/
127953 #endif
127954 #ifdef SQLITE_ENABLE_RTREE
127955 /************** Include rtree.h in the middle of main.c **********************/
127956 /************** Begin file rtree.h *******************************************/
127957 /*
127958 ** 2008 May 26
127959 **
127960 ** The author disclaims copyright to this source code.  In place of
127961 ** a legal notice, here is a blessing:
127962 **
127963 **    May you do good and not evil.
127964 **    May you find forgiveness for yourself and forgive others.
127965 **    May you share freely, never taking more than you give.
127966 **
127967 ******************************************************************************
127968 **
127969 ** This header file is used by programs that want to link against the
127970 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
127971 */
127972 
127973 #if 0
127974 extern "C" {
127975 #endif  /* __cplusplus */
127976 
127977 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
127978 
127979 #if 0
127980 }  /* extern "C" */
127981 #endif  /* __cplusplus */
127982 
127983 /************** End of rtree.h ***********************************************/
127984 /************** Continuing where we left off in main.c ***********************/
127985 #endif
127986 #ifdef SQLITE_ENABLE_ICU
127987 /************** Include sqliteicu.h in the middle of main.c ******************/
127988 /************** Begin file sqliteicu.h ***************************************/
127989 /*
127990 ** 2008 May 26
127991 **
127992 ** The author disclaims copyright to this source code.  In place of
127993 ** a legal notice, here is a blessing:
127994 **
127995 **    May you do good and not evil.
127996 **    May you find forgiveness for yourself and forgive others.
127997 **    May you share freely, never taking more than you give.
127998 **
127999 ******************************************************************************
128000 **
128001 ** This header file is used by programs that want to link against the
128002 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
128003 */
128004 
128005 #if 0
128006 extern "C" {
128007 #endif  /* __cplusplus */
128008 
128009 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
128010 
128011 #if 0
128012 }  /* extern "C" */
128013 #endif  /* __cplusplus */
128014 
128015 
128016 /************** End of sqliteicu.h *******************************************/
128017 /************** Continuing where we left off in main.c ***********************/
128018 #endif
128019 
128020 #ifndef SQLITE_AMALGAMATION
128021 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
128022 ** contains the text of SQLITE_VERSION macro.
128023 */
128024 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
128025 #endif
128026 
128027 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
128028 ** a pointer to the to the sqlite3_version[] string constant.
128029 */
128030 SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void){ return sqlite3_version; }
128031 
128032 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
128033 ** pointer to a string constant whose value is the same as the
128034 ** SQLITE_SOURCE_ID C preprocessor macro.
128035 */
128036 SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
128037 
128038 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
128039 ** returns an integer equal to SQLITE_VERSION_NUMBER.
128040 */
128041 SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
128042 
128043 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
128044 ** zero if and only if SQLite was compiled with mutexing code omitted due to
128045 ** the SQLITE_THREADSAFE compile-time option being set to 0.
128046 */
128047 SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
128048 
128049 /*
128050 ** When compiling the test fixture or with debugging enabled (on Win32),
128051 ** this variable being set to non-zero will cause OSTRACE macros to emit
128052 ** extra diagnostic information.
128053 */
128054 #ifdef SQLITE_HAVE_OS_TRACE
128055 # ifndef SQLITE_DEBUG_OS_TRACE
128056 #   define SQLITE_DEBUG_OS_TRACE 0
128057 # endif
128058   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
128059 #endif
128060 
128061 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
128062 /*
128063 ** If the following function pointer is not NULL and if
128064 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
128065 ** I/O active are written using this function.  These messages
128066 ** are intended for debugging activity only.
128067 */
128068 SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
128069 #endif
128070 
128071 /*
128072 ** If the following global variable points to a string which is the
128073 ** name of a directory, then that directory will be used to store
128074 ** temporary files.
128075 **
128076 ** See also the "PRAGMA temp_store_directory" SQL command.
128077 */
128078 SQLITE_API char *sqlite3_temp_directory = 0;
128079 
128080 /*
128081 ** If the following global variable points to a string which is the
128082 ** name of a directory, then that directory will be used to store
128083 ** all database files specified with a relative pathname.
128084 **
128085 ** See also the "PRAGMA data_store_directory" SQL command.
128086 */
128087 SQLITE_API char *sqlite3_data_directory = 0;
128088 
128089 /*
128090 ** Initialize SQLite.
128091 **
128092 ** This routine must be called to initialize the memory allocation,
128093 ** VFS, and mutex subsystems prior to doing any serious work with
128094 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
128095 ** this routine will be called automatically by key routines such as
128096 ** sqlite3_open().
128097 **
128098 ** This routine is a no-op except on its very first call for the process,
128099 ** or for the first call after a call to sqlite3_shutdown.
128100 **
128101 ** The first thread to call this routine runs the initialization to
128102 ** completion.  If subsequent threads call this routine before the first
128103 ** thread has finished the initialization process, then the subsequent
128104 ** threads must block until the first thread finishes with the initialization.
128105 **
128106 ** The first thread might call this routine recursively.  Recursive
128107 ** calls to this routine should not block, of course.  Otherwise the
128108 ** initialization process would never complete.
128109 **
128110 ** Let X be the first thread to enter this routine.  Let Y be some other
128111 ** thread.  Then while the initial invocation of this routine by X is
128112 ** incomplete, it is required that:
128113 **
128114 **    *  Calls to this routine from Y must block until the outer-most
128115 **       call by X completes.
128116 **
128117 **    *  Recursive calls to this routine from thread X return immediately
128118 **       without blocking.
128119 */
128120 SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void){
128121   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
128122   int rc;                                      /* Result code */
128123 #ifdef SQLITE_EXTRA_INIT
128124   int bRunExtraInit = 0;                       /* Extra initialization needed */
128125 #endif
128126 
128127 #ifdef SQLITE_OMIT_WSD
128128   rc = sqlite3_wsd_init(4096, 24);
128129   if( rc!=SQLITE_OK ){
128130     return rc;
128131   }
128132 #endif
128133 
128134   /* If the following assert() fails on some obscure processor/compiler
128135   ** combination, the work-around is to set the correct pointer
128136   ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
128137   assert( SQLITE_PTRSIZE==sizeof(char*) );
128138 
128139   /* If SQLite is already completely initialized, then this call
128140   ** to sqlite3_initialize() should be a no-op.  But the initialization
128141   ** must be complete.  So isInit must not be set until the very end
128142   ** of this routine.
128143   */
128144   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
128145 
128146   /* Make sure the mutex subsystem is initialized.  If unable to
128147   ** initialize the mutex subsystem, return early with the error.
128148   ** If the system is so sick that we are unable to allocate a mutex,
128149   ** there is not much SQLite is going to be able to do.
128150   **
128151   ** The mutex subsystem must take care of serializing its own
128152   ** initialization.
128153   */
128154   rc = sqlite3MutexInit();
128155   if( rc ) return rc;
128156 
128157   /* Initialize the malloc() system and the recursive pInitMutex mutex.
128158   ** This operation is protected by the STATIC_MASTER mutex.  Note that
128159   ** MutexAlloc() is called for a static mutex prior to initializing the
128160   ** malloc subsystem - this implies that the allocation of a static
128161   ** mutex must not require support from the malloc subsystem.
128162   */
128163   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
128164   sqlite3_mutex_enter(pMaster);
128165   sqlite3GlobalConfig.isMutexInit = 1;
128166   if( !sqlite3GlobalConfig.isMallocInit ){
128167     rc = sqlite3MallocInit();
128168   }
128169   if( rc==SQLITE_OK ){
128170     sqlite3GlobalConfig.isMallocInit = 1;
128171     if( !sqlite3GlobalConfig.pInitMutex ){
128172       sqlite3GlobalConfig.pInitMutex =
128173            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
128174       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
128175         rc = SQLITE_NOMEM;
128176       }
128177     }
128178   }
128179   if( rc==SQLITE_OK ){
128180     sqlite3GlobalConfig.nRefInitMutex++;
128181   }
128182   sqlite3_mutex_leave(pMaster);
128183 
128184   /* If rc is not SQLITE_OK at this point, then either the malloc
128185   ** subsystem could not be initialized or the system failed to allocate
128186   ** the pInitMutex mutex. Return an error in either case.  */
128187   if( rc!=SQLITE_OK ){
128188     return rc;
128189   }
128190 
128191   /* Do the rest of the initialization under the recursive mutex so
128192   ** that we will be able to handle recursive calls into
128193   ** sqlite3_initialize().  The recursive calls normally come through
128194   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
128195   ** recursive calls might also be possible.
128196   **
128197   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
128198   ** to the xInit method, so the xInit method need not be threadsafe.
128199   **
128200   ** The following mutex is what serializes access to the appdef pcache xInit
128201   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
128202   ** call to sqlite3PcacheInitialize().
128203   */
128204   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
128205   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
128206     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
128207     sqlite3GlobalConfig.inProgress = 1;
128208     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
128209     sqlite3RegisterGlobalFunctions();
128210     if( sqlite3GlobalConfig.isPCacheInit==0 ){
128211       rc = sqlite3PcacheInitialize();
128212     }
128213     if( rc==SQLITE_OK ){
128214       sqlite3GlobalConfig.isPCacheInit = 1;
128215       rc = sqlite3OsInit();
128216     }
128217     if( rc==SQLITE_OK ){
128218       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
128219           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
128220       sqlite3GlobalConfig.isInit = 1;
128221 #ifdef SQLITE_EXTRA_INIT
128222       bRunExtraInit = 1;
128223 #endif
128224     }
128225     sqlite3GlobalConfig.inProgress = 0;
128226   }
128227   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
128228 
128229   /* Go back under the static mutex and clean up the recursive
128230   ** mutex to prevent a resource leak.
128231   */
128232   sqlite3_mutex_enter(pMaster);
128233   sqlite3GlobalConfig.nRefInitMutex--;
128234   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
128235     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
128236     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
128237     sqlite3GlobalConfig.pInitMutex = 0;
128238   }
128239   sqlite3_mutex_leave(pMaster);
128240 
128241   /* The following is just a sanity check to make sure SQLite has
128242   ** been compiled correctly.  It is important to run this code, but
128243   ** we don't want to run it too often and soak up CPU cycles for no
128244   ** reason.  So we run it once during initialization.
128245   */
128246 #ifndef NDEBUG
128247 #ifndef SQLITE_OMIT_FLOATING_POINT
128248   /* This section of code's only "output" is via assert() statements. */
128249   if ( rc==SQLITE_OK ){
128250     u64 x = (((u64)1)<<63)-1;
128251     double y;
128252     assert(sizeof(x)==8);
128253     assert(sizeof(x)==sizeof(y));
128254     memcpy(&y, &x, 8);
128255     assert( sqlite3IsNaN(y) );
128256   }
128257 #endif
128258 #endif
128259 
128260   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
128261   ** compile-time option.
128262   */
128263 #ifdef SQLITE_EXTRA_INIT
128264   if( bRunExtraInit ){
128265     int SQLITE_EXTRA_INIT(const char*);
128266     rc = SQLITE_EXTRA_INIT(0);
128267   }
128268 #endif
128269 
128270   return rc;
128271 }
128272 
128273 /*
128274 ** Undo the effects of sqlite3_initialize().  Must not be called while
128275 ** there are outstanding database connections or memory allocations or
128276 ** while any part of SQLite is otherwise in use in any thread.  This
128277 ** routine is not threadsafe.  But it is safe to invoke this routine
128278 ** on when SQLite is already shut down.  If SQLite is already shut down
128279 ** when this routine is invoked, then this routine is a harmless no-op.
128280 */
128281 SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void){
128282 #ifdef SQLITE_OMIT_WSD
128283   int rc = sqlite3_wsd_init(4096, 24);
128284   if( rc!=SQLITE_OK ){
128285     return rc;
128286   }
128287 #endif
128288 
128289   if( sqlite3GlobalConfig.isInit ){
128290 #ifdef SQLITE_EXTRA_SHUTDOWN
128291     void SQLITE_EXTRA_SHUTDOWN(void);
128292     SQLITE_EXTRA_SHUTDOWN();
128293 #endif
128294     sqlite3_os_end();
128295     sqlite3_reset_auto_extension();
128296     sqlite3GlobalConfig.isInit = 0;
128297   }
128298   if( sqlite3GlobalConfig.isPCacheInit ){
128299     sqlite3PcacheShutdown();
128300     sqlite3GlobalConfig.isPCacheInit = 0;
128301   }
128302   if( sqlite3GlobalConfig.isMallocInit ){
128303     sqlite3MallocEnd();
128304     sqlite3GlobalConfig.isMallocInit = 0;
128305 
128306 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
128307     /* The heap subsystem has now been shutdown and these values are supposed
128308     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
128309     ** which would rely on that heap subsystem; therefore, make sure these
128310     ** values cannot refer to heap memory that was just invalidated when the
128311     ** heap subsystem was shutdown.  This is only done if the current call to
128312     ** this function resulted in the heap subsystem actually being shutdown.
128313     */
128314     sqlite3_data_directory = 0;
128315     sqlite3_temp_directory = 0;
128316 #endif
128317   }
128318   if( sqlite3GlobalConfig.isMutexInit ){
128319     sqlite3MutexEnd();
128320     sqlite3GlobalConfig.isMutexInit = 0;
128321   }
128322 
128323   return SQLITE_OK;
128324 }
128325 
128326 /*
128327 ** This API allows applications to modify the global configuration of
128328 ** the SQLite library at run-time.
128329 **
128330 ** This routine should only be called when there are no outstanding
128331 ** database connections or memory allocations.  This routine is not
128332 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
128333 ** behavior.
128334 */
128335 SQLITE_API int SQLITE_CDECL sqlite3_config(int op, ...){
128336   va_list ap;
128337   int rc = SQLITE_OK;
128338 
128339   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
128340   ** the SQLite library is in use. */
128341   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
128342 
128343   va_start(ap, op);
128344   switch( op ){
128345 
128346     /* Mutex configuration options are only available in a threadsafe
128347     ** compile.
128348     */
128349 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
128350     case SQLITE_CONFIG_SINGLETHREAD: {
128351       /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
128352       ** Single-thread. */
128353       sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
128354       sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
128355       break;
128356     }
128357 #endif
128358 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
128359     case SQLITE_CONFIG_MULTITHREAD: {
128360       /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
128361       ** Multi-thread. */
128362       sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
128363       sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
128364       break;
128365     }
128366 #endif
128367 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
128368     case SQLITE_CONFIG_SERIALIZED: {
128369       /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
128370       ** Serialized. */
128371       sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
128372       sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
128373       break;
128374     }
128375 #endif
128376 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
128377     case SQLITE_CONFIG_MUTEX: {
128378       /* Specify an alternative mutex implementation */
128379       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
128380       break;
128381     }
128382 #endif
128383 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
128384     case SQLITE_CONFIG_GETMUTEX: {
128385       /* Retrieve the current mutex implementation */
128386       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
128387       break;
128388     }
128389 #endif
128390 
128391     case SQLITE_CONFIG_MALLOC: {
128392       /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
128393       ** single argument which is a pointer to an instance of the
128394       ** sqlite3_mem_methods structure. The argument specifies alternative
128395       ** low-level memory allocation routines to be used in place of the memory
128396       ** allocation routines built into SQLite. */
128397       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
128398       break;
128399     }
128400     case SQLITE_CONFIG_GETMALLOC: {
128401       /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
128402       ** single argument which is a pointer to an instance of the
128403       ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
128404       ** filled with the currently defined memory allocation routines. */
128405       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
128406       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
128407       break;
128408     }
128409     case SQLITE_CONFIG_MEMSTATUS: {
128410       /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
128411       ** single argument of type int, interpreted as a boolean, which enables
128412       ** or disables the collection of memory allocation statistics. */
128413       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
128414       break;
128415     }
128416     case SQLITE_CONFIG_SCRATCH: {
128417       /* EVIDENCE-OF: R-08404-60887 There are three arguments to
128418       ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
128419       ** which the scratch allocations will be drawn, the size of each scratch
128420       ** allocation (sz), and the maximum number of scratch allocations (N). */
128421       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
128422       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
128423       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
128424       break;
128425     }
128426     case SQLITE_CONFIG_PAGECACHE: {
128427       /* EVIDENCE-OF: R-31408-40510 There are three arguments to
128428       ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory, the size
128429       ** of each page buffer (sz), and the number of pages (N). */
128430       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
128431       sqlite3GlobalConfig.szPage = va_arg(ap, int);
128432       sqlite3GlobalConfig.nPage = va_arg(ap, int);
128433       break;
128434     }
128435     case SQLITE_CONFIG_PCACHE_HDRSZ: {
128436       /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
128437       ** a single parameter which is a pointer to an integer and writes into
128438       ** that integer the number of extra bytes per page required for each page
128439       ** in SQLITE_CONFIG_PAGECACHE. */
128440       *va_arg(ap, int*) =
128441           sqlite3HeaderSizeBtree() +
128442           sqlite3HeaderSizePcache() +
128443           sqlite3HeaderSizePcache1();
128444       break;
128445     }
128446 
128447     case SQLITE_CONFIG_PCACHE: {
128448       /* no-op */
128449       break;
128450     }
128451     case SQLITE_CONFIG_GETPCACHE: {
128452       /* now an error */
128453       rc = SQLITE_ERROR;
128454       break;
128455     }
128456 
128457     case SQLITE_CONFIG_PCACHE2: {
128458       /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
128459       ** single argument which is a pointer to an sqlite3_pcache_methods2
128460       ** object. This object specifies the interface to a custom page cache
128461       ** implementation. */
128462       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
128463       break;
128464     }
128465     case SQLITE_CONFIG_GETPCACHE2: {
128466       /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
128467       ** single argument which is a pointer to an sqlite3_pcache_methods2
128468       ** object. SQLite copies of the current page cache implementation into
128469       ** that object. */
128470       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
128471         sqlite3PCacheSetDefault();
128472       }
128473       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
128474       break;
128475     }
128476 
128477 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
128478 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
128479 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
128480 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
128481     case SQLITE_CONFIG_HEAP: {
128482       /* EVIDENCE-OF: R-19854-42126 There are three arguments to
128483       ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
128484       ** number of bytes in the memory buffer, and the minimum allocation size.
128485       */
128486       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
128487       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
128488       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
128489 
128490       if( sqlite3GlobalConfig.mnReq<1 ){
128491         sqlite3GlobalConfig.mnReq = 1;
128492       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
128493         /* cap min request size at 2^12 */
128494         sqlite3GlobalConfig.mnReq = (1<<12);
128495       }
128496 
128497       if( sqlite3GlobalConfig.pHeap==0 ){
128498         /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
128499         ** is NULL, then SQLite reverts to using its default memory allocator
128500         ** (the system malloc() implementation), undoing any prior invocation of
128501         ** SQLITE_CONFIG_MALLOC.
128502         **
128503         ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
128504         ** revert to its default implementation when sqlite3_initialize() is run
128505         */
128506         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
128507       }else{
128508         /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
128509         ** alternative memory allocator is engaged to handle all of SQLites
128510         ** memory allocation needs. */
128511 #ifdef SQLITE_ENABLE_MEMSYS3
128512         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
128513 #endif
128514 #ifdef SQLITE_ENABLE_MEMSYS5
128515         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
128516 #endif
128517       }
128518       break;
128519     }
128520 #endif
128521 
128522     case SQLITE_CONFIG_LOOKASIDE: {
128523       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
128524       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
128525       break;
128526     }
128527 
128528     /* Record a pointer to the logger function and its first argument.
128529     ** The default is NULL.  Logging is disabled if the function pointer is
128530     ** NULL.
128531     */
128532     case SQLITE_CONFIG_LOG: {
128533       /* MSVC is picky about pulling func ptrs from va lists.
128534       ** http://support.microsoft.com/kb/47961
128535       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
128536       */
128537       typedef void(*LOGFUNC_t)(void*,int,const char*);
128538       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
128539       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
128540       break;
128541     }
128542 
128543     /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
128544     ** can be changed at start-time using the
128545     ** sqlite3_config(SQLITE_CONFIG_URI,1) or
128546     ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
128547     */
128548     case SQLITE_CONFIG_URI: {
128549       /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
128550       ** argument of type int. If non-zero, then URI handling is globally
128551       ** enabled. If the parameter is zero, then URI handling is globally
128552       ** disabled. */
128553       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
128554       break;
128555     }
128556 
128557     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
128558       /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
128559       ** option takes a single integer argument which is interpreted as a
128560       ** boolean in order to enable or disable the use of covering indices for
128561       ** full table scans in the query optimizer. */
128562       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
128563       break;
128564     }
128565 
128566 #ifdef SQLITE_ENABLE_SQLLOG
128567     case SQLITE_CONFIG_SQLLOG: {
128568       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
128569       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
128570       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
128571       break;
128572     }
128573 #endif
128574 
128575     case SQLITE_CONFIG_MMAP_SIZE: {
128576       /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
128577       ** integer (sqlite3_int64) values that are the default mmap size limit
128578       ** (the default setting for PRAGMA mmap_size) and the maximum allowed
128579       ** mmap size limit. */
128580       sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
128581       sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
128582       /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
128583       ** negative, then that argument is changed to its compile-time default.
128584       **
128585       ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
128586       ** silently truncated if necessary so that it does not exceed the
128587       ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
128588       ** compile-time option.
128589       */
128590       if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
128591         mxMmap = SQLITE_MAX_MMAP_SIZE;
128592       }
128593       if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
128594       if( szMmap>mxMmap) szMmap = mxMmap;
128595       sqlite3GlobalConfig.mxMmap = mxMmap;
128596       sqlite3GlobalConfig.szMmap = szMmap;
128597       break;
128598     }
128599 
128600 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
128601     case SQLITE_CONFIG_WIN32_HEAPSIZE: {
128602       /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
128603       ** unsigned integer value that specifies the maximum size of the created
128604       ** heap. */
128605       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
128606       break;
128607     }
128608 #endif
128609 
128610     case SQLITE_CONFIG_PMASZ: {
128611       sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
128612       break;
128613     }
128614 
128615     default: {
128616       rc = SQLITE_ERROR;
128617       break;
128618     }
128619   }
128620   va_end(ap);
128621   return rc;
128622 }
128623 
128624 /*
128625 ** Set up the lookaside buffers for a database connection.
128626 ** Return SQLITE_OK on success.
128627 ** If lookaside is already active, return SQLITE_BUSY.
128628 **
128629 ** The sz parameter is the number of bytes in each lookaside slot.
128630 ** The cnt parameter is the number of slots.  If pStart is NULL the
128631 ** space for the lookaside memory is obtained from sqlite3_malloc().
128632 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
128633 ** the lookaside memory.
128634 */
128635 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
128636   void *pStart;
128637   if( db->lookaside.nOut ){
128638     return SQLITE_BUSY;
128639   }
128640   /* Free any existing lookaside buffer for this handle before
128641   ** allocating a new one so we don't have to have space for
128642   ** both at the same time.
128643   */
128644   if( db->lookaside.bMalloced ){
128645     sqlite3_free(db->lookaside.pStart);
128646   }
128647   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
128648   ** than a pointer to be useful.
128649   */
128650   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
128651   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
128652   if( cnt<0 ) cnt = 0;
128653   if( sz==0 || cnt==0 ){
128654     sz = 0;
128655     pStart = 0;
128656   }else if( pBuf==0 ){
128657     sqlite3BeginBenignMalloc();
128658     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
128659     sqlite3EndBenignMalloc();
128660     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
128661   }else{
128662     pStart = pBuf;
128663   }
128664   db->lookaside.pStart = pStart;
128665   db->lookaside.pFree = 0;
128666   db->lookaside.sz = (u16)sz;
128667   if( pStart ){
128668     int i;
128669     LookasideSlot *p;
128670     assert( sz > (int)sizeof(LookasideSlot*) );
128671     p = (LookasideSlot*)pStart;
128672     for(i=cnt-1; i>=0; i--){
128673       p->pNext = db->lookaside.pFree;
128674       db->lookaside.pFree = p;
128675       p = (LookasideSlot*)&((u8*)p)[sz];
128676     }
128677     db->lookaside.pEnd = p;
128678     db->lookaside.bEnabled = 1;
128679     db->lookaside.bMalloced = pBuf==0 ?1:0;
128680   }else{
128681     db->lookaside.pStart = db;
128682     db->lookaside.pEnd = db;
128683     db->lookaside.bEnabled = 0;
128684     db->lookaside.bMalloced = 0;
128685   }
128686   return SQLITE_OK;
128687 }
128688 
128689 /*
128690 ** Return the mutex associated with a database connection.
128691 */
128692 SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3 *db){
128693 #ifdef SQLITE_ENABLE_API_ARMOR
128694   if( !sqlite3SafetyCheckOk(db) ){
128695     (void)SQLITE_MISUSE_BKPT;
128696     return 0;
128697   }
128698 #endif
128699   return db->mutex;
128700 }
128701 
128702 /*
128703 ** Free up as much memory as we can from the given database
128704 ** connection.
128705 */
128706 SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3 *db){
128707   int i;
128708 
128709 #ifdef SQLITE_ENABLE_API_ARMOR
128710   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
128711 #endif
128712   sqlite3_mutex_enter(db->mutex);
128713   sqlite3BtreeEnterAll(db);
128714   for(i=0; i<db->nDb; i++){
128715     Btree *pBt = db->aDb[i].pBt;
128716     if( pBt ){
128717       Pager *pPager = sqlite3BtreePager(pBt);
128718       sqlite3PagerShrink(pPager);
128719     }
128720   }
128721   sqlite3BtreeLeaveAll(db);
128722   sqlite3_mutex_leave(db->mutex);
128723   return SQLITE_OK;
128724 }
128725 
128726 /*
128727 ** Configuration settings for an individual database connection
128728 */
128729 SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3 *db, int op, ...){
128730   va_list ap;
128731   int rc;
128732   va_start(ap, op);
128733   switch( op ){
128734     case SQLITE_DBCONFIG_LOOKASIDE: {
128735       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
128736       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
128737       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
128738       rc = setupLookaside(db, pBuf, sz, cnt);
128739       break;
128740     }
128741     default: {
128742       static const struct {
128743         int op;      /* The opcode */
128744         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
128745       } aFlagOp[] = {
128746         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
128747         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
128748       };
128749       unsigned int i;
128750       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
128751       for(i=0; i<ArraySize(aFlagOp); i++){
128752         if( aFlagOp[i].op==op ){
128753           int onoff = va_arg(ap, int);
128754           int *pRes = va_arg(ap, int*);
128755           int oldFlags = db->flags;
128756           if( onoff>0 ){
128757             db->flags |= aFlagOp[i].mask;
128758           }else if( onoff==0 ){
128759             db->flags &= ~aFlagOp[i].mask;
128760           }
128761           if( oldFlags!=db->flags ){
128762             sqlite3ExpirePreparedStatements(db);
128763           }
128764           if( pRes ){
128765             *pRes = (db->flags & aFlagOp[i].mask)!=0;
128766           }
128767           rc = SQLITE_OK;
128768           break;
128769         }
128770       }
128771       break;
128772     }
128773   }
128774   va_end(ap);
128775   return rc;
128776 }
128777 
128778 
128779 /*
128780 ** Return true if the buffer z[0..n-1] contains all spaces.
128781 */
128782 static int allSpaces(const char *z, int n){
128783   while( n>0 && z[n-1]==' ' ){ n--; }
128784   return n==0;
128785 }
128786 
128787 /*
128788 ** This is the default collating function named "BINARY" which is always
128789 ** available.
128790 **
128791 ** If the padFlag argument is not NULL then space padding at the end
128792 ** of strings is ignored.  This implements the RTRIM collation.
128793 */
128794 static int binCollFunc(
128795   void *padFlag,
128796   int nKey1, const void *pKey1,
128797   int nKey2, const void *pKey2
128798 ){
128799   int rc, n;
128800   n = nKey1<nKey2 ? nKey1 : nKey2;
128801   /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
128802   ** strings byte by byte using the memcmp() function from the standard C
128803   ** library. */
128804   rc = memcmp(pKey1, pKey2, n);
128805   if( rc==0 ){
128806     if( padFlag
128807      && allSpaces(((char*)pKey1)+n, nKey1-n)
128808      && allSpaces(((char*)pKey2)+n, nKey2-n)
128809     ){
128810       /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
128811       ** spaces at the end of either string do not change the result. In other
128812       ** words, strings will compare equal to one another as long as they
128813       ** differ only in the number of spaces at the end.
128814       */
128815     }else{
128816       rc = nKey1 - nKey2;
128817     }
128818   }
128819   return rc;
128820 }
128821 
128822 /*
128823 ** Another built-in collating sequence: NOCASE.
128824 **
128825 ** This collating sequence is intended to be used for "case independent
128826 ** comparison". SQLite's knowledge of upper and lower case equivalents
128827 ** extends only to the 26 characters used in the English language.
128828 **
128829 ** At the moment there is only a UTF-8 implementation.
128830 */
128831 static int nocaseCollatingFunc(
128832   void *NotUsed,
128833   int nKey1, const void *pKey1,
128834   int nKey2, const void *pKey2
128835 ){
128836   int r = sqlite3StrNICmp(
128837       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
128838   UNUSED_PARAMETER(NotUsed);
128839   if( 0==r ){
128840     r = nKey1-nKey2;
128841   }
128842   return r;
128843 }
128844 
128845 /*
128846 ** Return the ROWID of the most recent insert
128847 */
128848 SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3 *db){
128849 #ifdef SQLITE_ENABLE_API_ARMOR
128850   if( !sqlite3SafetyCheckOk(db) ){
128851     (void)SQLITE_MISUSE_BKPT;
128852     return 0;
128853   }
128854 #endif
128855   return db->lastRowid;
128856 }
128857 
128858 /*
128859 ** Return the number of changes in the most recent call to sqlite3_exec().
128860 */
128861 SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3 *db){
128862 #ifdef SQLITE_ENABLE_API_ARMOR
128863   if( !sqlite3SafetyCheckOk(db) ){
128864     (void)SQLITE_MISUSE_BKPT;
128865     return 0;
128866   }
128867 #endif
128868   return db->nChange;
128869 }
128870 
128871 /*
128872 ** Return the number of changes since the database handle was opened.
128873 */
128874 SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3 *db){
128875 #ifdef SQLITE_ENABLE_API_ARMOR
128876   if( !sqlite3SafetyCheckOk(db) ){
128877     (void)SQLITE_MISUSE_BKPT;
128878     return 0;
128879   }
128880 #endif
128881   return db->nTotalChange;
128882 }
128883 
128884 /*
128885 ** Close all open savepoints. This function only manipulates fields of the
128886 ** database handle object, it does not close any savepoints that may be open
128887 ** at the b-tree/pager level.
128888 */
128889 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
128890   while( db->pSavepoint ){
128891     Savepoint *pTmp = db->pSavepoint;
128892     db->pSavepoint = pTmp->pNext;
128893     sqlite3DbFree(db, pTmp);
128894   }
128895   db->nSavepoint = 0;
128896   db->nStatement = 0;
128897   db->isTransactionSavepoint = 0;
128898 }
128899 
128900 /*
128901 ** Invoke the destructor function associated with FuncDef p, if any. Except,
128902 ** if this is not the last copy of the function, do not invoke it. Multiple
128903 ** copies of a single function are created when create_function() is called
128904 ** with SQLITE_ANY as the encoding.
128905 */
128906 static void functionDestroy(sqlite3 *db, FuncDef *p){
128907   FuncDestructor *pDestructor = p->pDestructor;
128908   if( pDestructor ){
128909     pDestructor->nRef--;
128910     if( pDestructor->nRef==0 ){
128911       pDestructor->xDestroy(pDestructor->pUserData);
128912       sqlite3DbFree(db, pDestructor);
128913     }
128914   }
128915 }
128916 
128917 /*
128918 ** Disconnect all sqlite3_vtab objects that belong to database connection
128919 ** db. This is called when db is being closed.
128920 */
128921 static void disconnectAllVtab(sqlite3 *db){
128922 #ifndef SQLITE_OMIT_VIRTUALTABLE
128923   int i;
128924   sqlite3BtreeEnterAll(db);
128925   for(i=0; i<db->nDb; i++){
128926     Schema *pSchema = db->aDb[i].pSchema;
128927     if( db->aDb[i].pSchema ){
128928       HashElem *p;
128929       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
128930         Table *pTab = (Table *)sqliteHashData(p);
128931         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
128932       }
128933     }
128934   }
128935   sqlite3VtabUnlockList(db);
128936   sqlite3BtreeLeaveAll(db);
128937 #else
128938   UNUSED_PARAMETER(db);
128939 #endif
128940 }
128941 
128942 /*
128943 ** Return TRUE if database connection db has unfinalized prepared
128944 ** statements or unfinished sqlite3_backup objects.
128945 */
128946 static int connectionIsBusy(sqlite3 *db){
128947   int j;
128948   assert( sqlite3_mutex_held(db->mutex) );
128949   if( db->pVdbe ) return 1;
128950   for(j=0; j<db->nDb; j++){
128951     Btree *pBt = db->aDb[j].pBt;
128952     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
128953   }
128954   return 0;
128955 }
128956 
128957 /*
128958 ** Close an existing SQLite database
128959 */
128960 static int sqlite3Close(sqlite3 *db, int forceZombie){
128961   if( !db ){
128962     /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
128963     ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
128964     return SQLITE_OK;
128965   }
128966   if( !sqlite3SafetyCheckSickOrOk(db) ){
128967     return SQLITE_MISUSE_BKPT;
128968   }
128969   sqlite3_mutex_enter(db->mutex);
128970 
128971   /* Force xDisconnect calls on all virtual tables */
128972   disconnectAllVtab(db);
128973 
128974   /* If a transaction is open, the disconnectAllVtab() call above
128975   ** will not have called the xDisconnect() method on any virtual
128976   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
128977   ** call will do so. We need to do this before the check for active
128978   ** SQL statements below, as the v-table implementation may be storing
128979   ** some prepared statements internally.
128980   */
128981   sqlite3VtabRollback(db);
128982 
128983   /* Legacy behavior (sqlite3_close() behavior) is to return
128984   ** SQLITE_BUSY if the connection can not be closed immediately.
128985   */
128986   if( !forceZombie && connectionIsBusy(db) ){
128987     sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
128988        "statements or unfinished backups");
128989     sqlite3_mutex_leave(db->mutex);
128990     return SQLITE_BUSY;
128991   }
128992 
128993 #ifdef SQLITE_ENABLE_SQLLOG
128994   if( sqlite3GlobalConfig.xSqllog ){
128995     /* Closing the handle. Fourth parameter is passed the value 2. */
128996     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
128997   }
128998 #endif
128999 
129000   /* Convert the connection into a zombie and then close it.
129001   */
129002   db->magic = SQLITE_MAGIC_ZOMBIE;
129003   sqlite3LeaveMutexAndCloseZombie(db);
129004   return SQLITE_OK;
129005 }
129006 
129007 /*
129008 ** Two variations on the public interface for closing a database
129009 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
129010 ** leaves the connection option if there are unfinalized prepared
129011 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
129012 ** version forces the connection to become a zombie if there are
129013 ** unclosed resources, and arranges for deallocation when the last
129014 ** prepare statement or sqlite3_backup closes.
129015 */
129016 SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
129017 SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
129018 
129019 
129020 /*
129021 ** Close the mutex on database connection db.
129022 **
129023 ** Furthermore, if database connection db is a zombie (meaning that there
129024 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
129025 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
129026 ** finished, then free all resources.
129027 */
129028 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
129029   HashElem *i;                    /* Hash table iterator */
129030   int j;
129031 
129032   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
129033   ** or if the connection has not yet been closed by sqlite3_close_v2(),
129034   ** then just leave the mutex and return.
129035   */
129036   if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
129037     sqlite3_mutex_leave(db->mutex);
129038     return;
129039   }
129040 
129041   /* If we reach this point, it means that the database connection has
129042   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
129043   ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
129044   ** go ahead and free all resources.
129045   */
129046 
129047   /* If a transaction is open, roll it back. This also ensures that if
129048   ** any database schemas have been modified by an uncommitted transaction
129049   ** they are reset. And that the required b-tree mutex is held to make
129050   ** the pager rollback and schema reset an atomic operation. */
129051   sqlite3RollbackAll(db, SQLITE_OK);
129052 
129053   /* Free any outstanding Savepoint structures. */
129054   sqlite3CloseSavepoints(db);
129055 
129056   /* Close all database connections */
129057   for(j=0; j<db->nDb; j++){
129058     struct Db *pDb = &db->aDb[j];
129059     if( pDb->pBt ){
129060       sqlite3BtreeClose(pDb->pBt);
129061       pDb->pBt = 0;
129062       if( j!=1 ){
129063         pDb->pSchema = 0;
129064       }
129065     }
129066   }
129067   /* Clear the TEMP schema separately and last */
129068   if( db->aDb[1].pSchema ){
129069     sqlite3SchemaClear(db->aDb[1].pSchema);
129070   }
129071   sqlite3VtabUnlockList(db);
129072 
129073   /* Free up the array of auxiliary databases */
129074   sqlite3CollapseDatabaseArray(db);
129075   assert( db->nDb<=2 );
129076   assert( db->aDb==db->aDbStatic );
129077 
129078   /* Tell the code in notify.c that the connection no longer holds any
129079   ** locks and does not require any further unlock-notify callbacks.
129080   */
129081   sqlite3ConnectionClosed(db);
129082 
129083   for(j=0; j<ArraySize(db->aFunc.a); j++){
129084     FuncDef *pNext, *pHash, *p;
129085     for(p=db->aFunc.a[j]; p; p=pHash){
129086       pHash = p->pHash;
129087       while( p ){
129088         functionDestroy(db, p);
129089         pNext = p->pNext;
129090         sqlite3DbFree(db, p);
129091         p = pNext;
129092       }
129093     }
129094   }
129095   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
129096     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
129097     /* Invoke any destructors registered for collation sequence user data. */
129098     for(j=0; j<3; j++){
129099       if( pColl[j].xDel ){
129100         pColl[j].xDel(pColl[j].pUser);
129101       }
129102     }
129103     sqlite3DbFree(db, pColl);
129104   }
129105   sqlite3HashClear(&db->aCollSeq);
129106 #ifndef SQLITE_OMIT_VIRTUALTABLE
129107   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
129108     Module *pMod = (Module *)sqliteHashData(i);
129109     if( pMod->xDestroy ){
129110       pMod->xDestroy(pMod->pAux);
129111     }
129112     sqlite3DbFree(db, pMod);
129113   }
129114   sqlite3HashClear(&db->aModule);
129115 #endif
129116 
129117   sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
129118   sqlite3ValueFree(db->pErr);
129119   sqlite3CloseExtensions(db);
129120 #if SQLITE_USER_AUTHENTICATION
129121   sqlite3_free(db->auth.zAuthUser);
129122   sqlite3_free(db->auth.zAuthPW);
129123 #endif
129124 
129125   db->magic = SQLITE_MAGIC_ERROR;
129126 
129127   /* The temp-database schema is allocated differently from the other schema
129128   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
129129   ** So it needs to be freed here. Todo: Why not roll the temp schema into
129130   ** the same sqliteMalloc() as the one that allocates the database
129131   ** structure?
129132   */
129133   sqlite3DbFree(db, db->aDb[1].pSchema);
129134   sqlite3_mutex_leave(db->mutex);
129135   db->magic = SQLITE_MAGIC_CLOSED;
129136   sqlite3_mutex_free(db->mutex);
129137   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
129138   if( db->lookaside.bMalloced ){
129139     sqlite3_free(db->lookaside.pStart);
129140   }
129141   sqlite3_free(db);
129142 }
129143 
129144 /*
129145 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
129146 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
129147 ** breaker") and made to return tripCode if there are any further
129148 ** attempts to use that cursor.  Read cursors remain open and valid
129149 ** but are "saved" in case the table pages are moved around.
129150 */
129151 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
129152   int i;
129153   int inTrans = 0;
129154   int schemaChange;
129155   assert( sqlite3_mutex_held(db->mutex) );
129156   sqlite3BeginBenignMalloc();
129157 
129158   /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
129159   ** This is important in case the transaction being rolled back has
129160   ** modified the database schema. If the b-tree mutexes are not taken
129161   ** here, then another shared-cache connection might sneak in between
129162   ** the database rollback and schema reset, which can cause false
129163   ** corruption reports in some cases.  */
129164   sqlite3BtreeEnterAll(db);
129165   schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
129166 
129167   for(i=0; i<db->nDb; i++){
129168     Btree *p = db->aDb[i].pBt;
129169     if( p ){
129170       if( sqlite3BtreeIsInTrans(p) ){
129171         inTrans = 1;
129172       }
129173       sqlite3BtreeRollback(p, tripCode, !schemaChange);
129174     }
129175   }
129176   sqlite3VtabRollback(db);
129177   sqlite3EndBenignMalloc();
129178 
129179   if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
129180     sqlite3ExpirePreparedStatements(db);
129181     sqlite3ResetAllSchemasOfConnection(db);
129182   }
129183   sqlite3BtreeLeaveAll(db);
129184 
129185   /* Any deferred constraint violations have now been resolved. */
129186   db->nDeferredCons = 0;
129187   db->nDeferredImmCons = 0;
129188   db->flags &= ~SQLITE_DeferFKs;
129189 
129190   /* If one has been configured, invoke the rollback-hook callback */
129191   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
129192     db->xRollbackCallback(db->pRollbackArg);
129193   }
129194 }
129195 
129196 /*
129197 ** Return a static string containing the name corresponding to the error code
129198 ** specified in the argument.
129199 */
129200 #if defined(SQLITE_NEED_ERR_NAME)
129201 SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
129202   const char *zName = 0;
129203   int i, origRc = rc;
129204   for(i=0; i<2 && zName==0; i++, rc &= 0xff){
129205     switch( rc ){
129206       case SQLITE_OK:                 zName = "SQLITE_OK";                break;
129207       case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
129208       case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
129209       case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
129210       case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
129211       case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
129212       case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
129213       case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
129214       case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
129215       case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
129216       case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
129217       case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
129218       case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
129219       case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
129220       case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
129221       case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
129222       case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
129223       case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
129224       case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
129225       case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
129226       case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
129227       case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
129228       case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
129229       case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
129230       case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
129231       case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
129232       case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
129233       case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
129234       case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
129235       case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
129236       case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
129237       case SQLITE_IOERR_CHECKRESERVEDLOCK:
129238                                 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
129239       case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
129240       case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
129241       case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
129242       case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
129243       case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
129244       case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
129245       case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
129246       case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
129247       case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
129248       case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
129249       case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
129250       case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
129251       case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
129252       case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
129253       case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
129254       case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
129255       case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
129256       case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
129257       case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
129258       case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
129259       case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
129260       case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
129261       case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
129262       case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
129263       case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
129264       case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
129265       case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
129266       case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
129267       case SQLITE_CONSTRAINT_FOREIGNKEY:
129268                                 zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
129269       case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
129270       case SQLITE_CONSTRAINT_PRIMARYKEY:
129271                                 zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
129272       case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
129273       case SQLITE_CONSTRAINT_COMMITHOOK:
129274                                 zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
129275       case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
129276       case SQLITE_CONSTRAINT_FUNCTION:
129277                                 zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
129278       case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
129279       case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
129280       case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
129281       case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
129282       case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
129283       case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
129284       case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
129285       case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
129286       case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
129287       case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
129288       case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
129289       case SQLITE_NOTICE_RECOVER_ROLLBACK:
129290                                 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
129291       case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
129292       case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
129293       case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
129294     }
129295   }
129296   if( zName==0 ){
129297     static char zBuf[50];
129298     sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
129299     zName = zBuf;
129300   }
129301   return zName;
129302 }
129303 #endif
129304 
129305 /*
129306 ** Return a static string that describes the kind of error specified in the
129307 ** argument.
129308 */
129309 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
129310   static const char* const aMsg[] = {
129311     /* SQLITE_OK          */ "not an error",
129312     /* SQLITE_ERROR       */ "SQL logic error or missing database",
129313     /* SQLITE_INTERNAL    */ 0,
129314     /* SQLITE_PERM        */ "access permission denied",
129315     /* SQLITE_ABORT       */ "callback requested query abort",
129316     /* SQLITE_BUSY        */ "database is locked",
129317     /* SQLITE_LOCKED      */ "database table is locked",
129318     /* SQLITE_NOMEM       */ "out of memory",
129319     /* SQLITE_READONLY    */ "attempt to write a readonly database",
129320     /* SQLITE_INTERRUPT   */ "interrupted",
129321     /* SQLITE_IOERR       */ "disk I/O error",
129322     /* SQLITE_CORRUPT     */ "database disk image is malformed",
129323     /* SQLITE_NOTFOUND    */ "unknown operation",
129324     /* SQLITE_FULL        */ "database or disk is full",
129325     /* SQLITE_CANTOPEN    */ "unable to open database file",
129326     /* SQLITE_PROTOCOL    */ "locking protocol",
129327     /* SQLITE_EMPTY       */ "table contains no data",
129328     /* SQLITE_SCHEMA      */ "database schema has changed",
129329     /* SQLITE_TOOBIG      */ "string or blob too big",
129330     /* SQLITE_CONSTRAINT  */ "constraint failed",
129331     /* SQLITE_MISMATCH    */ "datatype mismatch",
129332     /* SQLITE_MISUSE      */ "library routine called out of sequence",
129333     /* SQLITE_NOLFS       */ "large file support is disabled",
129334     /* SQLITE_AUTH        */ "authorization denied",
129335     /* SQLITE_FORMAT      */ "auxiliary database format error",
129336     /* SQLITE_RANGE       */ "bind or column index out of range",
129337     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
129338   };
129339   const char *zErr = "unknown error";
129340   switch( rc ){
129341     case SQLITE_ABORT_ROLLBACK: {
129342       zErr = "abort due to ROLLBACK";
129343       break;
129344     }
129345     default: {
129346       rc &= 0xff;
129347       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
129348         zErr = aMsg[rc];
129349       }
129350       break;
129351     }
129352   }
129353   return zErr;
129354 }
129355 
129356 /*
129357 ** This routine implements a busy callback that sleeps and tries
129358 ** again until a timeout value is reached.  The timeout value is
129359 ** an integer number of milliseconds passed in as the first
129360 ** argument.
129361 */
129362 static int sqliteDefaultBusyCallback(
129363  void *ptr,               /* Database connection */
129364  int count                /* Number of times table has been busy */
129365 ){
129366 #if SQLITE_OS_WIN || HAVE_USLEEP
129367   static const u8 delays[] =
129368      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
129369   static const u8 totals[] =
129370      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
129371 # define NDELAY ArraySize(delays)
129372   sqlite3 *db = (sqlite3 *)ptr;
129373   int timeout = db->busyTimeout;
129374   int delay, prior;
129375 
129376   assert( count>=0 );
129377   if( count < NDELAY ){
129378     delay = delays[count];
129379     prior = totals[count];
129380   }else{
129381     delay = delays[NDELAY-1];
129382     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
129383   }
129384   if( prior + delay > timeout ){
129385     delay = timeout - prior;
129386     if( delay<=0 ) return 0;
129387   }
129388   sqlite3OsSleep(db->pVfs, delay*1000);
129389   return 1;
129390 #else
129391   sqlite3 *db = (sqlite3 *)ptr;
129392   int timeout = ((sqlite3 *)ptr)->busyTimeout;
129393   if( (count+1)*1000 > timeout ){
129394     return 0;
129395   }
129396   sqlite3OsSleep(db->pVfs, 1000000);
129397   return 1;
129398 #endif
129399 }
129400 
129401 /*
129402 ** Invoke the given busy handler.
129403 **
129404 ** This routine is called when an operation failed with a lock.
129405 ** If this routine returns non-zero, the lock is retried.  If it
129406 ** returns 0, the operation aborts with an SQLITE_BUSY error.
129407 */
129408 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
129409   int rc;
129410   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
129411   rc = p->xFunc(p->pArg, p->nBusy);
129412   if( rc==0 ){
129413     p->nBusy = -1;
129414   }else{
129415     p->nBusy++;
129416   }
129417   return rc;
129418 }
129419 
129420 /*
129421 ** This routine sets the busy callback for an Sqlite database to the
129422 ** given callback function with the given argument.
129423 */
129424 SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(
129425   sqlite3 *db,
129426   int (*xBusy)(void*,int),
129427   void *pArg
129428 ){
129429 #ifdef SQLITE_ENABLE_API_ARMOR
129430   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
129431 #endif
129432   sqlite3_mutex_enter(db->mutex);
129433   db->busyHandler.xFunc = xBusy;
129434   db->busyHandler.pArg = pArg;
129435   db->busyHandler.nBusy = 0;
129436   db->busyTimeout = 0;
129437   sqlite3_mutex_leave(db->mutex);
129438   return SQLITE_OK;
129439 }
129440 
129441 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
129442 /*
129443 ** This routine sets the progress callback for an Sqlite database to the
129444 ** given callback function with the given argument. The progress callback will
129445 ** be invoked every nOps opcodes.
129446 */
129447 SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(
129448   sqlite3 *db,
129449   int nOps,
129450   int (*xProgress)(void*),
129451   void *pArg
129452 ){
129453 #ifdef SQLITE_ENABLE_API_ARMOR
129454   if( !sqlite3SafetyCheckOk(db) ){
129455     (void)SQLITE_MISUSE_BKPT;
129456     return;
129457   }
129458 #endif
129459   sqlite3_mutex_enter(db->mutex);
129460   if( nOps>0 ){
129461     db->xProgress = xProgress;
129462     db->nProgressOps = (unsigned)nOps;
129463     db->pProgressArg = pArg;
129464   }else{
129465     db->xProgress = 0;
129466     db->nProgressOps = 0;
129467     db->pProgressArg = 0;
129468   }
129469   sqlite3_mutex_leave(db->mutex);
129470 }
129471 #endif
129472 
129473 
129474 /*
129475 ** This routine installs a default busy handler that waits for the
129476 ** specified number of milliseconds before returning 0.
129477 */
129478 SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3 *db, int ms){
129479 #ifdef SQLITE_ENABLE_API_ARMOR
129480   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
129481 #endif
129482   if( ms>0 ){
129483     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
129484     db->busyTimeout = ms;
129485   }else{
129486     sqlite3_busy_handler(db, 0, 0);
129487   }
129488   return SQLITE_OK;
129489 }
129490 
129491 /*
129492 ** Cause any pending operation to stop at its earliest opportunity.
129493 */
129494 SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3 *db){
129495 #ifdef SQLITE_ENABLE_API_ARMOR
129496   if( !sqlite3SafetyCheckOk(db) ){
129497     (void)SQLITE_MISUSE_BKPT;
129498     return;
129499   }
129500 #endif
129501   db->u1.isInterrupted = 1;
129502 }
129503 
129504 
129505 /*
129506 ** This function is exactly the same as sqlite3_create_function(), except
129507 ** that it is designed to be called by internal code. The difference is
129508 ** that if a malloc() fails in sqlite3_create_function(), an error code
129509 ** is returned and the mallocFailed flag cleared.
129510 */
129511 SQLITE_PRIVATE int sqlite3CreateFunc(
129512   sqlite3 *db,
129513   const char *zFunctionName,
129514   int nArg,
129515   int enc,
129516   void *pUserData,
129517   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
129518   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
129519   void (*xFinal)(sqlite3_context*),
129520   FuncDestructor *pDestructor
129521 ){
129522   FuncDef *p;
129523   int nName;
129524   int extraFlags;
129525 
129526   assert( sqlite3_mutex_held(db->mutex) );
129527   if( zFunctionName==0 ||
129528       (xFunc && (xFinal || xStep)) ||
129529       (!xFunc && (xFinal && !xStep)) ||
129530       (!xFunc && (!xFinal && xStep)) ||
129531       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
129532       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
129533     return SQLITE_MISUSE_BKPT;
129534   }
129535 
129536   assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
129537   extraFlags = enc &  SQLITE_DETERMINISTIC;
129538   enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
129539 
129540 #ifndef SQLITE_OMIT_UTF16
129541   /* If SQLITE_UTF16 is specified as the encoding type, transform this
129542   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
129543   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
129544   **
129545   ** If SQLITE_ANY is specified, add three versions of the function
129546   ** to the hash table.
129547   */
129548   if( enc==SQLITE_UTF16 ){
129549     enc = SQLITE_UTF16NATIVE;
129550   }else if( enc==SQLITE_ANY ){
129551     int rc;
129552     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
129553          pUserData, xFunc, xStep, xFinal, pDestructor);
129554     if( rc==SQLITE_OK ){
129555       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
129556           pUserData, xFunc, xStep, xFinal, pDestructor);
129557     }
129558     if( rc!=SQLITE_OK ){
129559       return rc;
129560     }
129561     enc = SQLITE_UTF16BE;
129562   }
129563 #else
129564   enc = SQLITE_UTF8;
129565 #endif
129566 
129567   /* Check if an existing function is being overridden or deleted. If so,
129568   ** and there are active VMs, then return SQLITE_BUSY. If a function
129569   ** is being overridden/deleted but there are no active VMs, allow the
129570   ** operation to continue but invalidate all precompiled statements.
129571   */
129572   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
129573   if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
129574     if( db->nVdbeActive ){
129575       sqlite3ErrorWithMsg(db, SQLITE_BUSY,
129576         "unable to delete/modify user-function due to active statements");
129577       assert( !db->mallocFailed );
129578       return SQLITE_BUSY;
129579     }else{
129580       sqlite3ExpirePreparedStatements(db);
129581     }
129582   }
129583 
129584   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
129585   assert(p || db->mallocFailed);
129586   if( !p ){
129587     return SQLITE_NOMEM;
129588   }
129589 
129590   /* If an older version of the function with a configured destructor is
129591   ** being replaced invoke the destructor function here. */
129592   functionDestroy(db, p);
129593 
129594   if( pDestructor ){
129595     pDestructor->nRef++;
129596   }
129597   p->pDestructor = pDestructor;
129598   p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
129599   testcase( p->funcFlags & SQLITE_DETERMINISTIC );
129600   p->xFunc = xFunc;
129601   p->xStep = xStep;
129602   p->xFinalize = xFinal;
129603   p->pUserData = pUserData;
129604   p->nArg = (u16)nArg;
129605   return SQLITE_OK;
129606 }
129607 
129608 /*
129609 ** Create new user functions.
129610 */
129611 SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
129612   sqlite3 *db,
129613   const char *zFunc,
129614   int nArg,
129615   int enc,
129616   void *p,
129617   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
129618   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
129619   void (*xFinal)(sqlite3_context*)
129620 ){
129621   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
129622                                     xFinal, 0);
129623 }
129624 
129625 SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
129626   sqlite3 *db,
129627   const char *zFunc,
129628   int nArg,
129629   int enc,
129630   void *p,
129631   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
129632   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
129633   void (*xFinal)(sqlite3_context*),
129634   void (*xDestroy)(void *)
129635 ){
129636   int rc = SQLITE_ERROR;
129637   FuncDestructor *pArg = 0;
129638 
129639 #ifdef SQLITE_ENABLE_API_ARMOR
129640   if( !sqlite3SafetyCheckOk(db) ){
129641     return SQLITE_MISUSE_BKPT;
129642   }
129643 #endif
129644   sqlite3_mutex_enter(db->mutex);
129645   if( xDestroy ){
129646     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
129647     if( !pArg ){
129648       xDestroy(p);
129649       goto out;
129650     }
129651     pArg->xDestroy = xDestroy;
129652     pArg->pUserData = p;
129653   }
129654   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
129655   if( pArg && pArg->nRef==0 ){
129656     assert( rc!=SQLITE_OK );
129657     xDestroy(p);
129658     sqlite3DbFree(db, pArg);
129659   }
129660 
129661  out:
129662   rc = sqlite3ApiExit(db, rc);
129663   sqlite3_mutex_leave(db->mutex);
129664   return rc;
129665 }
129666 
129667 #ifndef SQLITE_OMIT_UTF16
129668 SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
129669   sqlite3 *db,
129670   const void *zFunctionName,
129671   int nArg,
129672   int eTextRep,
129673   void *p,
129674   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
129675   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
129676   void (*xFinal)(sqlite3_context*)
129677 ){
129678   int rc;
129679   char *zFunc8;
129680 
129681 #ifdef SQLITE_ENABLE_API_ARMOR
129682   if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
129683 #endif
129684   sqlite3_mutex_enter(db->mutex);
129685   assert( !db->mallocFailed );
129686   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
129687   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
129688   sqlite3DbFree(db, zFunc8);
129689   rc = sqlite3ApiExit(db, rc);
129690   sqlite3_mutex_leave(db->mutex);
129691   return rc;
129692 }
129693 #endif
129694 
129695 
129696 /*
129697 ** Declare that a function has been overloaded by a virtual table.
129698 **
129699 ** If the function already exists as a regular global function, then
129700 ** this routine is a no-op.  If the function does not exist, then create
129701 ** a new one that always throws a run-time error.
129702 **
129703 ** When virtual tables intend to provide an overloaded function, they
129704 ** should call this routine to make sure the global function exists.
129705 ** A global function must exist in order for name resolution to work
129706 ** properly.
129707 */
129708 SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(
129709   sqlite3 *db,
129710   const char *zName,
129711   int nArg
129712 ){
129713   int nName = sqlite3Strlen30(zName);
129714   int rc = SQLITE_OK;
129715 
129716 #ifdef SQLITE_ENABLE_API_ARMOR
129717   if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
129718     return SQLITE_MISUSE_BKPT;
129719   }
129720 #endif
129721   sqlite3_mutex_enter(db->mutex);
129722   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
129723     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
129724                            0, sqlite3InvalidFunction, 0, 0, 0);
129725   }
129726   rc = sqlite3ApiExit(db, rc);
129727   sqlite3_mutex_leave(db->mutex);
129728   return rc;
129729 }
129730 
129731 #ifndef SQLITE_OMIT_TRACE
129732 /*
129733 ** Register a trace function.  The pArg from the previously registered trace
129734 ** is returned.
129735 **
129736 ** A NULL trace function means that no tracing is executes.  A non-NULL
129737 ** trace is a pointer to a function that is invoked at the start of each
129738 ** SQL statement.
129739 */
129740 SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
129741   void *pOld;
129742 
129743 #ifdef SQLITE_ENABLE_API_ARMOR
129744   if( !sqlite3SafetyCheckOk(db) ){
129745     (void)SQLITE_MISUSE_BKPT;
129746     return 0;
129747   }
129748 #endif
129749   sqlite3_mutex_enter(db->mutex);
129750   pOld = db->pTraceArg;
129751   db->xTrace = xTrace;
129752   db->pTraceArg = pArg;
129753   sqlite3_mutex_leave(db->mutex);
129754   return pOld;
129755 }
129756 /*
129757 ** Register a profile function.  The pArg from the previously registered
129758 ** profile function is returned.
129759 **
129760 ** A NULL profile function means that no profiling is executes.  A non-NULL
129761 ** profile is a pointer to a function that is invoked at the conclusion of
129762 ** each SQL statement that is run.
129763 */
129764 SQLITE_API void *SQLITE_STDCALL sqlite3_profile(
129765   sqlite3 *db,
129766   void (*xProfile)(void*,const char*,sqlite_uint64),
129767   void *pArg
129768 ){
129769   void *pOld;
129770 
129771 #ifdef SQLITE_ENABLE_API_ARMOR
129772   if( !sqlite3SafetyCheckOk(db) ){
129773     (void)SQLITE_MISUSE_BKPT;
129774     return 0;
129775   }
129776 #endif
129777   sqlite3_mutex_enter(db->mutex);
129778   pOld = db->pProfileArg;
129779   db->xProfile = xProfile;
129780   db->pProfileArg = pArg;
129781   sqlite3_mutex_leave(db->mutex);
129782   return pOld;
129783 }
129784 #endif /* SQLITE_OMIT_TRACE */
129785 
129786 /*
129787 ** Register a function to be invoked when a transaction commits.
129788 ** If the invoked function returns non-zero, then the commit becomes a
129789 ** rollback.
129790 */
129791 SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(
129792   sqlite3 *db,              /* Attach the hook to this database */
129793   int (*xCallback)(void*),  /* Function to invoke on each commit */
129794   void *pArg                /* Argument to the function */
129795 ){
129796   void *pOld;
129797 
129798 #ifdef SQLITE_ENABLE_API_ARMOR
129799   if( !sqlite3SafetyCheckOk(db) ){
129800     (void)SQLITE_MISUSE_BKPT;
129801     return 0;
129802   }
129803 #endif
129804   sqlite3_mutex_enter(db->mutex);
129805   pOld = db->pCommitArg;
129806   db->xCommitCallback = xCallback;
129807   db->pCommitArg = pArg;
129808   sqlite3_mutex_leave(db->mutex);
129809   return pOld;
129810 }
129811 
129812 /*
129813 ** Register a callback to be invoked each time a row is updated,
129814 ** inserted or deleted using this database connection.
129815 */
129816 SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
129817   sqlite3 *db,              /* Attach the hook to this database */
129818   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
129819   void *pArg                /* Argument to the function */
129820 ){
129821   void *pRet;
129822 
129823 #ifdef SQLITE_ENABLE_API_ARMOR
129824   if( !sqlite3SafetyCheckOk(db) ){
129825     (void)SQLITE_MISUSE_BKPT;
129826     return 0;
129827   }
129828 #endif
129829   sqlite3_mutex_enter(db->mutex);
129830   pRet = db->pUpdateArg;
129831   db->xUpdateCallback = xCallback;
129832   db->pUpdateArg = pArg;
129833   sqlite3_mutex_leave(db->mutex);
129834   return pRet;
129835 }
129836 
129837 /*
129838 ** Register a callback to be invoked each time a transaction is rolled
129839 ** back by this database connection.
129840 */
129841 SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(
129842   sqlite3 *db,              /* Attach the hook to this database */
129843   void (*xCallback)(void*), /* Callback function */
129844   void *pArg                /* Argument to the function */
129845 ){
129846   void *pRet;
129847 
129848 #ifdef SQLITE_ENABLE_API_ARMOR
129849   if( !sqlite3SafetyCheckOk(db) ){
129850     (void)SQLITE_MISUSE_BKPT;
129851     return 0;
129852   }
129853 #endif
129854   sqlite3_mutex_enter(db->mutex);
129855   pRet = db->pRollbackArg;
129856   db->xRollbackCallback = xCallback;
129857   db->pRollbackArg = pArg;
129858   sqlite3_mutex_leave(db->mutex);
129859   return pRet;
129860 }
129861 
129862 #ifndef SQLITE_OMIT_WAL
129863 /*
129864 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
129865 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
129866 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
129867 ** wal_autocheckpoint()).
129868 */
129869 SQLITE_PRIVATE int sqlite3WalDefaultHook(
129870   void *pClientData,     /* Argument */
129871   sqlite3 *db,           /* Connection */
129872   const char *zDb,       /* Database */
129873   int nFrame             /* Size of WAL */
129874 ){
129875   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
129876     sqlite3BeginBenignMalloc();
129877     sqlite3_wal_checkpoint(db, zDb);
129878     sqlite3EndBenignMalloc();
129879   }
129880   return SQLITE_OK;
129881 }
129882 #endif /* SQLITE_OMIT_WAL */
129883 
129884 /*
129885 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
129886 ** a database after committing a transaction if there are nFrame or
129887 ** more frames in the log file. Passing zero or a negative value as the
129888 ** nFrame parameter disables automatic checkpoints entirely.
129889 **
129890 ** The callback registered by this function replaces any existing callback
129891 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
129892 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
129893 ** configured by this function.
129894 */
129895 SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
129896 #ifdef SQLITE_OMIT_WAL
129897   UNUSED_PARAMETER(db);
129898   UNUSED_PARAMETER(nFrame);
129899 #else
129900 #ifdef SQLITE_ENABLE_API_ARMOR
129901   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
129902 #endif
129903   if( nFrame>0 ){
129904     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
129905   }else{
129906     sqlite3_wal_hook(db, 0, 0);
129907   }
129908 #endif
129909   return SQLITE_OK;
129910 }
129911 
129912 /*
129913 ** Register a callback to be invoked each time a transaction is written
129914 ** into the write-ahead-log by this database connection.
129915 */
129916 SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
129917   sqlite3 *db,                    /* Attach the hook to this db handle */
129918   int(*xCallback)(void *, sqlite3*, const char*, int),
129919   void *pArg                      /* First argument passed to xCallback() */
129920 ){
129921 #ifndef SQLITE_OMIT_WAL
129922   void *pRet;
129923 #ifdef SQLITE_ENABLE_API_ARMOR
129924   if( !sqlite3SafetyCheckOk(db) ){
129925     (void)SQLITE_MISUSE_BKPT;
129926     return 0;
129927   }
129928 #endif
129929   sqlite3_mutex_enter(db->mutex);
129930   pRet = db->pWalArg;
129931   db->xWalCallback = xCallback;
129932   db->pWalArg = pArg;
129933   sqlite3_mutex_leave(db->mutex);
129934   return pRet;
129935 #else
129936   return 0;
129937 #endif
129938 }
129939 
129940 /*
129941 ** Checkpoint database zDb.
129942 */
129943 SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
129944   sqlite3 *db,                    /* Database handle */
129945   const char *zDb,                /* Name of attached database (or NULL) */
129946   int eMode,                      /* SQLITE_CHECKPOINT_* value */
129947   int *pnLog,                     /* OUT: Size of WAL log in frames */
129948   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
129949 ){
129950 #ifdef SQLITE_OMIT_WAL
129951   return SQLITE_OK;
129952 #else
129953   int rc;                         /* Return code */
129954   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
129955 
129956 #ifdef SQLITE_ENABLE_API_ARMOR
129957   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
129958 #endif
129959 
129960   /* Initialize the output variables to -1 in case an error occurs. */
129961   if( pnLog ) *pnLog = -1;
129962   if( pnCkpt ) *pnCkpt = -1;
129963 
129964   assert( SQLITE_CHECKPOINT_PASSIVE==0 );
129965   assert( SQLITE_CHECKPOINT_FULL==1 );
129966   assert( SQLITE_CHECKPOINT_RESTART==2 );
129967   assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
129968   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
129969     /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
129970     ** mode: */
129971     return SQLITE_MISUSE;
129972   }
129973 
129974   sqlite3_mutex_enter(db->mutex);
129975   if( zDb && zDb[0] ){
129976     iDb = sqlite3FindDbName(db, zDb);
129977   }
129978   if( iDb<0 ){
129979     rc = SQLITE_ERROR;
129980     sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
129981   }else{
129982     db->busyHandler.nBusy = 0;
129983     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
129984     sqlite3Error(db, rc);
129985   }
129986   rc = sqlite3ApiExit(db, rc);
129987   sqlite3_mutex_leave(db->mutex);
129988   return rc;
129989 #endif
129990 }
129991 
129992 
129993 /*
129994 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
129995 ** to contains a zero-length string, all attached databases are
129996 ** checkpointed.
129997 */
129998 SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
129999   /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
130000   ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
130001   return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
130002 }
130003 
130004 #ifndef SQLITE_OMIT_WAL
130005 /*
130006 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
130007 ** not currently open in WAL mode.
130008 **
130009 ** If a transaction is open on the database being checkpointed, this
130010 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
130011 ** an error occurs while running the checkpoint, an SQLite error code is
130012 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
130013 **
130014 ** The mutex on database handle db should be held by the caller. The mutex
130015 ** associated with the specific b-tree being checkpointed is taken by
130016 ** this function while the checkpoint is running.
130017 **
130018 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
130019 ** checkpointed. If an error is encountered it is returned immediately -
130020 ** no attempt is made to checkpoint any remaining databases.
130021 **
130022 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
130023 */
130024 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
130025   int rc = SQLITE_OK;             /* Return code */
130026   int i;                          /* Used to iterate through attached dbs */
130027   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
130028 
130029   assert( sqlite3_mutex_held(db->mutex) );
130030   assert( !pnLog || *pnLog==-1 );
130031   assert( !pnCkpt || *pnCkpt==-1 );
130032 
130033   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
130034     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
130035       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
130036       pnLog = 0;
130037       pnCkpt = 0;
130038       if( rc==SQLITE_BUSY ){
130039         bBusy = 1;
130040         rc = SQLITE_OK;
130041       }
130042     }
130043   }
130044 
130045   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
130046 }
130047 #endif /* SQLITE_OMIT_WAL */
130048 
130049 /*
130050 ** This function returns true if main-memory should be used instead of
130051 ** a temporary file for transient pager files and statement journals.
130052 ** The value returned depends on the value of db->temp_store (runtime
130053 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
130054 ** following table describes the relationship between these two values
130055 ** and this functions return value.
130056 **
130057 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
130058 **   -----------------     --------------     ------------------------------
130059 **   0                     any                file      (return 0)
130060 **   1                     1                  file      (return 0)
130061 **   1                     2                  memory    (return 1)
130062 **   1                     0                  file      (return 0)
130063 **   2                     1                  file      (return 0)
130064 **   2                     2                  memory    (return 1)
130065 **   2                     0                  memory    (return 1)
130066 **   3                     any                memory    (return 1)
130067 */
130068 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
130069 #if SQLITE_TEMP_STORE==1
130070   return ( db->temp_store==2 );
130071 #endif
130072 #if SQLITE_TEMP_STORE==2
130073   return ( db->temp_store!=1 );
130074 #endif
130075 #if SQLITE_TEMP_STORE==3
130076   return 1;
130077 #endif
130078 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
130079   return 0;
130080 #endif
130081 }
130082 
130083 /*
130084 ** Return UTF-8 encoded English language explanation of the most recent
130085 ** error.
130086 */
130087 SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3 *db){
130088   const char *z;
130089   if( !db ){
130090     return sqlite3ErrStr(SQLITE_NOMEM);
130091   }
130092   if( !sqlite3SafetyCheckSickOrOk(db) ){
130093     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
130094   }
130095   sqlite3_mutex_enter(db->mutex);
130096   if( db->mallocFailed ){
130097     z = sqlite3ErrStr(SQLITE_NOMEM);
130098   }else{
130099     testcase( db->pErr==0 );
130100     z = (char*)sqlite3_value_text(db->pErr);
130101     assert( !db->mallocFailed );
130102     if( z==0 ){
130103       z = sqlite3ErrStr(db->errCode);
130104     }
130105   }
130106   sqlite3_mutex_leave(db->mutex);
130107   return z;
130108 }
130109 
130110 #ifndef SQLITE_OMIT_UTF16
130111 /*
130112 ** Return UTF-16 encoded English language explanation of the most recent
130113 ** error.
130114 */
130115 SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3 *db){
130116   static const u16 outOfMem[] = {
130117     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
130118   };
130119   static const u16 misuse[] = {
130120     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
130121     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
130122     'c', 'a', 'l', 'l', 'e', 'd', ' ',
130123     'o', 'u', 't', ' ',
130124     'o', 'f', ' ',
130125     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
130126   };
130127 
130128   const void *z;
130129   if( !db ){
130130     return (void *)outOfMem;
130131   }
130132   if( !sqlite3SafetyCheckSickOrOk(db) ){
130133     return (void *)misuse;
130134   }
130135   sqlite3_mutex_enter(db->mutex);
130136   if( db->mallocFailed ){
130137     z = (void *)outOfMem;
130138   }else{
130139     z = sqlite3_value_text16(db->pErr);
130140     if( z==0 ){
130141       sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
130142       z = sqlite3_value_text16(db->pErr);
130143     }
130144     /* A malloc() may have failed within the call to sqlite3_value_text16()
130145     ** above. If this is the case, then the db->mallocFailed flag needs to
130146     ** be cleared before returning. Do this directly, instead of via
130147     ** sqlite3ApiExit(), to avoid setting the database handle error message.
130148     */
130149     db->mallocFailed = 0;
130150   }
130151   sqlite3_mutex_leave(db->mutex);
130152   return z;
130153 }
130154 #endif /* SQLITE_OMIT_UTF16 */
130155 
130156 /*
130157 ** Return the most recent error code generated by an SQLite routine. If NULL is
130158 ** passed to this function, we assume a malloc() failed during sqlite3_open().
130159 */
130160 SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db){
130161   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
130162     return SQLITE_MISUSE_BKPT;
130163   }
130164   if( !db || db->mallocFailed ){
130165     return SQLITE_NOMEM;
130166   }
130167   return db->errCode & db->errMask;
130168 }
130169 SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db){
130170   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
130171     return SQLITE_MISUSE_BKPT;
130172   }
130173   if( !db || db->mallocFailed ){
130174     return SQLITE_NOMEM;
130175   }
130176   return db->errCode;
130177 }
130178 
130179 /*
130180 ** Return a string that describes the kind of error specified in the
130181 ** argument.  For now, this simply calls the internal sqlite3ErrStr()
130182 ** function.
130183 */
130184 SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int rc){
130185   return sqlite3ErrStr(rc);
130186 }
130187 
130188 /*
130189 ** Create a new collating function for database "db".  The name is zName
130190 ** and the encoding is enc.
130191 */
130192 static int createCollation(
130193   sqlite3* db,
130194   const char *zName,
130195   u8 enc,
130196   void* pCtx,
130197   int(*xCompare)(void*,int,const void*,int,const void*),
130198   void(*xDel)(void*)
130199 ){
130200   CollSeq *pColl;
130201   int enc2;
130202 
130203   assert( sqlite3_mutex_held(db->mutex) );
130204 
130205   /* If SQLITE_UTF16 is specified as the encoding type, transform this
130206   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
130207   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
130208   */
130209   enc2 = enc;
130210   testcase( enc2==SQLITE_UTF16 );
130211   testcase( enc2==SQLITE_UTF16_ALIGNED );
130212   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
130213     enc2 = SQLITE_UTF16NATIVE;
130214   }
130215   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
130216     return SQLITE_MISUSE_BKPT;
130217   }
130218 
130219   /* Check if this call is removing or replacing an existing collation
130220   ** sequence. If so, and there are active VMs, return busy. If there
130221   ** are no active VMs, invalidate any pre-compiled statements.
130222   */
130223   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
130224   if( pColl && pColl->xCmp ){
130225     if( db->nVdbeActive ){
130226       sqlite3ErrorWithMsg(db, SQLITE_BUSY,
130227         "unable to delete/modify collation sequence due to active statements");
130228       return SQLITE_BUSY;
130229     }
130230     sqlite3ExpirePreparedStatements(db);
130231 
130232     /* If collation sequence pColl was created directly by a call to
130233     ** sqlite3_create_collation, and not generated by synthCollSeq(),
130234     ** then any copies made by synthCollSeq() need to be invalidated.
130235     ** Also, collation destructor - CollSeq.xDel() - function may need
130236     ** to be called.
130237     */
130238     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
130239       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
130240       int j;
130241       for(j=0; j<3; j++){
130242         CollSeq *p = &aColl[j];
130243         if( p->enc==pColl->enc ){
130244           if( p->xDel ){
130245             p->xDel(p->pUser);
130246           }
130247           p->xCmp = 0;
130248         }
130249       }
130250     }
130251   }
130252 
130253   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
130254   if( pColl==0 ) return SQLITE_NOMEM;
130255   pColl->xCmp = xCompare;
130256   pColl->pUser = pCtx;
130257   pColl->xDel = xDel;
130258   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
130259   sqlite3Error(db, SQLITE_OK);
130260   return SQLITE_OK;
130261 }
130262 
130263 
130264 /*
130265 ** This array defines hard upper bounds on limit values.  The
130266 ** initializer must be kept in sync with the SQLITE_LIMIT_*
130267 ** #defines in sqlite3.h.
130268 */
130269 static const int aHardLimit[] = {
130270   SQLITE_MAX_LENGTH,
130271   SQLITE_MAX_SQL_LENGTH,
130272   SQLITE_MAX_COLUMN,
130273   SQLITE_MAX_EXPR_DEPTH,
130274   SQLITE_MAX_COMPOUND_SELECT,
130275   SQLITE_MAX_VDBE_OP,
130276   SQLITE_MAX_FUNCTION_ARG,
130277   SQLITE_MAX_ATTACHED,
130278   SQLITE_MAX_LIKE_PATTERN_LENGTH,
130279   SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
130280   SQLITE_MAX_TRIGGER_DEPTH,
130281   SQLITE_MAX_WORKER_THREADS,
130282 };
130283 
130284 /*
130285 ** Make sure the hard limits are set to reasonable values
130286 */
130287 #if SQLITE_MAX_LENGTH<100
130288 # error SQLITE_MAX_LENGTH must be at least 100
130289 #endif
130290 #if SQLITE_MAX_SQL_LENGTH<100
130291 # error SQLITE_MAX_SQL_LENGTH must be at least 100
130292 #endif
130293 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
130294 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
130295 #endif
130296 #if SQLITE_MAX_COMPOUND_SELECT<2
130297 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
130298 #endif
130299 #if SQLITE_MAX_VDBE_OP<40
130300 # error SQLITE_MAX_VDBE_OP must be at least 40
130301 #endif
130302 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
130303 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
130304 #endif
130305 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
130306 # error SQLITE_MAX_ATTACHED must be between 0 and 125
130307 #endif
130308 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
130309 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
130310 #endif
130311 #if SQLITE_MAX_COLUMN>32767
130312 # error SQLITE_MAX_COLUMN must not exceed 32767
130313 #endif
130314 #if SQLITE_MAX_TRIGGER_DEPTH<1
130315 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
130316 #endif
130317 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
130318 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
130319 #endif
130320 
130321 
130322 /*
130323 ** Change the value of a limit.  Report the old value.
130324 ** If an invalid limit index is supplied, report -1.
130325 ** Make no changes but still report the old value if the
130326 ** new limit is negative.
130327 **
130328 ** A new lower limit does not shrink existing constructs.
130329 ** It merely prevents new constructs that exceed the limit
130330 ** from forming.
130331 */
130332 SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
130333   int oldLimit;
130334 
130335 #ifdef SQLITE_ENABLE_API_ARMOR
130336   if( !sqlite3SafetyCheckOk(db) ){
130337     (void)SQLITE_MISUSE_BKPT;
130338     return -1;
130339   }
130340 #endif
130341 
130342   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
130343   ** there is a hard upper bound set at compile-time by a C preprocessor
130344   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
130345   ** "_MAX_".)
130346   */
130347   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
130348   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
130349   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
130350   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
130351   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
130352   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
130353   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
130354   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
130355   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
130356                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
130357   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
130358   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
130359   assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
130360   assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
130361 
130362 
130363   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
130364     return -1;
130365   }
130366   oldLimit = db->aLimit[limitId];
130367   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
130368     if( newLimit>aHardLimit[limitId] ){
130369       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
130370     }
130371     db->aLimit[limitId] = newLimit;
130372   }
130373   return oldLimit;                     /* IMP: R-53341-35419 */
130374 }
130375 
130376 /*
130377 ** This function is used to parse both URIs and non-URI filenames passed by the
130378 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
130379 ** URIs specified as part of ATTACH statements.
130380 **
130381 ** The first argument to this function is the name of the VFS to use (or
130382 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
130383 ** query parameter. The second argument contains the URI (or non-URI filename)
130384 ** itself. When this function is called the *pFlags variable should contain
130385 ** the default flags to open the database handle with. The value stored in
130386 ** *pFlags may be updated before returning if the URI filename contains
130387 ** "cache=xxx" or "mode=xxx" query parameters.
130388 **
130389 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
130390 ** the VFS that should be used to open the database file. *pzFile is set to
130391 ** point to a buffer containing the name of the file to open. It is the
130392 ** responsibility of the caller to eventually call sqlite3_free() to release
130393 ** this buffer.
130394 **
130395 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
130396 ** may be set to point to a buffer containing an English language error
130397 ** message. It is the responsibility of the caller to eventually release
130398 ** this buffer by calling sqlite3_free().
130399 */
130400 SQLITE_PRIVATE int sqlite3ParseUri(
130401   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
130402   const char *zUri,               /* Nul-terminated URI to parse */
130403   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
130404   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
130405   char **pzFile,                  /* OUT: Filename component of URI */
130406   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
130407 ){
130408   int rc = SQLITE_OK;
130409   unsigned int flags = *pFlags;
130410   const char *zVfs = zDefaultVfs;
130411   char *zFile;
130412   char c;
130413   int nUri = sqlite3Strlen30(zUri);
130414 
130415   assert( *pzErrMsg==0 );
130416 
130417   if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
130418             || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
130419    && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
130420   ){
130421     char *zOpt;
130422     int eState;                   /* Parser state when parsing URI */
130423     int iIn;                      /* Input character index */
130424     int iOut = 0;                 /* Output character index */
130425     u64 nByte = nUri+2;           /* Bytes of space to allocate */
130426 
130427     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
130428     ** method that there may be extra parameters following the file-name.  */
130429     flags |= SQLITE_OPEN_URI;
130430 
130431     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
130432     zFile = sqlite3_malloc64(nByte);
130433     if( !zFile ) return SQLITE_NOMEM;
130434 
130435     iIn = 5;
130436 #ifdef SQLITE_ALLOW_URI_AUTHORITY
130437     if( strncmp(zUri+5, "///", 3)==0 ){
130438       iIn = 7;
130439       /* The following condition causes URIs with five leading / characters
130440       ** like file://///host/path to be converted into UNCs like //host/path.
130441       ** The correct URI for that UNC has only two or four leading / characters
130442       ** file://host/path or file:////host/path.  But 5 leading slashes is a
130443       ** common error, we are told, so we handle it as a special case. */
130444       if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
130445     }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
130446       iIn = 16;
130447     }
130448 #else
130449     /* Discard the scheme and authority segments of the URI. */
130450     if( zUri[5]=='/' && zUri[6]=='/' ){
130451       iIn = 7;
130452       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
130453       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
130454         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
130455             iIn-7, &zUri[7]);
130456         rc = SQLITE_ERROR;
130457         goto parse_uri_out;
130458       }
130459     }
130460 #endif
130461 
130462     /* Copy the filename and any query parameters into the zFile buffer.
130463     ** Decode %HH escape codes along the way.
130464     **
130465     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
130466     ** on the parsing context. As follows:
130467     **
130468     **   0: Parsing file-name.
130469     **   1: Parsing name section of a name=value query parameter.
130470     **   2: Parsing value section of a name=value query parameter.
130471     */
130472     eState = 0;
130473     while( (c = zUri[iIn])!=0 && c!='#' ){
130474       iIn++;
130475       if( c=='%'
130476        && sqlite3Isxdigit(zUri[iIn])
130477        && sqlite3Isxdigit(zUri[iIn+1])
130478       ){
130479         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
130480         octet += sqlite3HexToInt(zUri[iIn++]);
130481 
130482         assert( octet>=0 && octet<256 );
130483         if( octet==0 ){
130484           /* This branch is taken when "%00" appears within the URI. In this
130485           ** case we ignore all text in the remainder of the path, name or
130486           ** value currently being parsed. So ignore the current character
130487           ** and skip to the next "?", "=" or "&", as appropriate. */
130488           while( (c = zUri[iIn])!=0 && c!='#'
130489               && (eState!=0 || c!='?')
130490               && (eState!=1 || (c!='=' && c!='&'))
130491               && (eState!=2 || c!='&')
130492           ){
130493             iIn++;
130494           }
130495           continue;
130496         }
130497         c = octet;
130498       }else if( eState==1 && (c=='&' || c=='=') ){
130499         if( zFile[iOut-1]==0 ){
130500           /* An empty option name. Ignore this option altogether. */
130501           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
130502           continue;
130503         }
130504         if( c=='&' ){
130505           zFile[iOut++] = '\0';
130506         }else{
130507           eState = 2;
130508         }
130509         c = 0;
130510       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
130511         c = 0;
130512         eState = 1;
130513       }
130514       zFile[iOut++] = c;
130515     }
130516     if( eState==1 ) zFile[iOut++] = '\0';
130517     zFile[iOut++] = '\0';
130518     zFile[iOut++] = '\0';
130519 
130520     /* Check if there were any options specified that should be interpreted
130521     ** here. Options that are interpreted here include "vfs" and those that
130522     ** correspond to flags that may be passed to the sqlite3_open_v2()
130523     ** method. */
130524     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
130525     while( zOpt[0] ){
130526       int nOpt = sqlite3Strlen30(zOpt);
130527       char *zVal = &zOpt[nOpt+1];
130528       int nVal = sqlite3Strlen30(zVal);
130529 
130530       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
130531         zVfs = zVal;
130532       }else{
130533         struct OpenMode {
130534           const char *z;
130535           int mode;
130536         } *aMode = 0;
130537         char *zModeType = 0;
130538         int mask = 0;
130539         int limit = 0;
130540 
130541         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
130542           static struct OpenMode aCacheMode[] = {
130543             { "shared",  SQLITE_OPEN_SHAREDCACHE },
130544             { "private", SQLITE_OPEN_PRIVATECACHE },
130545             { 0, 0 }
130546           };
130547 
130548           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
130549           aMode = aCacheMode;
130550           limit = mask;
130551           zModeType = "cache";
130552         }
130553         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
130554           static struct OpenMode aOpenMode[] = {
130555             { "ro",  SQLITE_OPEN_READONLY },
130556             { "rw",  SQLITE_OPEN_READWRITE },
130557             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
130558             { "memory", SQLITE_OPEN_MEMORY },
130559             { 0, 0 }
130560           };
130561 
130562           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
130563                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
130564           aMode = aOpenMode;
130565           limit = mask & flags;
130566           zModeType = "access";
130567         }
130568 
130569         if( aMode ){
130570           int i;
130571           int mode = 0;
130572           for(i=0; aMode[i].z; i++){
130573             const char *z = aMode[i].z;
130574             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
130575               mode = aMode[i].mode;
130576               break;
130577             }
130578           }
130579           if( mode==0 ){
130580             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
130581             rc = SQLITE_ERROR;
130582             goto parse_uri_out;
130583           }
130584           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
130585             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
130586                                         zModeType, zVal);
130587             rc = SQLITE_PERM;
130588             goto parse_uri_out;
130589           }
130590           flags = (flags & ~mask) | mode;
130591         }
130592       }
130593 
130594       zOpt = &zVal[nVal+1];
130595     }
130596 
130597   }else{
130598     zFile = sqlite3_malloc64(nUri+2);
130599     if( !zFile ) return SQLITE_NOMEM;
130600     memcpy(zFile, zUri, nUri);
130601     zFile[nUri] = '\0';
130602     zFile[nUri+1] = '\0';
130603     flags &= ~SQLITE_OPEN_URI;
130604   }
130605 
130606   *ppVfs = sqlite3_vfs_find(zVfs);
130607   if( *ppVfs==0 ){
130608     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
130609     rc = SQLITE_ERROR;
130610   }
130611  parse_uri_out:
130612   if( rc!=SQLITE_OK ){
130613     sqlite3_free(zFile);
130614     zFile = 0;
130615   }
130616   *pFlags = flags;
130617   *pzFile = zFile;
130618   return rc;
130619 }
130620 
130621 
130622 /*
130623 ** This routine does the work of opening a database on behalf of
130624 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
130625 ** is UTF-8 encoded.
130626 */
130627 static int openDatabase(
130628   const char *zFilename, /* Database filename UTF-8 encoded */
130629   sqlite3 **ppDb,        /* OUT: Returned database handle */
130630   unsigned int flags,    /* Operational flags */
130631   const char *zVfs       /* Name of the VFS to use */
130632 ){
130633   sqlite3 *db;                    /* Store allocated handle here */
130634   int rc;                         /* Return code */
130635   int isThreadsafe;               /* True for threadsafe connections */
130636   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
130637   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
130638 
130639 #ifdef SQLITE_ENABLE_API_ARMOR
130640   if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
130641 #endif
130642   *ppDb = 0;
130643 #ifndef SQLITE_OMIT_AUTOINIT
130644   rc = sqlite3_initialize();
130645   if( rc ) return rc;
130646 #endif
130647 
130648   /* Only allow sensible combinations of bits in the flags argument.
130649   ** Throw an error if any non-sense combination is used.  If we
130650   ** do not block illegal combinations here, it could trigger
130651   ** assert() statements in deeper layers.  Sensible combinations
130652   ** are:
130653   **
130654   **  1:  SQLITE_OPEN_READONLY
130655   **  2:  SQLITE_OPEN_READWRITE
130656   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
130657   */
130658   assert( SQLITE_OPEN_READONLY  == 0x01 );
130659   assert( SQLITE_OPEN_READWRITE == 0x02 );
130660   assert( SQLITE_OPEN_CREATE    == 0x04 );
130661   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
130662   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
130663   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
130664   if( ((1<<(flags&7)) & 0x46)==0 ){
130665     return SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
130666   }
130667 
130668   if( sqlite3GlobalConfig.bCoreMutex==0 ){
130669     isThreadsafe = 0;
130670   }else if( flags & SQLITE_OPEN_NOMUTEX ){
130671     isThreadsafe = 0;
130672   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
130673     isThreadsafe = 1;
130674   }else{
130675     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
130676   }
130677   if( flags & SQLITE_OPEN_PRIVATECACHE ){
130678     flags &= ~SQLITE_OPEN_SHAREDCACHE;
130679   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
130680     flags |= SQLITE_OPEN_SHAREDCACHE;
130681   }
130682 
130683   /* Remove harmful bits from the flags parameter
130684   **
130685   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
130686   ** dealt with in the previous code block.  Besides these, the only
130687   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
130688   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
130689   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
130690   ** off all other flags.
130691   */
130692   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
130693                SQLITE_OPEN_EXCLUSIVE |
130694                SQLITE_OPEN_MAIN_DB |
130695                SQLITE_OPEN_TEMP_DB |
130696                SQLITE_OPEN_TRANSIENT_DB |
130697                SQLITE_OPEN_MAIN_JOURNAL |
130698                SQLITE_OPEN_TEMP_JOURNAL |
130699                SQLITE_OPEN_SUBJOURNAL |
130700                SQLITE_OPEN_MASTER_JOURNAL |
130701                SQLITE_OPEN_NOMUTEX |
130702                SQLITE_OPEN_FULLMUTEX |
130703                SQLITE_OPEN_WAL
130704              );
130705 
130706   /* Allocate the sqlite data structure */
130707   db = sqlite3MallocZero( sizeof(sqlite3) );
130708   if( db==0 ) goto opendb_out;
130709   if( isThreadsafe ){
130710     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
130711     if( db->mutex==0 ){
130712       sqlite3_free(db);
130713       db = 0;
130714       goto opendb_out;
130715     }
130716   }
130717   sqlite3_mutex_enter(db->mutex);
130718   db->errMask = 0xff;
130719   db->nDb = 2;
130720   db->magic = SQLITE_MAGIC_BUSY;
130721   db->aDb = db->aDbStatic;
130722 
130723   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
130724   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
130725   db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
130726   db->autoCommit = 1;
130727   db->nextAutovac = -1;
130728   db->szMmap = sqlite3GlobalConfig.szMmap;
130729   db->nextPagesize = 0;
130730   db->nMaxSorterMmap = 0x7FFFFFFF;
130731   db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
130732 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
130733                  | SQLITE_AutoIndex
130734 #endif
130735 #if SQLITE_DEFAULT_CKPTFULLFSYNC
130736                  | SQLITE_CkptFullFSync
130737 #endif
130738 #if SQLITE_DEFAULT_FILE_FORMAT<4
130739                  | SQLITE_LegacyFileFmt
130740 #endif
130741 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
130742                  | SQLITE_LoadExtension
130743 #endif
130744 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
130745                  | SQLITE_RecTriggers
130746 #endif
130747 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
130748                  | SQLITE_ForeignKeys
130749 #endif
130750 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
130751                  | SQLITE_ReverseOrder
130752 #endif
130753       ;
130754   sqlite3HashInit(&db->aCollSeq);
130755 #ifndef SQLITE_OMIT_VIRTUALTABLE
130756   sqlite3HashInit(&db->aModule);
130757 #endif
130758 
130759   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
130760   ** and UTF-16, so add a version for each to avoid any unnecessary
130761   ** conversions. The only error that can occur here is a malloc() failure.
130762   **
130763   ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
130764   ** functions:
130765   */
130766   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
130767   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
130768   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
130769   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
130770   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
130771   if( db->mallocFailed ){
130772     goto opendb_out;
130773   }
130774   /* EVIDENCE-OF: R-08308-17224 The default collating function for all
130775   ** strings is BINARY.
130776   */
130777   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
130778   assert( db->pDfltColl!=0 );
130779 
130780   /* Parse the filename/URI argument. */
130781   db->openFlags = flags;
130782   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
130783   if( rc!=SQLITE_OK ){
130784     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
130785     sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
130786     sqlite3_free(zErrMsg);
130787     goto opendb_out;
130788   }
130789 
130790   /* Open the backend database driver */
130791   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
130792                         flags | SQLITE_OPEN_MAIN_DB);
130793   if( rc!=SQLITE_OK ){
130794     if( rc==SQLITE_IOERR_NOMEM ){
130795       rc = SQLITE_NOMEM;
130796     }
130797     sqlite3Error(db, rc);
130798     goto opendb_out;
130799   }
130800   sqlite3BtreeEnter(db->aDb[0].pBt);
130801   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
130802   if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
130803   sqlite3BtreeLeave(db->aDb[0].pBt);
130804   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
130805 
130806   /* The default safety_level for the main database is 'full'; for the temp
130807   ** database it is 'NONE'. This matches the pager layer defaults.
130808   */
130809   db->aDb[0].zName = "main";
130810   db->aDb[0].safety_level = 3;
130811   db->aDb[1].zName = "temp";
130812   db->aDb[1].safety_level = 1;
130813 
130814   db->magic = SQLITE_MAGIC_OPEN;
130815   if( db->mallocFailed ){
130816     goto opendb_out;
130817   }
130818 
130819   /* Register all built-in functions, but do not attempt to read the
130820   ** database schema yet. This is delayed until the first time the database
130821   ** is accessed.
130822   */
130823   sqlite3Error(db, SQLITE_OK);
130824   sqlite3RegisterBuiltinFunctions(db);
130825 
130826   /* Load automatic extensions - extensions that have been registered
130827   ** using the sqlite3_automatic_extension() API.
130828   */
130829   rc = sqlite3_errcode(db);
130830   if( rc==SQLITE_OK ){
130831     sqlite3AutoLoadExtensions(db);
130832     rc = sqlite3_errcode(db);
130833     if( rc!=SQLITE_OK ){
130834       goto opendb_out;
130835     }
130836   }
130837 
130838 #ifdef SQLITE_ENABLE_FTS1
130839   if( !db->mallocFailed ){
130840     extern int sqlite3Fts1Init(sqlite3*);
130841     rc = sqlite3Fts1Init(db);
130842   }
130843 #endif
130844 
130845 #ifdef SQLITE_ENABLE_FTS2
130846   if( !db->mallocFailed && rc==SQLITE_OK ){
130847     extern int sqlite3Fts2Init(sqlite3*);
130848     rc = sqlite3Fts2Init(db);
130849   }
130850 #endif
130851 
130852 #ifdef SQLITE_ENABLE_FTS3
130853   if( !db->mallocFailed && rc==SQLITE_OK ){
130854     rc = sqlite3Fts3Init(db);
130855   }
130856 #endif
130857 
130858 #ifdef SQLITE_ENABLE_ICU
130859   if( !db->mallocFailed && rc==SQLITE_OK ){
130860     rc = sqlite3IcuInit(db);
130861   }
130862 #endif
130863 
130864 #ifdef SQLITE_ENABLE_RTREE
130865   if( !db->mallocFailed && rc==SQLITE_OK){
130866     rc = sqlite3RtreeInit(db);
130867   }
130868 #endif
130869 
130870 #ifdef SQLITE_ENABLE_DBSTAT_VTAB
130871   if( !db->mallocFailed && rc==SQLITE_OK){
130872     int sqlite3_dbstat_register(sqlite3*);
130873     rc = sqlite3_dbstat_register(db);
130874   }
130875 #endif
130876 
130877   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
130878   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
130879   ** mode.  Doing nothing at all also makes NORMAL the default.
130880   */
130881 #ifdef SQLITE_DEFAULT_LOCKING_MODE
130882   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
130883   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
130884                           SQLITE_DEFAULT_LOCKING_MODE);
130885 #endif
130886 
130887   if( rc ) sqlite3Error(db, rc);
130888 
130889   /* Enable the lookaside-malloc subsystem */
130890   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
130891                         sqlite3GlobalConfig.nLookaside);
130892 
130893   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
130894 
130895 opendb_out:
130896   sqlite3_free(zOpen);
130897   if( db ){
130898     assert( db->mutex!=0 || isThreadsafe==0
130899            || sqlite3GlobalConfig.bFullMutex==0 );
130900     sqlite3_mutex_leave(db->mutex);
130901   }
130902   rc = sqlite3_errcode(db);
130903   assert( db!=0 || rc==SQLITE_NOMEM );
130904   if( rc==SQLITE_NOMEM ){
130905     sqlite3_close(db);
130906     db = 0;
130907   }else if( rc!=SQLITE_OK ){
130908     db->magic = SQLITE_MAGIC_SICK;
130909   }
130910   *ppDb = db;
130911 #ifdef SQLITE_ENABLE_SQLLOG
130912   if( sqlite3GlobalConfig.xSqllog ){
130913     /* Opening a db handle. Fourth parameter is passed 0. */
130914     void *pArg = sqlite3GlobalConfig.pSqllogArg;
130915     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
130916   }
130917 #endif
130918   return sqlite3ApiExit(0, rc);
130919 }
130920 
130921 /*
130922 ** Open a new database handle.
130923 */
130924 SQLITE_API int SQLITE_STDCALL sqlite3_open(
130925   const char *zFilename,
130926   sqlite3 **ppDb
130927 ){
130928   return openDatabase(zFilename, ppDb,
130929                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
130930 }
130931 SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
130932   const char *filename,   /* Database filename (UTF-8) */
130933   sqlite3 **ppDb,         /* OUT: SQLite db handle */
130934   int flags,              /* Flags */
130935   const char *zVfs        /* Name of VFS module to use */
130936 ){
130937   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
130938 }
130939 
130940 #ifndef SQLITE_OMIT_UTF16
130941 /*
130942 ** Open a new database handle.
130943 */
130944 SQLITE_API int SQLITE_STDCALL sqlite3_open16(
130945   const void *zFilename,
130946   sqlite3 **ppDb
130947 ){
130948   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
130949   sqlite3_value *pVal;
130950   int rc;
130951 
130952 #ifdef SQLITE_ENABLE_API_ARMOR
130953   if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
130954 #endif
130955   *ppDb = 0;
130956 #ifndef SQLITE_OMIT_AUTOINIT
130957   rc = sqlite3_initialize();
130958   if( rc ) return rc;
130959 #endif
130960   if( zFilename==0 ) zFilename = "\000\000";
130961   pVal = sqlite3ValueNew(0);
130962   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
130963   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
130964   if( zFilename8 ){
130965     rc = openDatabase(zFilename8, ppDb,
130966                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
130967     assert( *ppDb || rc==SQLITE_NOMEM );
130968     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
130969       SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
130970     }
130971   }else{
130972     rc = SQLITE_NOMEM;
130973   }
130974   sqlite3ValueFree(pVal);
130975 
130976   return sqlite3ApiExit(0, rc);
130977 }
130978 #endif /* SQLITE_OMIT_UTF16 */
130979 
130980 /*
130981 ** Register a new collation sequence with the database handle db.
130982 */
130983 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
130984   sqlite3* db,
130985   const char *zName,
130986   int enc,
130987   void* pCtx,
130988   int(*xCompare)(void*,int,const void*,int,const void*)
130989 ){
130990   return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
130991 }
130992 
130993 /*
130994 ** Register a new collation sequence with the database handle db.
130995 */
130996 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
130997   sqlite3* db,
130998   const char *zName,
130999   int enc,
131000   void* pCtx,
131001   int(*xCompare)(void*,int,const void*,int,const void*),
131002   void(*xDel)(void*)
131003 ){
131004   int rc;
131005 
131006 #ifdef SQLITE_ENABLE_API_ARMOR
131007   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
131008 #endif
131009   sqlite3_mutex_enter(db->mutex);
131010   assert( !db->mallocFailed );
131011   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
131012   rc = sqlite3ApiExit(db, rc);
131013   sqlite3_mutex_leave(db->mutex);
131014   return rc;
131015 }
131016 
131017 #ifndef SQLITE_OMIT_UTF16
131018 /*
131019 ** Register a new collation sequence with the database handle db.
131020 */
131021 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
131022   sqlite3* db,
131023   const void *zName,
131024   int enc,
131025   void* pCtx,
131026   int(*xCompare)(void*,int,const void*,int,const void*)
131027 ){
131028   int rc = SQLITE_OK;
131029   char *zName8;
131030 
131031 #ifdef SQLITE_ENABLE_API_ARMOR
131032   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
131033 #endif
131034   sqlite3_mutex_enter(db->mutex);
131035   assert( !db->mallocFailed );
131036   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
131037   if( zName8 ){
131038     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
131039     sqlite3DbFree(db, zName8);
131040   }
131041   rc = sqlite3ApiExit(db, rc);
131042   sqlite3_mutex_leave(db->mutex);
131043   return rc;
131044 }
131045 #endif /* SQLITE_OMIT_UTF16 */
131046 
131047 /*
131048 ** Register a collation sequence factory callback with the database handle
131049 ** db. Replace any previously installed collation sequence factory.
131050 */
131051 SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
131052   sqlite3 *db,
131053   void *pCollNeededArg,
131054   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
131055 ){
131056 #ifdef SQLITE_ENABLE_API_ARMOR
131057   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
131058 #endif
131059   sqlite3_mutex_enter(db->mutex);
131060   db->xCollNeeded = xCollNeeded;
131061   db->xCollNeeded16 = 0;
131062   db->pCollNeededArg = pCollNeededArg;
131063   sqlite3_mutex_leave(db->mutex);
131064   return SQLITE_OK;
131065 }
131066 
131067 #ifndef SQLITE_OMIT_UTF16
131068 /*
131069 ** Register a collation sequence factory callback with the database handle
131070 ** db. Replace any previously installed collation sequence factory.
131071 */
131072 SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
131073   sqlite3 *db,
131074   void *pCollNeededArg,
131075   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
131076 ){
131077 #ifdef SQLITE_ENABLE_API_ARMOR
131078   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
131079 #endif
131080   sqlite3_mutex_enter(db->mutex);
131081   db->xCollNeeded = 0;
131082   db->xCollNeeded16 = xCollNeeded16;
131083   db->pCollNeededArg = pCollNeededArg;
131084   sqlite3_mutex_leave(db->mutex);
131085   return SQLITE_OK;
131086 }
131087 #endif /* SQLITE_OMIT_UTF16 */
131088 
131089 #ifndef SQLITE_OMIT_DEPRECATED
131090 /*
131091 ** This function is now an anachronism. It used to be used to recover from a
131092 ** malloc() failure, but SQLite now does this automatically.
131093 */
131094 SQLITE_API int SQLITE_STDCALL sqlite3_global_recover(void){
131095   return SQLITE_OK;
131096 }
131097 #endif
131098 
131099 /*
131100 ** Test to see whether or not the database connection is in autocommit
131101 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
131102 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
131103 ** by the next COMMIT or ROLLBACK.
131104 */
131105 SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3 *db){
131106 #ifdef SQLITE_ENABLE_API_ARMOR
131107   if( !sqlite3SafetyCheckOk(db) ){
131108     (void)SQLITE_MISUSE_BKPT;
131109     return 0;
131110   }
131111 #endif
131112   return db->autoCommit;
131113 }
131114 
131115 /*
131116 ** The following routines are substitutes for constants SQLITE_CORRUPT,
131117 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
131118 ** constants.  They serve two purposes:
131119 **
131120 **   1.  Serve as a convenient place to set a breakpoint in a debugger
131121 **       to detect when version error conditions occurs.
131122 **
131123 **   2.  Invoke sqlite3_log() to provide the source code location where
131124 **       a low-level error is first detected.
131125 */
131126 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
131127   testcase( sqlite3GlobalConfig.xLog!=0 );
131128   sqlite3_log(SQLITE_CORRUPT,
131129               "database corruption at line %d of [%.10s]",
131130               lineno, 20+sqlite3_sourceid());
131131   return SQLITE_CORRUPT;
131132 }
131133 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
131134   testcase( sqlite3GlobalConfig.xLog!=0 );
131135   sqlite3_log(SQLITE_MISUSE,
131136               "misuse at line %d of [%.10s]",
131137               lineno, 20+sqlite3_sourceid());
131138   return SQLITE_MISUSE;
131139 }
131140 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
131141   testcase( sqlite3GlobalConfig.xLog!=0 );
131142   sqlite3_log(SQLITE_CANTOPEN,
131143               "cannot open file at line %d of [%.10s]",
131144               lineno, 20+sqlite3_sourceid());
131145   return SQLITE_CANTOPEN;
131146 }
131147 
131148 
131149 #ifndef SQLITE_OMIT_DEPRECATED
131150 /*
131151 ** This is a convenience routine that makes sure that all thread-specific
131152 ** data for this thread has been deallocated.
131153 **
131154 ** SQLite no longer uses thread-specific data so this routine is now a
131155 ** no-op.  It is retained for historical compatibility.
131156 */
131157 SQLITE_API void SQLITE_STDCALL sqlite3_thread_cleanup(void){
131158 }
131159 #endif
131160 
131161 /*
131162 ** Return meta information about a specific column of a database table.
131163 ** See comment in sqlite3.h (sqlite.h.in) for details.
131164 */
131165 SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
131166   sqlite3 *db,                /* Connection handle */
131167   const char *zDbName,        /* Database name or NULL */
131168   const char *zTableName,     /* Table name */
131169   const char *zColumnName,    /* Column name */
131170   char const **pzDataType,    /* OUTPUT: Declared data type */
131171   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
131172   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
131173   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
131174   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
131175 ){
131176   int rc;
131177   char *zErrMsg = 0;
131178   Table *pTab = 0;
131179   Column *pCol = 0;
131180   int iCol = 0;
131181   char const *zDataType = 0;
131182   char const *zCollSeq = 0;
131183   int notnull = 0;
131184   int primarykey = 0;
131185   int autoinc = 0;
131186 
131187 
131188 #ifdef SQLITE_ENABLE_API_ARMOR
131189   if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
131190     return SQLITE_MISUSE_BKPT;
131191   }
131192 #endif
131193 
131194   /* Ensure the database schema has been loaded */
131195   sqlite3_mutex_enter(db->mutex);
131196   sqlite3BtreeEnterAll(db);
131197   rc = sqlite3Init(db, &zErrMsg);
131198   if( SQLITE_OK!=rc ){
131199     goto error_out;
131200   }
131201 
131202   /* Locate the table in question */
131203   pTab = sqlite3FindTable(db, zTableName, zDbName);
131204   if( !pTab || pTab->pSelect ){
131205     pTab = 0;
131206     goto error_out;
131207   }
131208 
131209   /* Find the column for which info is requested */
131210   if( zColumnName==0 ){
131211     /* Query for existance of table only */
131212   }else{
131213     for(iCol=0; iCol<pTab->nCol; iCol++){
131214       pCol = &pTab->aCol[iCol];
131215       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
131216         break;
131217       }
131218     }
131219     if( iCol==pTab->nCol ){
131220       if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
131221         iCol = pTab->iPKey;
131222         pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
131223       }else{
131224         pTab = 0;
131225         goto error_out;
131226       }
131227     }
131228   }
131229 
131230   /* The following block stores the meta information that will be returned
131231   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
131232   ** and autoinc. At this point there are two possibilities:
131233   **
131234   **     1. The specified column name was rowid", "oid" or "_rowid_"
131235   **        and there is no explicitly declared IPK column.
131236   **
131237   **     2. The table is not a view and the column name identified an
131238   **        explicitly declared column. Copy meta information from *pCol.
131239   */
131240   if( pCol ){
131241     zDataType = pCol->zType;
131242     zCollSeq = pCol->zColl;
131243     notnull = pCol->notNull!=0;
131244     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
131245     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
131246   }else{
131247     zDataType = "INTEGER";
131248     primarykey = 1;
131249   }
131250   if( !zCollSeq ){
131251     zCollSeq = "BINARY";
131252   }
131253 
131254 error_out:
131255   sqlite3BtreeLeaveAll(db);
131256 
131257   /* Whether the function call succeeded or failed, set the output parameters
131258   ** to whatever their local counterparts contain. If an error did occur,
131259   ** this has the effect of zeroing all output parameters.
131260   */
131261   if( pzDataType ) *pzDataType = zDataType;
131262   if( pzCollSeq ) *pzCollSeq = zCollSeq;
131263   if( pNotNull ) *pNotNull = notnull;
131264   if( pPrimaryKey ) *pPrimaryKey = primarykey;
131265   if( pAutoinc ) *pAutoinc = autoinc;
131266 
131267   if( SQLITE_OK==rc && !pTab ){
131268     sqlite3DbFree(db, zErrMsg);
131269     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
131270         zColumnName);
131271     rc = SQLITE_ERROR;
131272   }
131273   sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
131274   sqlite3DbFree(db, zErrMsg);
131275   rc = sqlite3ApiExit(db, rc);
131276   sqlite3_mutex_leave(db->mutex);
131277   return rc;
131278 }
131279 
131280 /*
131281 ** Sleep for a little while.  Return the amount of time slept.
131282 */
131283 SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int ms){
131284   sqlite3_vfs *pVfs;
131285   int rc;
131286   pVfs = sqlite3_vfs_find(0);
131287   if( pVfs==0 ) return 0;
131288 
131289   /* This function works in milliseconds, but the underlying OsSleep()
131290   ** API uses microseconds. Hence the 1000's.
131291   */
131292   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
131293   return rc;
131294 }
131295 
131296 /*
131297 ** Enable or disable the extended result codes.
131298 */
131299 SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3 *db, int onoff){
131300 #ifdef SQLITE_ENABLE_API_ARMOR
131301   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
131302 #endif
131303   sqlite3_mutex_enter(db->mutex);
131304   db->errMask = onoff ? 0xffffffff : 0xff;
131305   sqlite3_mutex_leave(db->mutex);
131306   return SQLITE_OK;
131307 }
131308 
131309 /*
131310 ** Invoke the xFileControl method on a particular database.
131311 */
131312 SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
131313   int rc = SQLITE_ERROR;
131314   Btree *pBtree;
131315 
131316 #ifdef SQLITE_ENABLE_API_ARMOR
131317   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
131318 #endif
131319   sqlite3_mutex_enter(db->mutex);
131320   pBtree = sqlite3DbNameToBtree(db, zDbName);
131321   if( pBtree ){
131322     Pager *pPager;
131323     sqlite3_file *fd;
131324     sqlite3BtreeEnter(pBtree);
131325     pPager = sqlite3BtreePager(pBtree);
131326     assert( pPager!=0 );
131327     fd = sqlite3PagerFile(pPager);
131328     assert( fd!=0 );
131329     if( op==SQLITE_FCNTL_FILE_POINTER ){
131330       *(sqlite3_file**)pArg = fd;
131331       rc = SQLITE_OK;
131332     }else if( fd->pMethods ){
131333       rc = sqlite3OsFileControl(fd, op, pArg);
131334     }else{
131335       rc = SQLITE_NOTFOUND;
131336     }
131337     sqlite3BtreeLeave(pBtree);
131338   }
131339   sqlite3_mutex_leave(db->mutex);
131340   return rc;
131341 }
131342 
131343 /*
131344 ** Interface to the testing logic.
131345 */
131346 SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...){
131347   int rc = 0;
131348 #ifndef SQLITE_OMIT_BUILTIN_TEST
131349   va_list ap;
131350   va_start(ap, op);
131351   switch( op ){
131352 
131353     /*
131354     ** Save the current state of the PRNG.
131355     */
131356     case SQLITE_TESTCTRL_PRNG_SAVE: {
131357       sqlite3PrngSaveState();
131358       break;
131359     }
131360 
131361     /*
131362     ** Restore the state of the PRNG to the last state saved using
131363     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
131364     ** this verb acts like PRNG_RESET.
131365     */
131366     case SQLITE_TESTCTRL_PRNG_RESTORE: {
131367       sqlite3PrngRestoreState();
131368       break;
131369     }
131370 
131371     /*
131372     ** Reset the PRNG back to its uninitialized state.  The next call
131373     ** to sqlite3_randomness() will reseed the PRNG using a single call
131374     ** to the xRandomness method of the default VFS.
131375     */
131376     case SQLITE_TESTCTRL_PRNG_RESET: {
131377       sqlite3_randomness(0,0);
131378       break;
131379     }
131380 
131381     /*
131382     **  sqlite3_test_control(BITVEC_TEST, size, program)
131383     **
131384     ** Run a test against a Bitvec object of size.  The program argument
131385     ** is an array of integers that defines the test.  Return -1 on a
131386     ** memory allocation error, 0 on success, or non-zero for an error.
131387     ** See the sqlite3BitvecBuiltinTest() for additional information.
131388     */
131389     case SQLITE_TESTCTRL_BITVEC_TEST: {
131390       int sz = va_arg(ap, int);
131391       int *aProg = va_arg(ap, int*);
131392       rc = sqlite3BitvecBuiltinTest(sz, aProg);
131393       break;
131394     }
131395 
131396     /*
131397     **  sqlite3_test_control(FAULT_INSTALL, xCallback)
131398     **
131399     ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
131400     ** if xCallback is not NULL.
131401     **
131402     ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
131403     ** is called immediately after installing the new callback and the return
131404     ** value from sqlite3FaultSim(0) becomes the return from
131405     ** sqlite3_test_control().
131406     */
131407     case SQLITE_TESTCTRL_FAULT_INSTALL: {
131408       /* MSVC is picky about pulling func ptrs from va lists.
131409       ** http://support.microsoft.com/kb/47961
131410       ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
131411       */
131412       typedef int(*TESTCALLBACKFUNC_t)(int);
131413       sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
131414       rc = sqlite3FaultSim(0);
131415       break;
131416     }
131417 
131418     /*
131419     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
131420     **
131421     ** Register hooks to call to indicate which malloc() failures
131422     ** are benign.
131423     */
131424     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
131425       typedef void (*void_function)(void);
131426       void_function xBenignBegin;
131427       void_function xBenignEnd;
131428       xBenignBegin = va_arg(ap, void_function);
131429       xBenignEnd = va_arg(ap, void_function);
131430       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
131431       break;
131432     }
131433 
131434     /*
131435     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
131436     **
131437     ** Set the PENDING byte to the value in the argument, if X>0.
131438     ** Make no changes if X==0.  Return the value of the pending byte
131439     ** as it existing before this routine was called.
131440     **
131441     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
131442     ** an incompatible database file format.  Changing the PENDING byte
131443     ** while any database connection is open results in undefined and
131444     ** deleterious behavior.
131445     */
131446     case SQLITE_TESTCTRL_PENDING_BYTE: {
131447       rc = PENDING_BYTE;
131448 #ifndef SQLITE_OMIT_WSD
131449       {
131450         unsigned int newVal = va_arg(ap, unsigned int);
131451         if( newVal ) sqlite3PendingByte = newVal;
131452       }
131453 #endif
131454       break;
131455     }
131456 
131457     /*
131458     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
131459     **
131460     ** This action provides a run-time test to see whether or not
131461     ** assert() was enabled at compile-time.  If X is true and assert()
131462     ** is enabled, then the return value is true.  If X is true and
131463     ** assert() is disabled, then the return value is zero.  If X is
131464     ** false and assert() is enabled, then the assertion fires and the
131465     ** process aborts.  If X is false and assert() is disabled, then the
131466     ** return value is zero.
131467     */
131468     case SQLITE_TESTCTRL_ASSERT: {
131469       volatile int x = 0;
131470       assert( (x = va_arg(ap,int))!=0 );
131471       rc = x;
131472       break;
131473     }
131474 
131475 
131476     /*
131477     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
131478     **
131479     ** This action provides a run-time test to see how the ALWAYS and
131480     ** NEVER macros were defined at compile-time.
131481     **
131482     ** The return value is ALWAYS(X).
131483     **
131484     ** The recommended test is X==2.  If the return value is 2, that means
131485     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
131486     ** default setting.  If the return value is 1, then ALWAYS() is either
131487     ** hard-coded to true or else it asserts if its argument is false.
131488     ** The first behavior (hard-coded to true) is the case if
131489     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
131490     ** behavior (assert if the argument to ALWAYS() is false) is the case if
131491     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
131492     **
131493     ** The run-time test procedure might look something like this:
131494     **
131495     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
131496     **      // ALWAYS() and NEVER() are no-op pass-through macros
131497     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
131498     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
131499     **    }else{
131500     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
131501     **    }
131502     */
131503     case SQLITE_TESTCTRL_ALWAYS: {
131504       int x = va_arg(ap,int);
131505       rc = ALWAYS(x);
131506       break;
131507     }
131508 
131509     /*
131510     **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
131511     **
131512     ** The integer returned reveals the byte-order of the computer on which
131513     ** SQLite is running:
131514     **
131515     **       1     big-endian,    determined at run-time
131516     **      10     little-endian, determined at run-time
131517     **  432101     big-endian,    determined at compile-time
131518     **  123410     little-endian, determined at compile-time
131519     */
131520     case SQLITE_TESTCTRL_BYTEORDER: {
131521       rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
131522       break;
131523     }
131524 
131525     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
131526     **
131527     ** Set the nReserve size to N for the main database on the database
131528     ** connection db.
131529     */
131530     case SQLITE_TESTCTRL_RESERVE: {
131531       sqlite3 *db = va_arg(ap, sqlite3*);
131532       int x = va_arg(ap,int);
131533       sqlite3_mutex_enter(db->mutex);
131534       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
131535       sqlite3_mutex_leave(db->mutex);
131536       break;
131537     }
131538 
131539     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
131540     **
131541     ** Enable or disable various optimizations for testing purposes.  The
131542     ** argument N is a bitmask of optimizations to be disabled.  For normal
131543     ** operation N should be 0.  The idea is that a test program (like the
131544     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
131545     ** with various optimizations disabled to verify that the same answer
131546     ** is obtained in every case.
131547     */
131548     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
131549       sqlite3 *db = va_arg(ap, sqlite3*);
131550       db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
131551       break;
131552     }
131553 
131554 #ifdef SQLITE_N_KEYWORD
131555     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
131556     **
131557     ** If zWord is a keyword recognized by the parser, then return the
131558     ** number of keywords.  Or if zWord is not a keyword, return 0.
131559     **
131560     ** This test feature is only available in the amalgamation since
131561     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
131562     ** is built using separate source files.
131563     */
131564     case SQLITE_TESTCTRL_ISKEYWORD: {
131565       const char *zWord = va_arg(ap, const char*);
131566       int n = sqlite3Strlen30(zWord);
131567       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
131568       break;
131569     }
131570 #endif
131571 
131572     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
131573     **
131574     ** Pass pFree into sqlite3ScratchFree().
131575     ** If sz>0 then allocate a scratch buffer into pNew.
131576     */
131577     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
131578       void *pFree, **ppNew;
131579       int sz;
131580       sz = va_arg(ap, int);
131581       ppNew = va_arg(ap, void**);
131582       pFree = va_arg(ap, void*);
131583       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
131584       sqlite3ScratchFree(pFree);
131585       break;
131586     }
131587 
131588     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
131589     **
131590     ** If parameter onoff is non-zero, configure the wrappers so that all
131591     ** subsequent calls to localtime() and variants fail. If onoff is zero,
131592     ** undo this setting.
131593     */
131594     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
131595       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
131596       break;
131597     }
131598 
131599     /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
131600     **
131601     ** Set or clear a flag that indicates that the database file is always well-
131602     ** formed and never corrupt.  This flag is clear by default, indicating that
131603     ** database files might have arbitrary corruption.  Setting the flag during
131604     ** testing causes certain assert() statements in the code to be activated
131605     ** that demonstrat invariants on well-formed database files.
131606     */
131607     case SQLITE_TESTCTRL_NEVER_CORRUPT: {
131608       sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
131609       break;
131610     }
131611 
131612 
131613     /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
131614     **
131615     ** Set the VDBE coverage callback function to xCallback with context
131616     ** pointer ptr.
131617     */
131618     case SQLITE_TESTCTRL_VDBE_COVERAGE: {
131619 #ifdef SQLITE_VDBE_COVERAGE
131620       typedef void (*branch_callback)(void*,int,u8,u8);
131621       sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
131622       sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
131623 #endif
131624       break;
131625     }
131626 
131627     /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
131628     case SQLITE_TESTCTRL_SORTER_MMAP: {
131629       sqlite3 *db = va_arg(ap, sqlite3*);
131630       db->nMaxSorterMmap = va_arg(ap, int);
131631       break;
131632     }
131633 
131634     /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
131635     **
131636     ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
131637     ** not.
131638     */
131639     case SQLITE_TESTCTRL_ISINIT: {
131640       if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
131641       break;
131642     }
131643 
131644     /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
131645     **
131646     ** This test control is used to create imposter tables.  "db" is a pointer
131647     ** to the database connection.  dbName is the database name (ex: "main" or
131648     ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
131649     ** or off.  "tnum" is the root page of the b-tree to which the imposter
131650     ** table should connect.
131651     **
131652     ** Enable imposter mode only when the schema has already been parsed.  Then
131653     ** run a single CREATE TABLE statement to construct the imposter table in
131654     ** the parsed schema.  Then turn imposter mode back off again.
131655     **
131656     ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
131657     ** the schema to be reparsed the next time it is needed.  This has the
131658     ** effect of erasing all imposter tables.
131659     */
131660     case SQLITE_TESTCTRL_IMPOSTER: {
131661       sqlite3 *db = va_arg(ap, sqlite3*);
131662       sqlite3_mutex_enter(db->mutex);
131663       db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
131664       db->init.busy = db->init.imposterTable = va_arg(ap,int);
131665       db->init.newTnum = va_arg(ap,int);
131666       if( db->init.busy==0 && db->init.newTnum>0 ){
131667         sqlite3ResetAllSchemasOfConnection(db);
131668       }
131669       sqlite3_mutex_leave(db->mutex);
131670       break;
131671     }
131672   }
131673   va_end(ap);
131674 #endif /* SQLITE_OMIT_BUILTIN_TEST */
131675   return rc;
131676 }
131677 
131678 /*
131679 ** This is a utility routine, useful to VFS implementations, that checks
131680 ** to see if a database file was a URI that contained a specific query
131681 ** parameter, and if so obtains the value of the query parameter.
131682 **
131683 ** The zFilename argument is the filename pointer passed into the xOpen()
131684 ** method of a VFS implementation.  The zParam argument is the name of the
131685 ** query parameter we seek.  This routine returns the value of the zParam
131686 ** parameter if it exists.  If the parameter does not exist, this routine
131687 ** returns a NULL pointer.
131688 */
131689 SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam){
131690   if( zFilename==0 || zParam==0 ) return 0;
131691   zFilename += sqlite3Strlen30(zFilename) + 1;
131692   while( zFilename[0] ){
131693     int x = strcmp(zFilename, zParam);
131694     zFilename += sqlite3Strlen30(zFilename) + 1;
131695     if( x==0 ) return zFilename;
131696     zFilename += sqlite3Strlen30(zFilename) + 1;
131697   }
131698   return 0;
131699 }
131700 
131701 /*
131702 ** Return a boolean value for a query parameter.
131703 */
131704 SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
131705   const char *z = sqlite3_uri_parameter(zFilename, zParam);
131706   bDflt = bDflt!=0;
131707   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
131708 }
131709 
131710 /*
131711 ** Return a 64-bit integer value for a query parameter.
131712 */
131713 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(
131714   const char *zFilename,    /* Filename as passed to xOpen */
131715   const char *zParam,       /* URI parameter sought */
131716   sqlite3_int64 bDflt       /* return if parameter is missing */
131717 ){
131718   const char *z = sqlite3_uri_parameter(zFilename, zParam);
131719   sqlite3_int64 v;
131720   if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
131721     bDflt = v;
131722   }
131723   return bDflt;
131724 }
131725 
131726 /*
131727 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
131728 */
131729 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
131730   int i;
131731   for(i=0; i<db->nDb; i++){
131732     if( db->aDb[i].pBt
131733      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
131734     ){
131735       return db->aDb[i].pBt;
131736     }
131737   }
131738   return 0;
131739 }
131740 
131741 /*
131742 ** Return the filename of the database associated with a database
131743 ** connection.
131744 */
131745 SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName){
131746   Btree *pBt;
131747 #ifdef SQLITE_ENABLE_API_ARMOR
131748   if( !sqlite3SafetyCheckOk(db) ){
131749     (void)SQLITE_MISUSE_BKPT;
131750     return 0;
131751   }
131752 #endif
131753   pBt = sqlite3DbNameToBtree(db, zDbName);
131754   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
131755 }
131756 
131757 /*
131758 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
131759 ** no such database exists.
131760 */
131761 SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
131762   Btree *pBt;
131763 #ifdef SQLITE_ENABLE_API_ARMOR
131764   if( !sqlite3SafetyCheckOk(db) ){
131765     (void)SQLITE_MISUSE_BKPT;
131766     return -1;
131767   }
131768 #endif
131769   pBt = sqlite3DbNameToBtree(db, zDbName);
131770   return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
131771 }
131772 
131773 /************** End of main.c ************************************************/
131774 /************** Begin file notify.c ******************************************/
131775 /*
131776 ** 2009 March 3
131777 **
131778 ** The author disclaims copyright to this source code.  In place of
131779 ** a legal notice, here is a blessing:
131780 **
131781 **    May you do good and not evil.
131782 **    May you find forgiveness for yourself and forgive others.
131783 **    May you share freely, never taking more than you give.
131784 **
131785 *************************************************************************
131786 **
131787 ** This file contains the implementation of the sqlite3_unlock_notify()
131788 ** API method and its associated functionality.
131789 */
131790 
131791 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
131792 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
131793 
131794 /*
131795 ** Public interfaces:
131796 **
131797 **   sqlite3ConnectionBlocked()
131798 **   sqlite3ConnectionUnlocked()
131799 **   sqlite3ConnectionClosed()
131800 **   sqlite3_unlock_notify()
131801 */
131802 
131803 #define assertMutexHeld() \
131804   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
131805 
131806 /*
131807 ** Head of a linked list of all sqlite3 objects created by this process
131808 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
131809 ** is not NULL. This variable may only accessed while the STATIC_MASTER
131810 ** mutex is held.
131811 */
131812 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
131813 
131814 #ifndef NDEBUG
131815 /*
131816 ** This function is a complex assert() that verifies the following
131817 ** properties of the blocked connections list:
131818 **
131819 **   1) Each entry in the list has a non-NULL value for either
131820 **      pUnlockConnection or pBlockingConnection, or both.
131821 **
131822 **   2) All entries in the list that share a common value for
131823 **      xUnlockNotify are grouped together.
131824 **
131825 **   3) If the argument db is not NULL, then none of the entries in the
131826 **      blocked connections list have pUnlockConnection or pBlockingConnection
131827 **      set to db. This is used when closing connection db.
131828 */
131829 static void checkListProperties(sqlite3 *db){
131830   sqlite3 *p;
131831   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
131832     int seen = 0;
131833     sqlite3 *p2;
131834 
131835     /* Verify property (1) */
131836     assert( p->pUnlockConnection || p->pBlockingConnection );
131837 
131838     /* Verify property (2) */
131839     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
131840       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
131841       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
131842       assert( db==0 || p->pUnlockConnection!=db );
131843       assert( db==0 || p->pBlockingConnection!=db );
131844     }
131845   }
131846 }
131847 #else
131848 # define checkListProperties(x)
131849 #endif
131850 
131851 /*
131852 ** Remove connection db from the blocked connections list. If connection
131853 ** db is not currently a part of the list, this function is a no-op.
131854 */
131855 static void removeFromBlockedList(sqlite3 *db){
131856   sqlite3 **pp;
131857   assertMutexHeld();
131858   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
131859     if( *pp==db ){
131860       *pp = (*pp)->pNextBlocked;
131861       break;
131862     }
131863   }
131864 }
131865 
131866 /*
131867 ** Add connection db to the blocked connections list. It is assumed
131868 ** that it is not already a part of the list.
131869 */
131870 static void addToBlockedList(sqlite3 *db){
131871   sqlite3 **pp;
131872   assertMutexHeld();
131873   for(
131874     pp=&sqlite3BlockedList;
131875     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
131876     pp=&(*pp)->pNextBlocked
131877   );
131878   db->pNextBlocked = *pp;
131879   *pp = db;
131880 }
131881 
131882 /*
131883 ** Obtain the STATIC_MASTER mutex.
131884 */
131885 static void enterMutex(void){
131886   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
131887   checkListProperties(0);
131888 }
131889 
131890 /*
131891 ** Release the STATIC_MASTER mutex.
131892 */
131893 static void leaveMutex(void){
131894   assertMutexHeld();
131895   checkListProperties(0);
131896   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
131897 }
131898 
131899 /*
131900 ** Register an unlock-notify callback.
131901 **
131902 ** This is called after connection "db" has attempted some operation
131903 ** but has received an SQLITE_LOCKED error because another connection
131904 ** (call it pOther) in the same process was busy using the same shared
131905 ** cache.  pOther is found by looking at db->pBlockingConnection.
131906 **
131907 ** If there is no blocking connection, the callback is invoked immediately,
131908 ** before this routine returns.
131909 **
131910 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
131911 ** a deadlock.
131912 **
131913 ** Otherwise, make arrangements to invoke xNotify when pOther drops
131914 ** its locks.
131915 **
131916 ** Each call to this routine overrides any prior callbacks registered
131917 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
131918 ** cancelled.
131919 */
131920 SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
131921   sqlite3 *db,
131922   void (*xNotify)(void **, int),
131923   void *pArg
131924 ){
131925   int rc = SQLITE_OK;
131926 
131927   sqlite3_mutex_enter(db->mutex);
131928   enterMutex();
131929 
131930   if( xNotify==0 ){
131931     removeFromBlockedList(db);
131932     db->pBlockingConnection = 0;
131933     db->pUnlockConnection = 0;
131934     db->xUnlockNotify = 0;
131935     db->pUnlockArg = 0;
131936   }else if( 0==db->pBlockingConnection ){
131937     /* The blocking transaction has been concluded. Or there never was a
131938     ** blocking transaction. In either case, invoke the notify callback
131939     ** immediately.
131940     */
131941     xNotify(&pArg, 1);
131942   }else{
131943     sqlite3 *p;
131944 
131945     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
131946     if( p ){
131947       rc = SQLITE_LOCKED;              /* Deadlock detected. */
131948     }else{
131949       db->pUnlockConnection = db->pBlockingConnection;
131950       db->xUnlockNotify = xNotify;
131951       db->pUnlockArg = pArg;
131952       removeFromBlockedList(db);
131953       addToBlockedList(db);
131954     }
131955   }
131956 
131957   leaveMutex();
131958   assert( !db->mallocFailed );
131959   sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
131960   sqlite3_mutex_leave(db->mutex);
131961   return rc;
131962 }
131963 
131964 /*
131965 ** This function is called while stepping or preparing a statement
131966 ** associated with connection db. The operation will return SQLITE_LOCKED
131967 ** to the user because it requires a lock that will not be available
131968 ** until connection pBlocker concludes its current transaction.
131969 */
131970 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
131971   enterMutex();
131972   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
131973     addToBlockedList(db);
131974   }
131975   db->pBlockingConnection = pBlocker;
131976   leaveMutex();
131977 }
131978 
131979 /*
131980 ** This function is called when
131981 ** the transaction opened by database db has just finished. Locks held
131982 ** by database connection db have been released.
131983 **
131984 ** This function loops through each entry in the blocked connections
131985 ** list and does the following:
131986 **
131987 **   1) If the sqlite3.pBlockingConnection member of a list entry is
131988 **      set to db, then set pBlockingConnection=0.
131989 **
131990 **   2) If the sqlite3.pUnlockConnection member of a list entry is
131991 **      set to db, then invoke the configured unlock-notify callback and
131992 **      set pUnlockConnection=0.
131993 **
131994 **   3) If the two steps above mean that pBlockingConnection==0 and
131995 **      pUnlockConnection==0, remove the entry from the blocked connections
131996 **      list.
131997 */
131998 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
131999   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
132000   int nArg = 0;                            /* Number of entries in aArg[] */
132001   sqlite3 **pp;                            /* Iterator variable */
132002   void **aArg;               /* Arguments to the unlock callback */
132003   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
132004   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
132005 
132006   aArg = aStatic;
132007   enterMutex();         /* Enter STATIC_MASTER mutex */
132008 
132009   /* This loop runs once for each entry in the blocked-connections list. */
132010   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
132011     sqlite3 *p = *pp;
132012 
132013     /* Step 1. */
132014     if( p->pBlockingConnection==db ){
132015       p->pBlockingConnection = 0;
132016     }
132017 
132018     /* Step 2. */
132019     if( p->pUnlockConnection==db ){
132020       assert( p->xUnlockNotify );
132021       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
132022         xUnlockNotify(aArg, nArg);
132023         nArg = 0;
132024       }
132025 
132026       sqlite3BeginBenignMalloc();
132027       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
132028       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
132029       if( (!aDyn && nArg==(int)ArraySize(aStatic))
132030        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
132031       ){
132032         /* The aArg[] array needs to grow. */
132033         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
132034         if( pNew ){
132035           memcpy(pNew, aArg, nArg*sizeof(void *));
132036           sqlite3_free(aDyn);
132037           aDyn = aArg = pNew;
132038         }else{
132039           /* This occurs when the array of context pointers that need to
132040           ** be passed to the unlock-notify callback is larger than the
132041           ** aStatic[] array allocated on the stack and the attempt to
132042           ** allocate a larger array from the heap has failed.
132043           **
132044           ** This is a difficult situation to handle. Returning an error
132045           ** code to the caller is insufficient, as even if an error code
132046           ** is returned the transaction on connection db will still be
132047           ** closed and the unlock-notify callbacks on blocked connections
132048           ** will go unissued. This might cause the application to wait
132049           ** indefinitely for an unlock-notify callback that will never
132050           ** arrive.
132051           **
132052           ** Instead, invoke the unlock-notify callback with the context
132053           ** array already accumulated. We can then clear the array and
132054           ** begin accumulating any further context pointers without
132055           ** requiring any dynamic allocation. This is sub-optimal because
132056           ** it means that instead of one callback with a large array of
132057           ** context pointers the application will receive two or more
132058           ** callbacks with smaller arrays of context pointers, which will
132059           ** reduce the applications ability to prioritize multiple
132060           ** connections. But it is the best that can be done under the
132061           ** circumstances.
132062           */
132063           xUnlockNotify(aArg, nArg);
132064           nArg = 0;
132065         }
132066       }
132067       sqlite3EndBenignMalloc();
132068 
132069       aArg[nArg++] = p->pUnlockArg;
132070       xUnlockNotify = p->xUnlockNotify;
132071       p->pUnlockConnection = 0;
132072       p->xUnlockNotify = 0;
132073       p->pUnlockArg = 0;
132074     }
132075 
132076     /* Step 3. */
132077     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
132078       /* Remove connection p from the blocked connections list. */
132079       *pp = p->pNextBlocked;
132080       p->pNextBlocked = 0;
132081     }else{
132082       pp = &p->pNextBlocked;
132083     }
132084   }
132085 
132086   if( nArg!=0 ){
132087     xUnlockNotify(aArg, nArg);
132088   }
132089   sqlite3_free(aDyn);
132090   leaveMutex();         /* Leave STATIC_MASTER mutex */
132091 }
132092 
132093 /*
132094 ** This is called when the database connection passed as an argument is
132095 ** being closed. The connection is removed from the blocked list.
132096 */
132097 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
132098   sqlite3ConnectionUnlocked(db);
132099   enterMutex();
132100   removeFromBlockedList(db);
132101   checkListProperties(db);
132102   leaveMutex();
132103 }
132104 #endif
132105 
132106 /************** End of notify.c **********************************************/
132107 /************** Begin file fts3.c ********************************************/
132108 /*
132109 ** 2006 Oct 10
132110 **
132111 ** The author disclaims copyright to this source code.  In place of
132112 ** a legal notice, here is a blessing:
132113 **
132114 **    May you do good and not evil.
132115 **    May you find forgiveness for yourself and forgive others.
132116 **    May you share freely, never taking more than you give.
132117 **
132118 ******************************************************************************
132119 **
132120 ** This is an SQLite module implementing full-text search.
132121 */
132122 
132123 /*
132124 ** The code in this file is only compiled if:
132125 **
132126 **     * The FTS3 module is being built as an extension
132127 **       (in which case SQLITE_CORE is not defined), or
132128 **
132129 **     * The FTS3 module is being built into the core of
132130 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
132131 */
132132 
132133 /* The full-text index is stored in a series of b+tree (-like)
132134 ** structures called segments which map terms to doclists.  The
132135 ** structures are like b+trees in layout, but are constructed from the
132136 ** bottom up in optimal fashion and are not updatable.  Since trees
132137 ** are built from the bottom up, things will be described from the
132138 ** bottom up.
132139 **
132140 **
132141 **** Varints ****
132142 ** The basic unit of encoding is a variable-length integer called a
132143 ** varint.  We encode variable-length integers in little-endian order
132144 ** using seven bits * per byte as follows:
132145 **
132146 ** KEY:
132147 **         A = 0xxxxxxx    7 bits of data and one flag bit
132148 **         B = 1xxxxxxx    7 bits of data and one flag bit
132149 **
132150 **  7 bits - A
132151 ** 14 bits - BA
132152 ** 21 bits - BBA
132153 ** and so on.
132154 **
132155 ** This is similar in concept to how sqlite encodes "varints" but
132156 ** the encoding is not the same.  SQLite varints are big-endian
132157 ** are are limited to 9 bytes in length whereas FTS3 varints are
132158 ** little-endian and can be up to 10 bytes in length (in theory).
132159 **
132160 ** Example encodings:
132161 **
132162 **     1:    0x01
132163 **   127:    0x7f
132164 **   128:    0x81 0x00
132165 **
132166 **
132167 **** Document lists ****
132168 ** A doclist (document list) holds a docid-sorted list of hits for a
132169 ** given term.  Doclists hold docids and associated token positions.
132170 ** A docid is the unique integer identifier for a single document.
132171 ** A position is the index of a word within the document.  The first
132172 ** word of the document has a position of 0.
132173 **
132174 ** FTS3 used to optionally store character offsets using a compile-time
132175 ** option.  But that functionality is no longer supported.
132176 **
132177 ** A doclist is stored like this:
132178 **
132179 ** array {
132180 **   varint docid;          (delta from previous doclist)
132181 **   array {                (position list for column 0)
132182 **     varint position;     (2 more than the delta from previous position)
132183 **   }
132184 **   array {
132185 **     varint POS_COLUMN;   (marks start of position list for new column)
132186 **     varint column;       (index of new column)
132187 **     array {
132188 **       varint position;   (2 more than the delta from previous position)
132189 **     }
132190 **   }
132191 **   varint POS_END;        (marks end of positions for this document.
132192 ** }
132193 **
132194 ** Here, array { X } means zero or more occurrences of X, adjacent in
132195 ** memory.  A "position" is an index of a token in the token stream
132196 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
132197 ** in the same logical place as the position element, and act as sentinals
132198 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
132199 ** The positions numbers are not stored literally but rather as two more
132200 ** than the difference from the prior position, or the just the position plus
132201 ** 2 for the first position.  Example:
132202 **
132203 **   label:       A B C D E  F  G H   I  J K
132204 **   value:     123 5 9 1 1 14 35 0 234 72 0
132205 **
132206 ** The 123 value is the first docid.  For column zero in this document
132207 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
132208 ** at D signals the start of a new column; the 1 at E indicates that the
132209 ** new column is column number 1.  There are two positions at 12 and 45
132210 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
132211 ** 234 at I is the delta to next docid (357).  It has one position 70
132212 ** (72-2) and then terminates with the 0 at K.
132213 **
132214 ** A "position-list" is the list of positions for multiple columns for
132215 ** a single docid.  A "column-list" is the set of positions for a single
132216 ** column.  Hence, a position-list consists of one or more column-lists,
132217 ** a document record consists of a docid followed by a position-list and
132218 ** a doclist consists of one or more document records.
132219 **
132220 ** A bare doclist omits the position information, becoming an
132221 ** array of varint-encoded docids.
132222 **
132223 **** Segment leaf nodes ****
132224 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
132225 ** nodes are written using LeafWriter, and read using LeafReader (to
132226 ** iterate through a single leaf node's data) and LeavesReader (to
132227 ** iterate through a segment's entire leaf layer).  Leaf nodes have
132228 ** the format:
132229 **
132230 ** varint iHeight;             (height from leaf level, always 0)
132231 ** varint nTerm;               (length of first term)
132232 ** char pTerm[nTerm];          (content of first term)
132233 ** varint nDoclist;            (length of term's associated doclist)
132234 ** char pDoclist[nDoclist];    (content of doclist)
132235 ** array {
132236 **                             (further terms are delta-encoded)
132237 **   varint nPrefix;           (length of prefix shared with previous term)
132238 **   varint nSuffix;           (length of unshared suffix)
132239 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
132240 **   varint nDoclist;          (length of term's associated doclist)
132241 **   char pDoclist[nDoclist];  (content of doclist)
132242 ** }
132243 **
132244 ** Here, array { X } means zero or more occurrences of X, adjacent in
132245 ** memory.
132246 **
132247 ** Leaf nodes are broken into blocks which are stored contiguously in
132248 ** the %_segments table in sorted order.  This means that when the end
132249 ** of a node is reached, the next term is in the node with the next
132250 ** greater node id.
132251 **
132252 ** New data is spilled to a new leaf node when the current node
132253 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
132254 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
132255 ** node (a leaf node with a single term and doclist).  The goal of
132256 ** these settings is to pack together groups of small doclists while
132257 ** making it efficient to directly access large doclists.  The
132258 ** assumption is that large doclists represent terms which are more
132259 ** likely to be query targets.
132260 **
132261 ** TODO(shess) It may be useful for blocking decisions to be more
132262 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
132263 ** node rather than splitting into 2k and .5k nodes.  My intuition is
132264 ** that this might extend through 2x or 4x the pagesize.
132265 **
132266 **
132267 **** Segment interior nodes ****
132268 ** Segment interior nodes store blockids for subtree nodes and terms
132269 ** to describe what data is stored by the each subtree.  Interior
132270 ** nodes are written using InteriorWriter, and read using
132271 ** InteriorReader.  InteriorWriters are created as needed when
132272 ** SegmentWriter creates new leaf nodes, or when an interior node
132273 ** itself grows too big and must be split.  The format of interior
132274 ** nodes:
132275 **
132276 ** varint iHeight;           (height from leaf level, always >0)
132277 ** varint iBlockid;          (block id of node's leftmost subtree)
132278 ** optional {
132279 **   varint nTerm;           (length of first term)
132280 **   char pTerm[nTerm];      (content of first term)
132281 **   array {
132282 **                                (further terms are delta-encoded)
132283 **     varint nPrefix;            (length of shared prefix with previous term)
132284 **     varint nSuffix;            (length of unshared suffix)
132285 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
132286 **   }
132287 ** }
132288 **
132289 ** Here, optional { X } means an optional element, while array { X }
132290 ** means zero or more occurrences of X, adjacent in memory.
132291 **
132292 ** An interior node encodes n terms separating n+1 subtrees.  The
132293 ** subtree blocks are contiguous, so only the first subtree's blockid
132294 ** is encoded.  The subtree at iBlockid will contain all terms less
132295 ** than the first term encoded (or all terms if no term is encoded).
132296 ** Otherwise, for terms greater than or equal to pTerm[i] but less
132297 ** than pTerm[i+1], the subtree for that term will be rooted at
132298 ** iBlockid+i.  Interior nodes only store enough term data to
132299 ** distinguish adjacent children (if the rightmost term of the left
132300 ** child is "something", and the leftmost term of the right child is
132301 ** "wicked", only "w" is stored).
132302 **
132303 ** New data is spilled to a new interior node at the same height when
132304 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
132305 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
132306 ** interior nodes and making the tree too skinny.  The interior nodes
132307 ** at a given height are naturally tracked by interior nodes at
132308 ** height+1, and so on.
132309 **
132310 **
132311 **** Segment directory ****
132312 ** The segment directory in table %_segdir stores meta-information for
132313 ** merging and deleting segments, and also the root node of the
132314 ** segment's tree.
132315 **
132316 ** The root node is the top node of the segment's tree after encoding
132317 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
132318 ** This could be either a leaf node or an interior node.  If the top
132319 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
132320 ** and a new root interior node is generated (which should always fit
132321 ** within ROOT_MAX because it only needs space for 2 varints, the
132322 ** height and the blockid of the previous root).
132323 **
132324 ** The meta-information in the segment directory is:
132325 **   level               - segment level (see below)
132326 **   idx                 - index within level
132327 **                       - (level,idx uniquely identify a segment)
132328 **   start_block         - first leaf node
132329 **   leaves_end_block    - last leaf node
132330 **   end_block           - last block (including interior nodes)
132331 **   root                - contents of root node
132332 **
132333 ** If the root node is a leaf node, then start_block,
132334 ** leaves_end_block, and end_block are all 0.
132335 **
132336 **
132337 **** Segment merging ****
132338 ** To amortize update costs, segments are grouped into levels and
132339 ** merged in batches.  Each increase in level represents exponentially
132340 ** more documents.
132341 **
132342 ** New documents (actually, document updates) are tokenized and
132343 ** written individually (using LeafWriter) to a level 0 segment, with
132344 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
132345 ** level 0 segments are merged into a single level 1 segment.  Level 1
132346 ** is populated like level 0, and eventually MERGE_COUNT level 1
132347 ** segments are merged to a single level 2 segment (representing
132348 ** MERGE_COUNT^2 updates), and so on.
132349 **
132350 ** A segment merge traverses all segments at a given level in
132351 ** parallel, performing a straightforward sorted merge.  Since segment
132352 ** leaf nodes are written in to the %_segments table in order, this
132353 ** merge traverses the underlying sqlite disk structures efficiently.
132354 ** After the merge, all segment blocks from the merged level are
132355 ** deleted.
132356 **
132357 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
132358 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
132359 ** very similar performance numbers to 16 on insertion, though they're
132360 ** a tiny bit slower (perhaps due to more overhead in merge-time
132361 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
132362 ** 16, 2 about 66% slower than 16.
132363 **
132364 ** At query time, high MERGE_COUNT increases the number of segments
132365 ** which need to be scanned and merged.  For instance, with 100k docs
132366 ** inserted:
132367 **
132368 **    MERGE_COUNT   segments
132369 **       16           25
132370 **        8           12
132371 **        4           10
132372 **        2            6
132373 **
132374 ** This appears to have only a moderate impact on queries for very
132375 ** frequent terms (which are somewhat dominated by segment merge
132376 ** costs), and infrequent and non-existent terms still seem to be fast
132377 ** even with many segments.
132378 **
132379 ** TODO(shess) That said, it would be nice to have a better query-side
132380 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
132381 ** optimizations to things like doclist merging will swing the sweet
132382 ** spot around.
132383 **
132384 **
132385 **
132386 **** Handling of deletions and updates ****
132387 ** Since we're using a segmented structure, with no docid-oriented
132388 ** index into the term index, we clearly cannot simply update the term
132389 ** index when a document is deleted or updated.  For deletions, we
132390 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
132391 ** we simply write the new doclist.  Segment merges overwrite older
132392 ** data for a particular docid with newer data, so deletes or updates
132393 ** will eventually overtake the earlier data and knock it out.  The
132394 ** query logic likewise merges doclists so that newer data knocks out
132395 ** older data.
132396 */
132397 
132398 /************** Include fts3Int.h in the middle of fts3.c ********************/
132399 /************** Begin file fts3Int.h *****************************************/
132400 /*
132401 ** 2009 Nov 12
132402 **
132403 ** The author disclaims copyright to this source code.  In place of
132404 ** a legal notice, here is a blessing:
132405 **
132406 **    May you do good and not evil.
132407 **    May you find forgiveness for yourself and forgive others.
132408 **    May you share freely, never taking more than you give.
132409 **
132410 ******************************************************************************
132411 **
132412 */
132413 #ifndef _FTSINT_H
132414 #define _FTSINT_H
132415 
132416 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
132417 # define NDEBUG 1
132418 #endif
132419 
132420 /*
132421 ** FTS4 is really an extension for FTS3.  It is enabled using the
132422 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
132423 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
132424 */
132425 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
132426 # define SQLITE_ENABLE_FTS3
132427 #endif
132428 
132429 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
132430 
132431 /* If not building as part of the core, include sqlite3ext.h. */
132432 #ifndef SQLITE_CORE
132433 SQLITE_EXTENSION_INIT3
132434 #endif
132435 
132436 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
132437 /************** Begin file fts3_tokenizer.h **********************************/
132438 /*
132439 ** 2006 July 10
132440 **
132441 ** The author disclaims copyright to this source code.
132442 **
132443 *************************************************************************
132444 ** Defines the interface to tokenizers used by fulltext-search.  There
132445 ** are three basic components:
132446 **
132447 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
132448 ** interface functions.  This is essentially the class structure for
132449 ** tokenizers.
132450 **
132451 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
132452 ** including customization information defined at creation time.
132453 **
132454 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
132455 ** tokens from a particular input.
132456 */
132457 #ifndef _FTS3_TOKENIZER_H_
132458 #define _FTS3_TOKENIZER_H_
132459 
132460 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
132461 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
132462 ** we will need a way to register the API consistently.
132463 */
132464 
132465 /*
132466 ** Structures used by the tokenizer interface. When a new tokenizer
132467 ** implementation is registered, the caller provides a pointer to
132468 ** an sqlite3_tokenizer_module containing pointers to the callback
132469 ** functions that make up an implementation.
132470 **
132471 ** When an fts3 table is created, it passes any arguments passed to
132472 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
132473 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
132474 ** implementation. The xCreate() function in turn returns an
132475 ** sqlite3_tokenizer structure representing the specific tokenizer to
132476 ** be used for the fts3 table (customized by the tokenizer clause arguments).
132477 **
132478 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
132479 ** method is called. It returns an sqlite3_tokenizer_cursor object
132480 ** that may be used to tokenize a specific input buffer based on
132481 ** the tokenization rules supplied by a specific sqlite3_tokenizer
132482 ** object.
132483 */
132484 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
132485 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
132486 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
132487 
132488 struct sqlite3_tokenizer_module {
132489 
132490   /*
132491   ** Structure version. Should always be set to 0 or 1.
132492   */
132493   int iVersion;
132494 
132495   /*
132496   ** Create a new tokenizer. The values in the argv[] array are the
132497   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
132498   ** TABLE statement that created the fts3 table. For example, if
132499   ** the following SQL is executed:
132500   **
132501   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
132502   **
132503   ** then argc is set to 2, and the argv[] array contains pointers
132504   ** to the strings "arg1" and "arg2".
132505   **
132506   ** This method should return either SQLITE_OK (0), or an SQLite error
132507   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
132508   ** to point at the newly created tokenizer structure. The generic
132509   ** sqlite3_tokenizer.pModule variable should not be initialized by
132510   ** this callback. The caller will do so.
132511   */
132512   int (*xCreate)(
132513     int argc,                           /* Size of argv array */
132514     const char *const*argv,             /* Tokenizer argument strings */
132515     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
132516   );
132517 
132518   /*
132519   ** Destroy an existing tokenizer. The fts3 module calls this method
132520   ** exactly once for each successful call to xCreate().
132521   */
132522   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
132523 
132524   /*
132525   ** Create a tokenizer cursor to tokenize an input buffer. The caller
132526   ** is responsible for ensuring that the input buffer remains valid
132527   ** until the cursor is closed (using the xClose() method).
132528   */
132529   int (*xOpen)(
132530     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
132531     const char *pInput, int nBytes,      /* Input buffer */
132532     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
132533   );
132534 
132535   /*
132536   ** Destroy an existing tokenizer cursor. The fts3 module calls this
132537   ** method exactly once for each successful call to xOpen().
132538   */
132539   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
132540 
132541   /*
132542   ** Retrieve the next token from the tokenizer cursor pCursor. This
132543   ** method should either return SQLITE_OK and set the values of the
132544   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
132545   ** the end of the buffer has been reached, or an SQLite error code.
132546   **
132547   ** *ppToken should be set to point at a buffer containing the
132548   ** normalized version of the token (i.e. after any case-folding and/or
132549   ** stemming has been performed). *pnBytes should be set to the length
132550   ** of this buffer in bytes. The input text that generated the token is
132551   ** identified by the byte offsets returned in *piStartOffset and
132552   ** *piEndOffset. *piStartOffset should be set to the index of the first
132553   ** byte of the token in the input buffer. *piEndOffset should be set
132554   ** to the index of the first byte just past the end of the token in
132555   ** the input buffer.
132556   **
132557   ** The buffer *ppToken is set to point at is managed by the tokenizer
132558   ** implementation. It is only required to be valid until the next call
132559   ** to xNext() or xClose().
132560   */
132561   /* TODO(shess) current implementation requires pInput to be
132562   ** nul-terminated.  This should either be fixed, or pInput/nBytes
132563   ** should be converted to zInput.
132564   */
132565   int (*xNext)(
132566     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
132567     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
132568     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
132569     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
132570     int *piPosition      /* OUT: Number of tokens returned before this one */
132571   );
132572 
132573   /***********************************************************************
132574   ** Methods below this point are only available if iVersion>=1.
132575   */
132576 
132577   /*
132578   ** Configure the language id of a tokenizer cursor.
132579   */
132580   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
132581 };
132582 
132583 struct sqlite3_tokenizer {
132584   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
132585   /* Tokenizer implementations will typically add additional fields */
132586 };
132587 
132588 struct sqlite3_tokenizer_cursor {
132589   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
132590   /* Tokenizer implementations will typically add additional fields */
132591 };
132592 
132593 int fts3_global_term_cnt(int iTerm, int iCol);
132594 int fts3_term_cnt(int iTerm, int iCol);
132595 
132596 
132597 #endif /* _FTS3_TOKENIZER_H_ */
132598 
132599 /************** End of fts3_tokenizer.h **************************************/
132600 /************** Continuing where we left off in fts3Int.h ********************/
132601 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
132602 /************** Begin file fts3_hash.h ***************************************/
132603 /*
132604 ** 2001 September 22
132605 **
132606 ** The author disclaims copyright to this source code.  In place of
132607 ** a legal notice, here is a blessing:
132608 **
132609 **    May you do good and not evil.
132610 **    May you find forgiveness for yourself and forgive others.
132611 **    May you share freely, never taking more than you give.
132612 **
132613 *************************************************************************
132614 ** This is the header file for the generic hash-table implementation
132615 ** used in SQLite.  We've modified it slightly to serve as a standalone
132616 ** hash table implementation for the full-text indexing module.
132617 **
132618 */
132619 #ifndef _FTS3_HASH_H_
132620 #define _FTS3_HASH_H_
132621 
132622 /* Forward declarations of structures. */
132623 typedef struct Fts3Hash Fts3Hash;
132624 typedef struct Fts3HashElem Fts3HashElem;
132625 
132626 /* A complete hash table is an instance of the following structure.
132627 ** The internals of this structure are intended to be opaque -- client
132628 ** code should not attempt to access or modify the fields of this structure
132629 ** directly.  Change this structure only by using the routines below.
132630 ** However, many of the "procedures" and "functions" for modifying and
132631 ** accessing this structure are really macros, so we can't really make
132632 ** this structure opaque.
132633 */
132634 struct Fts3Hash {
132635   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
132636   char copyKey;           /* True if copy of key made on insert */
132637   int count;              /* Number of entries in this table */
132638   Fts3HashElem *first;    /* The first element of the array */
132639   int htsize;             /* Number of buckets in the hash table */
132640   struct _fts3ht {        /* the hash table */
132641     int count;               /* Number of entries with this hash */
132642     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
132643   } *ht;
132644 };
132645 
132646 /* Each element in the hash table is an instance of the following
132647 ** structure.  All elements are stored on a single doubly-linked list.
132648 **
132649 ** Again, this structure is intended to be opaque, but it can't really
132650 ** be opaque because it is used by macros.
132651 */
132652 struct Fts3HashElem {
132653   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
132654   void *data;                /* Data associated with this element */
132655   void *pKey; int nKey;      /* Key associated with this element */
132656 };
132657 
132658 /*
132659 ** There are 2 different modes of operation for a hash table:
132660 **
132661 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
132662 **                           (including the null-terminator, if any).  Case
132663 **                           is respected in comparisons.
132664 **
132665 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
132666 **                           memcmp() is used to compare keys.
132667 **
132668 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
132669 */
132670 #define FTS3_HASH_STRING    1
132671 #define FTS3_HASH_BINARY    2
132672 
132673 /*
132674 ** Access routines.  To delete, insert a NULL pointer.
132675 */
132676 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
132677 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
132678 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
132679 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
132680 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
132681 
132682 /*
132683 ** Shorthand for the functions above
132684 */
132685 #define fts3HashInit     sqlite3Fts3HashInit
132686 #define fts3HashInsert   sqlite3Fts3HashInsert
132687 #define fts3HashFind     sqlite3Fts3HashFind
132688 #define fts3HashClear    sqlite3Fts3HashClear
132689 #define fts3HashFindElem sqlite3Fts3HashFindElem
132690 
132691 /*
132692 ** Macros for looping over all elements of a hash table.  The idiom is
132693 ** like this:
132694 **
132695 **   Fts3Hash h;
132696 **   Fts3HashElem *p;
132697 **   ...
132698 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
132699 **     SomeStructure *pData = fts3HashData(p);
132700 **     // do something with pData
132701 **   }
132702 */
132703 #define fts3HashFirst(H)  ((H)->first)
132704 #define fts3HashNext(E)   ((E)->next)
132705 #define fts3HashData(E)   ((E)->data)
132706 #define fts3HashKey(E)    ((E)->pKey)
132707 #define fts3HashKeysize(E) ((E)->nKey)
132708 
132709 /*
132710 ** Number of entries in a hash table
132711 */
132712 #define fts3HashCount(H)  ((H)->count)
132713 
132714 #endif /* _FTS3_HASH_H_ */
132715 
132716 /************** End of fts3_hash.h *******************************************/
132717 /************** Continuing where we left off in fts3Int.h ********************/
132718 
132719 /*
132720 ** This constant determines the maximum depth of an FTS expression tree
132721 ** that the library will create and use. FTS uses recursion to perform
132722 ** various operations on the query tree, so the disadvantage of a large
132723 ** limit is that it may allow very large queries to use large amounts
132724 ** of stack space (perhaps causing a stack overflow).
132725 */
132726 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
132727 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
132728 #endif
132729 
132730 
132731 /*
132732 ** This constant controls how often segments are merged. Once there are
132733 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
132734 ** segment of level N+1.
132735 */
132736 #define FTS3_MERGE_COUNT 16
132737 
132738 /*
132739 ** This is the maximum amount of data (in bytes) to store in the
132740 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
132741 ** populated as documents are inserted/updated/deleted in a transaction
132742 ** and used to create a new segment when the transaction is committed.
132743 ** However if this limit is reached midway through a transaction, a new
132744 ** segment is created and the hash table cleared immediately.
132745 */
132746 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
132747 
132748 /*
132749 ** Macro to return the number of elements in an array. SQLite has a
132750 ** similar macro called ArraySize(). Use a different name to avoid
132751 ** a collision when building an amalgamation with built-in FTS3.
132752 */
132753 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
132754 
132755 
132756 #ifndef MIN
132757 # define MIN(x,y) ((x)<(y)?(x):(y))
132758 #endif
132759 #ifndef MAX
132760 # define MAX(x,y) ((x)>(y)?(x):(y))
132761 #endif
132762 
132763 /*
132764 ** Maximum length of a varint encoded integer. The varint format is different
132765 ** from that used by SQLite, so the maximum length is 10, not 9.
132766 */
132767 #define FTS3_VARINT_MAX 10
132768 
132769 /*
132770 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
132771 ** in the document set and zero or more prefix indexes. All indexes are stored
132772 ** as one or more b+-trees in the %_segments and %_segdir tables.
132773 **
132774 ** It is possible to determine which index a b+-tree belongs to based on the
132775 ** value stored in the "%_segdir.level" column. Given this value L, the index
132776 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
132777 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
132778 ** between 1024 and 2047 to index 1, and so on.
132779 **
132780 ** It is considered impossible for an index to use more than 1024 levels. In
132781 ** theory though this may happen, but only after at least
132782 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
132783 */
132784 #define FTS3_SEGDIR_MAXLEVEL      1024
132785 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
132786 
132787 /*
132788 ** The testcase() macro is only used by the amalgamation.  If undefined,
132789 ** make it a no-op.
132790 */
132791 #ifndef testcase
132792 # define testcase(X)
132793 #endif
132794 
132795 /*
132796 ** Terminator values for position-lists and column-lists.
132797 */
132798 #define POS_COLUMN  (1)     /* Column-list terminator */
132799 #define POS_END     (0)     /* Position-list terminator */
132800 
132801 /*
132802 ** This section provides definitions to allow the
132803 ** FTS3 extension to be compiled outside of the
132804 ** amalgamation.
132805 */
132806 #ifndef SQLITE_AMALGAMATION
132807 /*
132808 ** Macros indicating that conditional expressions are always true or
132809 ** false.
132810 */
132811 #ifdef SQLITE_COVERAGE_TEST
132812 # define ALWAYS(x) (1)
132813 # define NEVER(X)  (0)
132814 #elif defined(SQLITE_DEBUG)
132815 # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
132816 # define NEVER(x) sqlite3Fts3Never((x)!=0)
132817 SQLITE_PRIVATE int sqlite3Fts3Always(int b);
132818 SQLITE_PRIVATE int sqlite3Fts3Never(int b);
132819 #else
132820 # define ALWAYS(x) (x)
132821 # define NEVER(x)  (x)
132822 #endif
132823 
132824 /*
132825 ** Internal types used by SQLite.
132826 */
132827 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
132828 typedef short int i16;            /* 2-byte (or larger) signed integer */
132829 typedef unsigned int u32;         /* 4-byte unsigned integer */
132830 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
132831 typedef sqlite3_int64 i64;        /* 8-byte signed integer */
132832 
132833 /*
132834 ** Macro used to suppress compiler warnings for unused parameters.
132835 */
132836 #define UNUSED_PARAMETER(x) (void)(x)
132837 
132838 /*
132839 ** Activate assert() only if SQLITE_TEST is enabled.
132840 */
132841 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
132842 # define NDEBUG 1
132843 #endif
132844 
132845 /*
132846 ** The TESTONLY macro is used to enclose variable declarations or
132847 ** other bits of code that are needed to support the arguments
132848 ** within testcase() and assert() macros.
132849 */
132850 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
132851 # define TESTONLY(X)  X
132852 #else
132853 # define TESTONLY(X)
132854 #endif
132855 
132856 #endif /* SQLITE_AMALGAMATION */
132857 
132858 #ifdef SQLITE_DEBUG
132859 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
132860 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
132861 #else
132862 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
132863 #endif
132864 
132865 typedef struct Fts3Table Fts3Table;
132866 typedef struct Fts3Cursor Fts3Cursor;
132867 typedef struct Fts3Expr Fts3Expr;
132868 typedef struct Fts3Phrase Fts3Phrase;
132869 typedef struct Fts3PhraseToken Fts3PhraseToken;
132870 
132871 typedef struct Fts3Doclist Fts3Doclist;
132872 typedef struct Fts3SegFilter Fts3SegFilter;
132873 typedef struct Fts3DeferredToken Fts3DeferredToken;
132874 typedef struct Fts3SegReader Fts3SegReader;
132875 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
132876 
132877 /*
132878 ** A connection to a fulltext index is an instance of the following
132879 ** structure. The xCreate and xConnect methods create an instance
132880 ** of this structure and xDestroy and xDisconnect free that instance.
132881 ** All other methods receive a pointer to the structure as one of their
132882 ** arguments.
132883 */
132884 struct Fts3Table {
132885   sqlite3_vtab base;              /* Base class used by SQLite core */
132886   sqlite3 *db;                    /* The database connection */
132887   const char *zDb;                /* logical database name */
132888   const char *zName;              /* virtual table name */
132889   int nColumn;                    /* number of named columns in virtual table */
132890   char **azColumn;                /* column names.  malloced */
132891   u8 *abNotindexed;               /* True for 'notindexed' columns */
132892   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
132893   char *zContentTbl;              /* content=xxx option, or NULL */
132894   char *zLanguageid;              /* languageid=xxx option, or NULL */
132895   int nAutoincrmerge;             /* Value configured by 'automerge' */
132896   u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
132897 
132898   /* Precompiled statements used by the implementation. Each of these
132899   ** statements is run and reset within a single virtual table API call.
132900   */
132901   sqlite3_stmt *aStmt[40];
132902 
132903   char *zReadExprlist;
132904   char *zWriteExprlist;
132905 
132906   int nNodeSize;                  /* Soft limit for node size */
132907   u8 bFts4;                       /* True for FTS4, false for FTS3 */
132908   u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
132909   u8 bHasDocsize;                 /* True if %_docsize table exists */
132910   u8 bDescIdx;                    /* True if doclists are in reverse order */
132911   u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
132912   int nPgsz;                      /* Page size for host database */
132913   char *zSegmentsTbl;             /* Name of %_segments table */
132914   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
132915 
132916   /*
132917   ** The following array of hash tables is used to buffer pending index
132918   ** updates during transactions. All pending updates buffered at any one
132919   ** time must share a common language-id (see the FTS4 langid= feature).
132920   ** The current language id is stored in variable iPrevLangid.
132921   **
132922   ** A single FTS4 table may have multiple full-text indexes. For each index
132923   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
132924   ** terms that appear in the document set. Each subsequent index in aIndex[]
132925   ** is an index of prefixes of a specific length.
132926   **
132927   ** Variable nPendingData contains an estimate the memory consumed by the
132928   ** pending data structures, including hash table overhead, but not including
132929   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
132930   ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
132931   ** recently inserted record.
132932   */
132933   int nIndex;                     /* Size of aIndex[] */
132934   struct Fts3Index {
132935     int nPrefix;                  /* Prefix length (0 for main terms index) */
132936     Fts3Hash hPending;            /* Pending terms table for this index */
132937   } *aIndex;
132938   int nMaxPendingData;            /* Max pending data before flush to disk */
132939   int nPendingData;               /* Current bytes of pending data */
132940   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
132941   int iPrevLangid;                /* Langid of recently inserted document */
132942 
132943 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
132944   /* State variables used for validating that the transaction control
132945   ** methods of the virtual table are called at appropriate times.  These
132946   ** values do not contribute to FTS functionality; they are used for
132947   ** verifying the operation of the SQLite core.
132948   */
132949   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
132950   int mxSavepoint;       /* Largest valid xSavepoint integer */
132951 #endif
132952 
132953 #ifdef SQLITE_TEST
132954   /* True to disable the incremental doclist optimization. This is controled
132955   ** by special insert command 'test-no-incr-doclist'.  */
132956   int bNoIncrDoclist;
132957 #endif
132958 };
132959 
132960 /*
132961 ** When the core wants to read from the virtual table, it creates a
132962 ** virtual table cursor (an instance of the following structure) using
132963 ** the xOpen method. Cursors are destroyed using the xClose method.
132964 */
132965 struct Fts3Cursor {
132966   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
132967   i16 eSearch;                    /* Search strategy (see below) */
132968   u8 isEof;                       /* True if at End Of Results */
132969   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
132970   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
132971   Fts3Expr *pExpr;                /* Parsed MATCH query string */
132972   int iLangid;                    /* Language being queried for */
132973   int nPhrase;                    /* Number of matchable phrases in query */
132974   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
132975   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
132976   char *pNextId;                  /* Pointer into the body of aDoclist */
132977   char *aDoclist;                 /* List of docids for full-text queries */
132978   int nDoclist;                   /* Size of buffer at aDoclist */
132979   u8 bDesc;                       /* True to sort in descending order */
132980   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
132981   int nRowAvg;                    /* Average size of database rows, in pages */
132982   sqlite3_int64 nDoc;             /* Documents in table */
132983   i64 iMinDocid;                  /* Minimum docid to return */
132984   i64 iMaxDocid;                  /* Maximum docid to return */
132985   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
132986   u32 *aMatchinfo;                /* Information about most recent match */
132987   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
132988   char *zMatchinfo;               /* Matchinfo specification */
132989 };
132990 
132991 #define FTS3_EVAL_FILTER    0
132992 #define FTS3_EVAL_NEXT      1
132993 #define FTS3_EVAL_MATCHINFO 2
132994 
132995 /*
132996 ** The Fts3Cursor.eSearch member is always set to one of the following.
132997 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
132998 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
132999 ** of the column to be searched.  For example, in
133000 **
133001 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
133002 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
133003 **
133004 ** Because the LHS of the MATCH operator is 2nd column "b",
133005 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
133006 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
133007 ** indicating that all columns should be searched,
133008 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
133009 */
133010 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
133011 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
133012 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
133013 
133014 /*
133015 ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
133016 ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
133017 ** above. The upper 16-bits contain a combination of the following
133018 ** bits, used to describe extra constraints on full-text searches.
133019 */
133020 #define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
133021 #define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
133022 #define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
133023 
133024 struct Fts3Doclist {
133025   char *aAll;                    /* Array containing doclist (or NULL) */
133026   int nAll;                      /* Size of a[] in bytes */
133027   char *pNextDocid;              /* Pointer to next docid */
133028 
133029   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
133030   int bFreeList;                 /* True if pList should be sqlite3_free()d */
133031   char *pList;                   /* Pointer to position list following iDocid */
133032   int nList;                     /* Length of position list */
133033 };
133034 
133035 /*
133036 ** A "phrase" is a sequence of one or more tokens that must match in
133037 ** sequence.  A single token is the base case and the most common case.
133038 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
133039 ** nToken will be the number of tokens in the string.
133040 */
133041 struct Fts3PhraseToken {
133042   char *z;                        /* Text of the token */
133043   int n;                          /* Number of bytes in buffer z */
133044   int isPrefix;                   /* True if token ends with a "*" character */
133045   int bFirst;                     /* True if token must appear at position 0 */
133046 
133047   /* Variables above this point are populated when the expression is
133048   ** parsed (by code in fts3_expr.c). Below this point the variables are
133049   ** used when evaluating the expression. */
133050   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
133051   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
133052 };
133053 
133054 struct Fts3Phrase {
133055   /* Cache of doclist for this phrase. */
133056   Fts3Doclist doclist;
133057   int bIncr;                 /* True if doclist is loaded incrementally */
133058   int iDoclistToken;
133059 
133060   /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
133061   ** OR condition.  */
133062   char *pOrPoslist;
133063   i64 iOrDocid;
133064 
133065   /* Variables below this point are populated by fts3_expr.c when parsing
133066   ** a MATCH expression. Everything above is part of the evaluation phase.
133067   */
133068   int nToken;                /* Number of tokens in the phrase */
133069   int iColumn;               /* Index of column this phrase must match */
133070   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
133071 };
133072 
133073 /*
133074 ** A tree of these objects forms the RHS of a MATCH operator.
133075 **
133076 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
133077 ** points to a malloced buffer, size nDoclist bytes, containing the results
133078 ** of this phrase query in FTS3 doclist format. As usual, the initial
133079 ** "Length" field found in doclists stored on disk is omitted from this
133080 ** buffer.
133081 **
133082 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
133083 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
133084 ** where nCol is the number of columns in the queried FTS table. The array
133085 ** is populated as follows:
133086 **
133087 **   aMI[iCol*3 + 0] = Undefined
133088 **   aMI[iCol*3 + 1] = Number of occurrences
133089 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
133090 **
133091 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
133092 ** when the expression node is.
133093 */
133094 struct Fts3Expr {
133095   int eType;                 /* One of the FTSQUERY_XXX values defined below */
133096   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
133097   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
133098   Fts3Expr *pLeft;           /* Left operand */
133099   Fts3Expr *pRight;          /* Right operand */
133100   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
133101 
133102   /* The following are used by the fts3_eval.c module. */
133103   sqlite3_int64 iDocid;      /* Current docid */
133104   u8 bEof;                   /* True this expression is at EOF already */
133105   u8 bStart;                 /* True if iDocid is valid */
133106   u8 bDeferred;              /* True if this expression is entirely deferred */
133107 
133108   u32 *aMI;
133109 };
133110 
133111 /*
133112 ** Candidate values for Fts3Query.eType. Note that the order of the first
133113 ** four values is in order of precedence when parsing expressions. For
133114 ** example, the following:
133115 **
133116 **   "a OR b AND c NOT d NEAR e"
133117 **
133118 ** is equivalent to:
133119 **
133120 **   "a OR (b AND (c NOT (d NEAR e)))"
133121 */
133122 #define FTSQUERY_NEAR   1
133123 #define FTSQUERY_NOT    2
133124 #define FTSQUERY_AND    3
133125 #define FTSQUERY_OR     4
133126 #define FTSQUERY_PHRASE 5
133127 
133128 
133129 /* fts3_write.c */
133130 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
133131 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
133132 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
133133 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
133134 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
133135   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
133136 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
133137   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
133138 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
133139 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
133140 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
133141 
133142 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
133143 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
133144 
133145 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
133146 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
133147 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
133148 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
133149 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
133150 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
133151 #else
133152 # define sqlite3Fts3FreeDeferredTokens(x)
133153 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
133154 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
133155 # define sqlite3Fts3FreeDeferredDoclists(x)
133156 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
133157 #endif
133158 
133159 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
133160 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
133161 
133162 /* Special values interpreted by sqlite3SegReaderCursor() */
133163 #define FTS3_SEGCURSOR_PENDING        -1
133164 #define FTS3_SEGCURSOR_ALL            -2
133165 
133166 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
133167 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
133168 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
133169 
133170 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
133171     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
133172 
133173 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
133174 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
133175 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
133176 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
133177 #define FTS3_SEGMENT_PREFIX        0x00000008
133178 #define FTS3_SEGMENT_SCAN          0x00000010
133179 #define FTS3_SEGMENT_FIRST         0x00000020
133180 
133181 /* Type passed as 4th argument to SegmentReaderIterate() */
133182 struct Fts3SegFilter {
133183   const char *zTerm;
133184   int nTerm;
133185   int iCol;
133186   int flags;
133187 };
133188 
133189 struct Fts3MultiSegReader {
133190   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
133191   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
133192   int nSegment;                   /* Size of apSegment array */
133193   int nAdvance;                   /* How many seg-readers to advance */
133194   Fts3SegFilter *pFilter;         /* Pointer to filter object */
133195   char *aBuffer;                  /* Buffer to merge doclists in */
133196   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
133197 
133198   int iColFilter;                 /* If >=0, filter for this column */
133199   int bRestart;
133200 
133201   /* Used by fts3.c only. */
133202   int nCost;                      /* Cost of running iterator */
133203   int bLookup;                    /* True if a lookup of a single entry. */
133204 
133205   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
133206   char *zTerm;                    /* Pointer to term buffer */
133207   int nTerm;                      /* Size of zTerm in bytes */
133208   char *aDoclist;                 /* Pointer to doclist buffer */
133209   int nDoclist;                   /* Size of aDoclist[] in bytes */
133210 };
133211 
133212 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
133213 
133214 #define fts3GetVarint32(p, piVal) (                                           \
133215   (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
133216 )
133217 
133218 /* fts3.c */
133219 SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
133220 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
133221 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
133222 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
133223 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
133224 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
133225 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
133226 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
133227 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
133228 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
133229 
133230 /* fts3_tokenizer.c */
133231 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
133232 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
133233 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
133234     sqlite3_tokenizer **, char **
133235 );
133236 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
133237 
133238 /* fts3_snippet.c */
133239 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
133240 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
133241   const char *, const char *, int, int
133242 );
133243 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
133244 
133245 /* fts3_expr.c */
133246 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
133247   char **, int, int, int, const char *, int, Fts3Expr **, char **
133248 );
133249 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
133250 #ifdef SQLITE_TEST
133251 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
133252 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
133253 #endif
133254 
133255 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
133256   sqlite3_tokenizer_cursor **
133257 );
133258 
133259 /* fts3_aux.c */
133260 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
133261 
133262 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
133263 
133264 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
133265     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
133266 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
133267     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
133268 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
133269 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
133270 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
133271 
133272 /* fts3_tokenize_vtab.c */
133273 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
133274 
133275 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
133276 #ifndef SQLITE_DISABLE_FTS3_UNICODE
133277 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
133278 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
133279 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
133280 #endif
133281 
133282 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
133283 #endif /* _FTSINT_H */
133284 
133285 /************** End of fts3Int.h *********************************************/
133286 /************** Continuing where we left off in fts3.c ***********************/
133287 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
133288 
133289 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
133290 # define SQLITE_CORE 1
133291 #endif
133292 
133293 /* #include <assert.h> */
133294 /* #include <stdlib.h> */
133295 /* #include <stddef.h> */
133296 /* #include <stdio.h> */
133297 /* #include <string.h> */
133298 /* #include <stdarg.h> */
133299 
133300 #ifndef SQLITE_CORE
133301   SQLITE_EXTENSION_INIT1
133302 #endif
133303 
133304 static int fts3EvalNext(Fts3Cursor *pCsr);
133305 static int fts3EvalStart(Fts3Cursor *pCsr);
133306 static int fts3TermSegReaderCursor(
133307     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
133308 
133309 #ifndef SQLITE_AMALGAMATION
133310 # if defined(SQLITE_DEBUG)
133311 SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
133312 SQLITE_PRIVATE int sqlite3Fts3Never(int b)  { assert( !b ); return b; }
133313 # endif
133314 #endif
133315 
133316 /*
133317 ** Write a 64-bit variable-length integer to memory starting at p[0].
133318 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
133319 ** The number of bytes written is returned.
133320 */
133321 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
133322   unsigned char *q = (unsigned char *) p;
133323   sqlite_uint64 vu = v;
133324   do{
133325     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
133326     vu >>= 7;
133327   }while( vu!=0 );
133328   q[-1] &= 0x7f;  /* turn off high bit in final byte */
133329   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
133330   return (int) (q - (unsigned char *)p);
133331 }
133332 
133333 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
133334   v = (v & mask1) | ( (*ptr++) << shift );                    \
133335   if( (v & mask2)==0 ){ var = v; return ret; }
133336 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
133337   v = (*ptr++);                                               \
133338   if( (v & mask2)==0 ){ var = v; return ret; }
133339 
133340 /*
133341 ** Read a 64-bit variable-length integer from memory starting at p[0].
133342 ** Return the number of bytes read, or 0 on error.
133343 ** The value is stored in *v.
133344 */
133345 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
133346   const char *pStart = p;
133347   u32 a;
133348   u64 b;
133349   int shift;
133350 
133351   GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
133352   GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
133353   GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
133354   GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
133355   b = (a & 0x0FFFFFFF );
133356 
133357   for(shift=28; shift<=63; shift+=7){
133358     u64 c = *p++;
133359     b += (c&0x7F) << shift;
133360     if( (c & 0x80)==0 ) break;
133361   }
133362   *v = b;
133363   return (int)(p - pStart);
133364 }
133365 
133366 /*
133367 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
133368 ** 32-bit integer before it is returned.
133369 */
133370 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
133371   u32 a;
133372 
133373 #ifndef fts3GetVarint32
133374   GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
133375 #else
133376   a = (*p++);
133377   assert( a & 0x80 );
133378 #endif
133379 
133380   GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
133381   GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
133382   GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
133383   a = (a & 0x0FFFFFFF );
133384   *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
133385   return 5;
133386 }
133387 
133388 /*
133389 ** Return the number of bytes required to encode v as a varint
133390 */
133391 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
133392   int i = 0;
133393   do{
133394     i++;
133395     v >>= 7;
133396   }while( v!=0 );
133397   return i;
133398 }
133399 
133400 /*
133401 ** Convert an SQL-style quoted string into a normal string by removing
133402 ** the quote characters.  The conversion is done in-place.  If the
133403 ** input does not begin with a quote character, then this routine
133404 ** is a no-op.
133405 **
133406 ** Examples:
133407 **
133408 **     "abc"   becomes   abc
133409 **     'xyz'   becomes   xyz
133410 **     [pqr]   becomes   pqr
133411 **     `mno`   becomes   mno
133412 **
133413 */
133414 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
133415   char quote;                     /* Quote character (if any ) */
133416 
133417   quote = z[0];
133418   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
133419     int iIn = 1;                  /* Index of next byte to read from input */
133420     int iOut = 0;                 /* Index of next byte to write to output */
133421 
133422     /* If the first byte was a '[', then the close-quote character is a ']' */
133423     if( quote=='[' ) quote = ']';
133424 
133425     while( z[iIn] ){
133426       if( z[iIn]==quote ){
133427         if( z[iIn+1]!=quote ) break;
133428         z[iOut++] = quote;
133429         iIn += 2;
133430       }else{
133431         z[iOut++] = z[iIn++];
133432       }
133433     }
133434     z[iOut] = '\0';
133435   }
133436 }
133437 
133438 /*
133439 ** Read a single varint from the doclist at *pp and advance *pp to point
133440 ** to the first byte past the end of the varint.  Add the value of the varint
133441 ** to *pVal.
133442 */
133443 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
133444   sqlite3_int64 iVal;
133445   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
133446   *pVal += iVal;
133447 }
133448 
133449 /*
133450 ** When this function is called, *pp points to the first byte following a
133451 ** varint that is part of a doclist (or position-list, or any other list
133452 ** of varints). This function moves *pp to point to the start of that varint,
133453 ** and sets *pVal by the varint value.
133454 **
133455 ** Argument pStart points to the first byte of the doclist that the
133456 ** varint is part of.
133457 */
133458 static void fts3GetReverseVarint(
133459   char **pp,
133460   char *pStart,
133461   sqlite3_int64 *pVal
133462 ){
133463   sqlite3_int64 iVal;
133464   char *p;
133465 
133466   /* Pointer p now points at the first byte past the varint we are
133467   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
133468   ** clear on character p[-1]. */
133469   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
133470   p++;
133471   *pp = p;
133472 
133473   sqlite3Fts3GetVarint(p, &iVal);
133474   *pVal = iVal;
133475 }
133476 
133477 /*
133478 ** The xDisconnect() virtual table method.
133479 */
133480 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
133481   Fts3Table *p = (Fts3Table *)pVtab;
133482   int i;
133483 
133484   assert( p->nPendingData==0 );
133485   assert( p->pSegments==0 );
133486 
133487   /* Free any prepared statements held */
133488   for(i=0; i<SizeofArray(p->aStmt); i++){
133489     sqlite3_finalize(p->aStmt[i]);
133490   }
133491   sqlite3_free(p->zSegmentsTbl);
133492   sqlite3_free(p->zReadExprlist);
133493   sqlite3_free(p->zWriteExprlist);
133494   sqlite3_free(p->zContentTbl);
133495   sqlite3_free(p->zLanguageid);
133496 
133497   /* Invoke the tokenizer destructor to free the tokenizer. */
133498   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
133499 
133500   sqlite3_free(p);
133501   return SQLITE_OK;
133502 }
133503 
133504 /*
133505 ** Write an error message into *pzErr
133506 */
133507 SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
133508   va_list ap;
133509   sqlite3_free(*pzErr);
133510   va_start(ap, zFormat);
133511   *pzErr = sqlite3_vmprintf(zFormat, ap);
133512   va_end(ap);
133513 }
133514 
133515 /*
133516 ** Construct one or more SQL statements from the format string given
133517 ** and then evaluate those statements. The success code is written
133518 ** into *pRc.
133519 **
133520 ** If *pRc is initially non-zero then this routine is a no-op.
133521 */
133522 static void fts3DbExec(
133523   int *pRc,              /* Success code */
133524   sqlite3 *db,           /* Database in which to run SQL */
133525   const char *zFormat,   /* Format string for SQL */
133526   ...                    /* Arguments to the format string */
133527 ){
133528   va_list ap;
133529   char *zSql;
133530   if( *pRc ) return;
133531   va_start(ap, zFormat);
133532   zSql = sqlite3_vmprintf(zFormat, ap);
133533   va_end(ap);
133534   if( zSql==0 ){
133535     *pRc = SQLITE_NOMEM;
133536   }else{
133537     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
133538     sqlite3_free(zSql);
133539   }
133540 }
133541 
133542 /*
133543 ** The xDestroy() virtual table method.
133544 */
133545 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
133546   Fts3Table *p = (Fts3Table *)pVtab;
133547   int rc = SQLITE_OK;              /* Return code */
133548   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
133549   sqlite3 *db = p->db;             /* Database handle */
133550 
133551   /* Drop the shadow tables */
133552   if( p->zContentTbl==0 ){
133553     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
133554   }
133555   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
133556   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
133557   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
133558   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
133559 
133560   /* If everything has worked, invoke fts3DisconnectMethod() to free the
133561   ** memory associated with the Fts3Table structure and return SQLITE_OK.
133562   ** Otherwise, return an SQLite error code.
133563   */
133564   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
133565 }
133566 
133567 
133568 /*
133569 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
133570 ** passed as the first argument. This is done as part of the xConnect()
133571 ** and xCreate() methods.
133572 **
133573 ** If *pRc is non-zero when this function is called, it is a no-op.
133574 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
133575 ** before returning.
133576 */
133577 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
133578   if( *pRc==SQLITE_OK ){
133579     int i;                        /* Iterator variable */
133580     int rc;                       /* Return code */
133581     char *zSql;                   /* SQL statement passed to declare_vtab() */
133582     char *zCols;                  /* List of user defined columns */
133583     const char *zLanguageid;
133584 
133585     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
133586     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
133587 
133588     /* Create a list of user columns for the virtual table */
133589     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
133590     for(i=1; zCols && i<p->nColumn; i++){
133591       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
133592     }
133593 
133594     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
133595     zSql = sqlite3_mprintf(
133596         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
133597         zCols, p->zName, zLanguageid
133598     );
133599     if( !zCols || !zSql ){
133600       rc = SQLITE_NOMEM;
133601     }else{
133602       rc = sqlite3_declare_vtab(p->db, zSql);
133603     }
133604 
133605     sqlite3_free(zSql);
133606     sqlite3_free(zCols);
133607     *pRc = rc;
133608   }
133609 }
133610 
133611 /*
133612 ** Create the %_stat table if it does not already exist.
133613 */
133614 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
133615   fts3DbExec(pRc, p->db,
133616       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
133617           "(id INTEGER PRIMARY KEY, value BLOB);",
133618       p->zDb, p->zName
133619   );
133620   if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
133621 }
133622 
133623 /*
133624 ** Create the backing store tables (%_content, %_segments and %_segdir)
133625 ** required by the FTS3 table passed as the only argument. This is done
133626 ** as part of the vtab xCreate() method.
133627 **
133628 ** If the p->bHasDocsize boolean is true (indicating that this is an
133629 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
133630 ** %_stat tables required by FTS4.
133631 */
133632 static int fts3CreateTables(Fts3Table *p){
133633   int rc = SQLITE_OK;             /* Return code */
133634   int i;                          /* Iterator variable */
133635   sqlite3 *db = p->db;            /* The database connection */
133636 
133637   if( p->zContentTbl==0 ){
133638     const char *zLanguageid = p->zLanguageid;
133639     char *zContentCols;           /* Columns of %_content table */
133640 
133641     /* Create a list of user columns for the content table */
133642     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
133643     for(i=0; zContentCols && i<p->nColumn; i++){
133644       char *z = p->azColumn[i];
133645       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
133646     }
133647     if( zLanguageid && zContentCols ){
133648       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
133649     }
133650     if( zContentCols==0 ) rc = SQLITE_NOMEM;
133651 
133652     /* Create the content table */
133653     fts3DbExec(&rc, db,
133654        "CREATE TABLE %Q.'%q_content'(%s)",
133655        p->zDb, p->zName, zContentCols
133656     );
133657     sqlite3_free(zContentCols);
133658   }
133659 
133660   /* Create other tables */
133661   fts3DbExec(&rc, db,
133662       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
133663       p->zDb, p->zName
133664   );
133665   fts3DbExec(&rc, db,
133666       "CREATE TABLE %Q.'%q_segdir'("
133667         "level INTEGER,"
133668         "idx INTEGER,"
133669         "start_block INTEGER,"
133670         "leaves_end_block INTEGER,"
133671         "end_block INTEGER,"
133672         "root BLOB,"
133673         "PRIMARY KEY(level, idx)"
133674       ");",
133675       p->zDb, p->zName
133676   );
133677   if( p->bHasDocsize ){
133678     fts3DbExec(&rc, db,
133679         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
133680         p->zDb, p->zName
133681     );
133682   }
133683   assert( p->bHasStat==p->bFts4 );
133684   if( p->bHasStat ){
133685     sqlite3Fts3CreateStatTable(&rc, p);
133686   }
133687   return rc;
133688 }
133689 
133690 /*
133691 ** Store the current database page-size in bytes in p->nPgsz.
133692 **
133693 ** If *pRc is non-zero when this function is called, it is a no-op.
133694 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
133695 ** before returning.
133696 */
133697 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
133698   if( *pRc==SQLITE_OK ){
133699     int rc;                       /* Return code */
133700     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
133701     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
133702 
133703     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
133704     if( !zSql ){
133705       rc = SQLITE_NOMEM;
133706     }else{
133707       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
133708       if( rc==SQLITE_OK ){
133709         sqlite3_step(pStmt);
133710         p->nPgsz = sqlite3_column_int(pStmt, 0);
133711         rc = sqlite3_finalize(pStmt);
133712       }else if( rc==SQLITE_AUTH ){
133713         p->nPgsz = 1024;
133714         rc = SQLITE_OK;
133715       }
133716     }
133717     assert( p->nPgsz>0 || rc!=SQLITE_OK );
133718     sqlite3_free(zSql);
133719     *pRc = rc;
133720   }
133721 }
133722 
133723 /*
133724 ** "Special" FTS4 arguments are column specifications of the following form:
133725 **
133726 **   <key> = <value>
133727 **
133728 ** There may not be whitespace surrounding the "=" character. The <value>
133729 ** term may be quoted, but the <key> may not.
133730 */
133731 static int fts3IsSpecialColumn(
133732   const char *z,
133733   int *pnKey,
133734   char **pzValue
133735 ){
133736   char *zValue;
133737   const char *zCsr = z;
133738 
133739   while( *zCsr!='=' ){
133740     if( *zCsr=='\0' ) return 0;
133741     zCsr++;
133742   }
133743 
133744   *pnKey = (int)(zCsr-z);
133745   zValue = sqlite3_mprintf("%s", &zCsr[1]);
133746   if( zValue ){
133747     sqlite3Fts3Dequote(zValue);
133748   }
133749   *pzValue = zValue;
133750   return 1;
133751 }
133752 
133753 /*
133754 ** Append the output of a printf() style formatting to an existing string.
133755 */
133756 static void fts3Appendf(
133757   int *pRc,                       /* IN/OUT: Error code */
133758   char **pz,                      /* IN/OUT: Pointer to string buffer */
133759   const char *zFormat,            /* Printf format string to append */
133760   ...                             /* Arguments for printf format string */
133761 ){
133762   if( *pRc==SQLITE_OK ){
133763     va_list ap;
133764     char *z;
133765     va_start(ap, zFormat);
133766     z = sqlite3_vmprintf(zFormat, ap);
133767     va_end(ap);
133768     if( z && *pz ){
133769       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
133770       sqlite3_free(z);
133771       z = z2;
133772     }
133773     if( z==0 ) *pRc = SQLITE_NOMEM;
133774     sqlite3_free(*pz);
133775     *pz = z;
133776   }
133777 }
133778 
133779 /*
133780 ** Return a copy of input string zInput enclosed in double-quotes (") and
133781 ** with all double quote characters escaped. For example:
133782 **
133783 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
133784 **
133785 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
133786 ** is the callers responsibility to call sqlite3_free() to release this
133787 ** memory.
133788 */
133789 static char *fts3QuoteId(char const *zInput){
133790   int nRet;
133791   char *zRet;
133792   nRet = 2 + (int)strlen(zInput)*2 + 1;
133793   zRet = sqlite3_malloc(nRet);
133794   if( zRet ){
133795     int i;
133796     char *z = zRet;
133797     *(z++) = '"';
133798     for(i=0; zInput[i]; i++){
133799       if( zInput[i]=='"' ) *(z++) = '"';
133800       *(z++) = zInput[i];
133801     }
133802     *(z++) = '"';
133803     *(z++) = '\0';
133804   }
133805   return zRet;
133806 }
133807 
133808 /*
133809 ** Return a list of comma separated SQL expressions and a FROM clause that
133810 ** could be used in a SELECT statement such as the following:
133811 **
133812 **     SELECT <list of expressions> FROM %_content AS x ...
133813 **
133814 ** to return the docid, followed by each column of text data in order
133815 ** from left to write. If parameter zFunc is not NULL, then instead of
133816 ** being returned directly each column of text data is passed to an SQL
133817 ** function named zFunc first. For example, if zFunc is "unzip" and the
133818 ** table has the three user-defined columns "a", "b", and "c", the following
133819 ** string is returned:
133820 **
133821 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
133822 **
133823 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
133824 ** is the responsibility of the caller to eventually free it.
133825 **
133826 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
133827 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
133828 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
133829 ** no error occurs, *pRc is left unmodified.
133830 */
133831 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
133832   char *zRet = 0;
133833   char *zFree = 0;
133834   char *zFunction;
133835   int i;
133836 
133837   if( p->zContentTbl==0 ){
133838     if( !zFunc ){
133839       zFunction = "";
133840     }else{
133841       zFree = zFunction = fts3QuoteId(zFunc);
133842     }
133843     fts3Appendf(pRc, &zRet, "docid");
133844     for(i=0; i<p->nColumn; i++){
133845       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
133846     }
133847     if( p->zLanguageid ){
133848       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
133849     }
133850     sqlite3_free(zFree);
133851   }else{
133852     fts3Appendf(pRc, &zRet, "rowid");
133853     for(i=0; i<p->nColumn; i++){
133854       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
133855     }
133856     if( p->zLanguageid ){
133857       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
133858     }
133859   }
133860   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
133861       p->zDb,
133862       (p->zContentTbl ? p->zContentTbl : p->zName),
133863       (p->zContentTbl ? "" : "_content")
133864   );
133865   return zRet;
133866 }
133867 
133868 /*
133869 ** Return a list of N comma separated question marks, where N is the number
133870 ** of columns in the %_content table (one for the docid plus one for each
133871 ** user-defined text column).
133872 **
133873 ** If argument zFunc is not NULL, then all but the first question mark
133874 ** is preceded by zFunc and an open bracket, and followed by a closed
133875 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
133876 ** user-defined text columns, the following string is returned:
133877 **
133878 **     "?, zip(?), zip(?), zip(?)"
133879 **
133880 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
133881 ** is the responsibility of the caller to eventually free it.
133882 **
133883 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
133884 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
133885 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
133886 ** no error occurs, *pRc is left unmodified.
133887 */
133888 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
133889   char *zRet = 0;
133890   char *zFree = 0;
133891   char *zFunction;
133892   int i;
133893 
133894   if( !zFunc ){
133895     zFunction = "";
133896   }else{
133897     zFree = zFunction = fts3QuoteId(zFunc);
133898   }
133899   fts3Appendf(pRc, &zRet, "?");
133900   for(i=0; i<p->nColumn; i++){
133901     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
133902   }
133903   if( p->zLanguageid ){
133904     fts3Appendf(pRc, &zRet, ", ?");
133905   }
133906   sqlite3_free(zFree);
133907   return zRet;
133908 }
133909 
133910 /*
133911 ** This function interprets the string at (*pp) as a non-negative integer
133912 ** value. It reads the integer and sets *pnOut to the value read, then
133913 ** sets *pp to point to the byte immediately following the last byte of
133914 ** the integer value.
133915 **
133916 ** Only decimal digits ('0'..'9') may be part of an integer value.
133917 **
133918 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
133919 ** the output value undefined. Otherwise SQLITE_OK is returned.
133920 **
133921 ** This function is used when parsing the "prefix=" FTS4 parameter.
133922 */
133923 static int fts3GobbleInt(const char **pp, int *pnOut){
133924   const int MAX_NPREFIX = 10000000;
133925   const char *p;                  /* Iterator pointer */
133926   int nInt = 0;                   /* Output value */
133927 
133928   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
133929     nInt = nInt * 10 + (p[0] - '0');
133930     if( nInt>MAX_NPREFIX ){
133931       nInt = 0;
133932       break;
133933     }
133934   }
133935   if( p==*pp ) return SQLITE_ERROR;
133936   *pnOut = nInt;
133937   *pp = p;
133938   return SQLITE_OK;
133939 }
133940 
133941 /*
133942 ** This function is called to allocate an array of Fts3Index structures
133943 ** representing the indexes maintained by the current FTS table. FTS tables
133944 ** always maintain the main "terms" index, but may also maintain one or
133945 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
133946 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
133947 **
133948 ** Argument zParam is passed the value of the "prefix=" option if one was
133949 ** specified, or NULL otherwise.
133950 **
133951 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
133952 ** the allocated array. *pnIndex is set to the number of elements in the
133953 ** array. If an error does occur, an SQLite error code is returned.
133954 **
133955 ** Regardless of whether or not an error is returned, it is the responsibility
133956 ** of the caller to call sqlite3_free() on the output array to free it.
133957 */
133958 static int fts3PrefixParameter(
133959   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
133960   int *pnIndex,                   /* OUT: size of *apIndex[] array */
133961   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
133962 ){
133963   struct Fts3Index *aIndex;       /* Allocated array */
133964   int nIndex = 1;                 /* Number of entries in array */
133965 
133966   if( zParam && zParam[0] ){
133967     const char *p;
133968     nIndex++;
133969     for(p=zParam; *p; p++){
133970       if( *p==',' ) nIndex++;
133971     }
133972   }
133973 
133974   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
133975   *apIndex = aIndex;
133976   if( !aIndex ){
133977     return SQLITE_NOMEM;
133978   }
133979 
133980   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
133981   if( zParam ){
133982     const char *p = zParam;
133983     int i;
133984     for(i=1; i<nIndex; i++){
133985       int nPrefix = 0;
133986       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
133987       assert( nPrefix>=0 );
133988       if( nPrefix==0 ){
133989         nIndex--;
133990         i--;
133991       }else{
133992         aIndex[i].nPrefix = nPrefix;
133993       }
133994       p++;
133995     }
133996   }
133997 
133998   *pnIndex = nIndex;
133999   return SQLITE_OK;
134000 }
134001 
134002 /*
134003 ** This function is called when initializing an FTS4 table that uses the
134004 ** content=xxx option. It determines the number of and names of the columns
134005 ** of the new FTS4 table.
134006 **
134007 ** The third argument passed to this function is the value passed to the
134008 ** config=xxx option (i.e. "xxx"). This function queries the database for
134009 ** a table of that name. If found, the output variables are populated
134010 ** as follows:
134011 **
134012 **   *pnCol:   Set to the number of columns table xxx has,
134013 **
134014 **   *pnStr:   Set to the total amount of space required to store a copy
134015 **             of each columns name, including the nul-terminator.
134016 **
134017 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
134018 **             the name of the corresponding column in table xxx. The array
134019 **             and its contents are allocated using a single allocation. It
134020 **             is the responsibility of the caller to free this allocation
134021 **             by eventually passing the *pazCol value to sqlite3_free().
134022 **
134023 ** If the table cannot be found, an error code is returned and the output
134024 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
134025 ** returned (and the output variables are undefined).
134026 */
134027 static int fts3ContentColumns(
134028   sqlite3 *db,                    /* Database handle */
134029   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
134030   const char *zTbl,               /* Name of content table */
134031   const char ***pazCol,           /* OUT: Malloc'd array of column names */
134032   int *pnCol,                     /* OUT: Size of array *pazCol */
134033   int *pnStr,                     /* OUT: Bytes of string content */
134034   char **pzErr                    /* OUT: error message */
134035 ){
134036   int rc = SQLITE_OK;             /* Return code */
134037   char *zSql;                     /* "SELECT *" statement on zTbl */
134038   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
134039 
134040   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
134041   if( !zSql ){
134042     rc = SQLITE_NOMEM;
134043   }else{
134044     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
134045     if( rc!=SQLITE_OK ){
134046       sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
134047     }
134048   }
134049   sqlite3_free(zSql);
134050 
134051   if( rc==SQLITE_OK ){
134052     const char **azCol;           /* Output array */
134053     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
134054     int nCol;                     /* Number of table columns */
134055     int i;                        /* Used to iterate through columns */
134056 
134057     /* Loop through the returned columns. Set nStr to the number of bytes of
134058     ** space required to store a copy of each column name, including the
134059     ** nul-terminator byte.  */
134060     nCol = sqlite3_column_count(pStmt);
134061     for(i=0; i<nCol; i++){
134062       const char *zCol = sqlite3_column_name(pStmt, i);
134063       nStr += (int)strlen(zCol) + 1;
134064     }
134065 
134066     /* Allocate and populate the array to return. */
134067     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
134068     if( azCol==0 ){
134069       rc = SQLITE_NOMEM;
134070     }else{
134071       char *p = (char *)&azCol[nCol];
134072       for(i=0; i<nCol; i++){
134073         const char *zCol = sqlite3_column_name(pStmt, i);
134074         int n = (int)strlen(zCol)+1;
134075         memcpy(p, zCol, n);
134076         azCol[i] = p;
134077         p += n;
134078       }
134079     }
134080     sqlite3_finalize(pStmt);
134081 
134082     /* Set the output variables. */
134083     *pnCol = nCol;
134084     *pnStr = nStr;
134085     *pazCol = azCol;
134086   }
134087 
134088   return rc;
134089 }
134090 
134091 /*
134092 ** This function is the implementation of both the xConnect and xCreate
134093 ** methods of the FTS3 virtual table.
134094 **
134095 ** The argv[] array contains the following:
134096 **
134097 **   argv[0]   -> module name  ("fts3" or "fts4")
134098 **   argv[1]   -> database name
134099 **   argv[2]   -> table name
134100 **   argv[...] -> "column name" and other module argument fields.
134101 */
134102 static int fts3InitVtab(
134103   int isCreate,                   /* True for xCreate, false for xConnect */
134104   sqlite3 *db,                    /* The SQLite database connection */
134105   void *pAux,                     /* Hash table containing tokenizers */
134106   int argc,                       /* Number of elements in argv array */
134107   const char * const *argv,       /* xCreate/xConnect argument array */
134108   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
134109   char **pzErr                    /* Write any error message here */
134110 ){
134111   Fts3Hash *pHash = (Fts3Hash *)pAux;
134112   Fts3Table *p = 0;               /* Pointer to allocated vtab */
134113   int rc = SQLITE_OK;             /* Return code */
134114   int i;                          /* Iterator variable */
134115   int nByte;                      /* Size of allocation used for *p */
134116   int iCol;                       /* Column index */
134117   int nString = 0;                /* Bytes required to hold all column names */
134118   int nCol = 0;                   /* Number of columns in the FTS table */
134119   char *zCsr;                     /* Space for holding column names */
134120   int nDb;                        /* Bytes required to hold database name */
134121   int nName;                      /* Bytes required to hold table name */
134122   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
134123   const char **aCol;              /* Array of column names */
134124   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
134125 
134126   int nIndex = 0;                 /* Size of aIndex[] array */
134127   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
134128 
134129   /* The results of parsing supported FTS4 key=value options: */
134130   int bNoDocsize = 0;             /* True to omit %_docsize table */
134131   int bDescIdx = 0;               /* True to store descending indexes */
134132   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
134133   char *zCompress = 0;            /* compress=? parameter (or NULL) */
134134   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
134135   char *zContent = 0;             /* content=? parameter (or NULL) */
134136   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
134137   char **azNotindexed = 0;        /* The set of notindexed= columns */
134138   int nNotindexed = 0;            /* Size of azNotindexed[] array */
134139 
134140   assert( strlen(argv[0])==4 );
134141   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
134142        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
134143   );
134144 
134145   nDb = (int)strlen(argv[1]) + 1;
134146   nName = (int)strlen(argv[2]) + 1;
134147 
134148   nByte = sizeof(const char *) * (argc-2);
134149   aCol = (const char **)sqlite3_malloc(nByte);
134150   if( aCol ){
134151     memset((void*)aCol, 0, nByte);
134152     azNotindexed = (char **)sqlite3_malloc(nByte);
134153   }
134154   if( azNotindexed ){
134155     memset(azNotindexed, 0, nByte);
134156   }
134157   if( !aCol || !azNotindexed ){
134158     rc = SQLITE_NOMEM;
134159     goto fts3_init_out;
134160   }
134161 
134162   /* Loop through all of the arguments passed by the user to the FTS3/4
134163   ** module (i.e. all the column names and special arguments). This loop
134164   ** does the following:
134165   **
134166   **   + Figures out the number of columns the FTSX table will have, and
134167   **     the number of bytes of space that must be allocated to store copies
134168   **     of the column names.
134169   **
134170   **   + If there is a tokenizer specification included in the arguments,
134171   **     initializes the tokenizer pTokenizer.
134172   */
134173   for(i=3; rc==SQLITE_OK && i<argc; i++){
134174     char const *z = argv[i];
134175     int nKey;
134176     char *zVal;
134177 
134178     /* Check if this is a tokenizer specification */
134179     if( !pTokenizer
134180      && strlen(z)>8
134181      && 0==sqlite3_strnicmp(z, "tokenize", 8)
134182      && 0==sqlite3Fts3IsIdChar(z[8])
134183     ){
134184       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
134185     }
134186 
134187     /* Check if it is an FTS4 special argument. */
134188     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
134189       struct Fts4Option {
134190         const char *zOpt;
134191         int nOpt;
134192       } aFts4Opt[] = {
134193         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
134194         { "prefix",      6 },     /* 1 -> PREFIX */
134195         { "compress",    8 },     /* 2 -> COMPRESS */
134196         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
134197         { "order",       5 },     /* 4 -> ORDER */
134198         { "content",     7 },     /* 5 -> CONTENT */
134199         { "languageid", 10 },     /* 6 -> LANGUAGEID */
134200         { "notindexed", 10 }      /* 7 -> NOTINDEXED */
134201       };
134202 
134203       int iOpt;
134204       if( !zVal ){
134205         rc = SQLITE_NOMEM;
134206       }else{
134207         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
134208           struct Fts4Option *pOp = &aFts4Opt[iOpt];
134209           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
134210             break;
134211           }
134212         }
134213         if( iOpt==SizeofArray(aFts4Opt) ){
134214           sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
134215           rc = SQLITE_ERROR;
134216         }else{
134217           switch( iOpt ){
134218             case 0:               /* MATCHINFO */
134219               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
134220                 sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
134221                 rc = SQLITE_ERROR;
134222               }
134223               bNoDocsize = 1;
134224               break;
134225 
134226             case 1:               /* PREFIX */
134227               sqlite3_free(zPrefix);
134228               zPrefix = zVal;
134229               zVal = 0;
134230               break;
134231 
134232             case 2:               /* COMPRESS */
134233               sqlite3_free(zCompress);
134234               zCompress = zVal;
134235               zVal = 0;
134236               break;
134237 
134238             case 3:               /* UNCOMPRESS */
134239               sqlite3_free(zUncompress);
134240               zUncompress = zVal;
134241               zVal = 0;
134242               break;
134243 
134244             case 4:               /* ORDER */
134245               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
134246                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
134247               ){
134248                 sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
134249                 rc = SQLITE_ERROR;
134250               }
134251               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
134252               break;
134253 
134254             case 5:              /* CONTENT */
134255               sqlite3_free(zContent);
134256               zContent = zVal;
134257               zVal = 0;
134258               break;
134259 
134260             case 6:              /* LANGUAGEID */
134261               assert( iOpt==6 );
134262               sqlite3_free(zLanguageid);
134263               zLanguageid = zVal;
134264               zVal = 0;
134265               break;
134266 
134267             case 7:              /* NOTINDEXED */
134268               azNotindexed[nNotindexed++] = zVal;
134269               zVal = 0;
134270               break;
134271           }
134272         }
134273         sqlite3_free(zVal);
134274       }
134275     }
134276 
134277     /* Otherwise, the argument is a column name. */
134278     else {
134279       nString += (int)(strlen(z) + 1);
134280       aCol[nCol++] = z;
134281     }
134282   }
134283 
134284   /* If a content=xxx option was specified, the following:
134285   **
134286   **   1. Ignore any compress= and uncompress= options.
134287   **
134288   **   2. If no column names were specified as part of the CREATE VIRTUAL
134289   **      TABLE statement, use all columns from the content table.
134290   */
134291   if( rc==SQLITE_OK && zContent ){
134292     sqlite3_free(zCompress);
134293     sqlite3_free(zUncompress);
134294     zCompress = 0;
134295     zUncompress = 0;
134296     if( nCol==0 ){
134297       sqlite3_free((void*)aCol);
134298       aCol = 0;
134299       rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
134300 
134301       /* If a languageid= option was specified, remove the language id
134302       ** column from the aCol[] array. */
134303       if( rc==SQLITE_OK && zLanguageid ){
134304         int j;
134305         for(j=0; j<nCol; j++){
134306           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
134307             int k;
134308             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
134309             nCol--;
134310             break;
134311           }
134312         }
134313       }
134314     }
134315   }
134316   if( rc!=SQLITE_OK ) goto fts3_init_out;
134317 
134318   if( nCol==0 ){
134319     assert( nString==0 );
134320     aCol[0] = "content";
134321     nString = 8;
134322     nCol = 1;
134323   }
134324 
134325   if( pTokenizer==0 ){
134326     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
134327     if( rc!=SQLITE_OK ) goto fts3_init_out;
134328   }
134329   assert( pTokenizer );
134330 
134331   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
134332   if( rc==SQLITE_ERROR ){
134333     assert( zPrefix );
134334     sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
134335   }
134336   if( rc!=SQLITE_OK ) goto fts3_init_out;
134337 
134338   /* Allocate and populate the Fts3Table structure. */
134339   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
134340           nCol * sizeof(char *) +              /* azColumn */
134341           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
134342           nCol * sizeof(u8) +                  /* abNotindexed */
134343           nName +                              /* zName */
134344           nDb +                                /* zDb */
134345           nString;                             /* Space for azColumn strings */
134346   p = (Fts3Table*)sqlite3_malloc(nByte);
134347   if( p==0 ){
134348     rc = SQLITE_NOMEM;
134349     goto fts3_init_out;
134350   }
134351   memset(p, 0, nByte);
134352   p->db = db;
134353   p->nColumn = nCol;
134354   p->nPendingData = 0;
134355   p->azColumn = (char **)&p[1];
134356   p->pTokenizer = pTokenizer;
134357   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
134358   p->bHasDocsize = (isFts4 && bNoDocsize==0);
134359   p->bHasStat = isFts4;
134360   p->bFts4 = isFts4;
134361   p->bDescIdx = bDescIdx;
134362   p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
134363   p->zContentTbl = zContent;
134364   p->zLanguageid = zLanguageid;
134365   zContent = 0;
134366   zLanguageid = 0;
134367   TESTONLY( p->inTransaction = -1 );
134368   TESTONLY( p->mxSavepoint = -1 );
134369 
134370   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
134371   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
134372   p->nIndex = nIndex;
134373   for(i=0; i<nIndex; i++){
134374     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
134375   }
134376   p->abNotindexed = (u8 *)&p->aIndex[nIndex];
134377 
134378   /* Fill in the zName and zDb fields of the vtab structure. */
134379   zCsr = (char *)&p->abNotindexed[nCol];
134380   p->zName = zCsr;
134381   memcpy(zCsr, argv[2], nName);
134382   zCsr += nName;
134383   p->zDb = zCsr;
134384   memcpy(zCsr, argv[1], nDb);
134385   zCsr += nDb;
134386 
134387   /* Fill in the azColumn array */
134388   for(iCol=0; iCol<nCol; iCol++){
134389     char *z;
134390     int n = 0;
134391     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
134392     memcpy(zCsr, z, n);
134393     zCsr[n] = '\0';
134394     sqlite3Fts3Dequote(zCsr);
134395     p->azColumn[iCol] = zCsr;
134396     zCsr += n+1;
134397     assert( zCsr <= &((char *)p)[nByte] );
134398   }
134399 
134400   /* Fill in the abNotindexed array */
134401   for(iCol=0; iCol<nCol; iCol++){
134402     int n = (int)strlen(p->azColumn[iCol]);
134403     for(i=0; i<nNotindexed; i++){
134404       char *zNot = azNotindexed[i];
134405       if( zNot && n==(int)strlen(zNot)
134406        && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
134407       ){
134408         p->abNotindexed[iCol] = 1;
134409         sqlite3_free(zNot);
134410         azNotindexed[i] = 0;
134411       }
134412     }
134413   }
134414   for(i=0; i<nNotindexed; i++){
134415     if( azNotindexed[i] ){
134416       sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
134417       rc = SQLITE_ERROR;
134418     }
134419   }
134420 
134421   if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
134422     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
134423     rc = SQLITE_ERROR;
134424     sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
134425   }
134426   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
134427   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
134428   if( rc!=SQLITE_OK ) goto fts3_init_out;
134429 
134430   /* If this is an xCreate call, create the underlying tables in the
134431   ** database. TODO: For xConnect(), it could verify that said tables exist.
134432   */
134433   if( isCreate ){
134434     rc = fts3CreateTables(p);
134435   }
134436 
134437   /* Check to see if a legacy fts3 table has been "upgraded" by the
134438   ** addition of a %_stat table so that it can use incremental merge.
134439   */
134440   if( !isFts4 && !isCreate ){
134441     p->bHasStat = 2;
134442   }
134443 
134444   /* Figure out the page-size for the database. This is required in order to
134445   ** estimate the cost of loading large doclists from the database.  */
134446   fts3DatabasePageSize(&rc, p);
134447   p->nNodeSize = p->nPgsz-35;
134448 
134449   /* Declare the table schema to SQLite. */
134450   fts3DeclareVtab(&rc, p);
134451 
134452 fts3_init_out:
134453   sqlite3_free(zPrefix);
134454   sqlite3_free(aIndex);
134455   sqlite3_free(zCompress);
134456   sqlite3_free(zUncompress);
134457   sqlite3_free(zContent);
134458   sqlite3_free(zLanguageid);
134459   for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
134460   sqlite3_free((void *)aCol);
134461   sqlite3_free((void *)azNotindexed);
134462   if( rc!=SQLITE_OK ){
134463     if( p ){
134464       fts3DisconnectMethod((sqlite3_vtab *)p);
134465     }else if( pTokenizer ){
134466       pTokenizer->pModule->xDestroy(pTokenizer);
134467     }
134468   }else{
134469     assert( p->pSegments==0 );
134470     *ppVTab = &p->base;
134471   }
134472   return rc;
134473 }
134474 
134475 /*
134476 ** The xConnect() and xCreate() methods for the virtual table. All the
134477 ** work is done in function fts3InitVtab().
134478 */
134479 static int fts3ConnectMethod(
134480   sqlite3 *db,                    /* Database connection */
134481   void *pAux,                     /* Pointer to tokenizer hash table */
134482   int argc,                       /* Number of elements in argv array */
134483   const char * const *argv,       /* xCreate/xConnect argument array */
134484   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
134485   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
134486 ){
134487   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
134488 }
134489 static int fts3CreateMethod(
134490   sqlite3 *db,                    /* Database connection */
134491   void *pAux,                     /* Pointer to tokenizer hash table */
134492   int argc,                       /* Number of elements in argv array */
134493   const char * const *argv,       /* xCreate/xConnect argument array */
134494   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
134495   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
134496 ){
134497   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
134498 }
134499 
134500 /*
134501 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
134502 ** extension is currently being used by a version of SQLite too old to
134503 ** support estimatedRows. In that case this function is a no-op.
134504 */
134505 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
134506 #if SQLITE_VERSION_NUMBER>=3008002
134507   if( sqlite3_libversion_number()>=3008002 ){
134508     pIdxInfo->estimatedRows = nRow;
134509   }
134510 #endif
134511 }
134512 
134513 /*
134514 ** Implementation of the xBestIndex method for FTS3 tables. There
134515 ** are three possible strategies, in order of preference:
134516 **
134517 **   1. Direct lookup by rowid or docid.
134518 **   2. Full-text search using a MATCH operator on a non-docid column.
134519 **   3. Linear scan of %_content table.
134520 */
134521 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
134522   Fts3Table *p = (Fts3Table *)pVTab;
134523   int i;                          /* Iterator variable */
134524   int iCons = -1;                 /* Index of constraint to use */
134525 
134526   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
134527   int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
134528   int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
134529   int iIdx;
134530 
134531   /* By default use a full table scan. This is an expensive option,
134532   ** so search through the constraints to see if a more efficient
134533   ** strategy is possible.
134534   */
134535   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
134536   pInfo->estimatedCost = 5000000;
134537   for(i=0; i<pInfo->nConstraint; i++){
134538     int bDocid;                 /* True if this constraint is on docid */
134539     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
134540     if( pCons->usable==0 ){
134541       if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
134542         /* There exists an unusable MATCH constraint. This means that if
134543         ** the planner does elect to use the results of this call as part
134544         ** of the overall query plan the user will see an "unable to use
134545         ** function MATCH in the requested context" error. To discourage
134546         ** this, return a very high cost here.  */
134547         pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
134548         pInfo->estimatedCost = 1e50;
134549         fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
134550         return SQLITE_OK;
134551       }
134552       continue;
134553     }
134554 
134555     bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
134556 
134557     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
134558     if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
134559       pInfo->idxNum = FTS3_DOCID_SEARCH;
134560       pInfo->estimatedCost = 1.0;
134561       iCons = i;
134562     }
134563 
134564     /* A MATCH constraint. Use a full-text search.
134565     **
134566     ** If there is more than one MATCH constraint available, use the first
134567     ** one encountered. If there is both a MATCH constraint and a direct
134568     ** rowid/docid lookup, prefer the MATCH strategy. This is done even
134569     ** though the rowid/docid lookup is faster than a MATCH query, selecting
134570     ** it would lead to an "unable to use function MATCH in the requested
134571     ** context" error.
134572     */
134573     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
134574      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
134575     ){
134576       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
134577       pInfo->estimatedCost = 2.0;
134578       iCons = i;
134579     }
134580 
134581     /* Equality constraint on the langid column */
134582     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
134583      && pCons->iColumn==p->nColumn + 2
134584     ){
134585       iLangidCons = i;
134586     }
134587 
134588     if( bDocid ){
134589       switch( pCons->op ){
134590         case SQLITE_INDEX_CONSTRAINT_GE:
134591         case SQLITE_INDEX_CONSTRAINT_GT:
134592           iDocidGe = i;
134593           break;
134594 
134595         case SQLITE_INDEX_CONSTRAINT_LE:
134596         case SQLITE_INDEX_CONSTRAINT_LT:
134597           iDocidLe = i;
134598           break;
134599       }
134600     }
134601   }
134602 
134603   iIdx = 1;
134604   if( iCons>=0 ){
134605     pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
134606     pInfo->aConstraintUsage[iCons].omit = 1;
134607   }
134608   if( iLangidCons>=0 ){
134609     pInfo->idxNum |= FTS3_HAVE_LANGID;
134610     pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
134611   }
134612   if( iDocidGe>=0 ){
134613     pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
134614     pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
134615   }
134616   if( iDocidLe>=0 ){
134617     pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
134618     pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
134619   }
134620 
134621   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
134622   ** docid) order. Both ascending and descending are possible.
134623   */
134624   if( pInfo->nOrderBy==1 ){
134625     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
134626     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
134627       if( pOrder->desc ){
134628         pInfo->idxStr = "DESC";
134629       }else{
134630         pInfo->idxStr = "ASC";
134631       }
134632       pInfo->orderByConsumed = 1;
134633     }
134634   }
134635 
134636   assert( p->pSegments==0 );
134637   return SQLITE_OK;
134638 }
134639 
134640 /*
134641 ** Implementation of xOpen method.
134642 */
134643 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
134644   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
134645 
134646   UNUSED_PARAMETER(pVTab);
134647 
134648   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
134649   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
134650   ** if the allocation fails, return SQLITE_NOMEM.
134651   */
134652   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
134653   if( !pCsr ){
134654     return SQLITE_NOMEM;
134655   }
134656   memset(pCsr, 0, sizeof(Fts3Cursor));
134657   return SQLITE_OK;
134658 }
134659 
134660 /*
134661 ** Close the cursor.  For additional information see the documentation
134662 ** on the xClose method of the virtual table interface.
134663 */
134664 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
134665   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
134666   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
134667   sqlite3_finalize(pCsr->pStmt);
134668   sqlite3Fts3ExprFree(pCsr->pExpr);
134669   sqlite3Fts3FreeDeferredTokens(pCsr);
134670   sqlite3_free(pCsr->aDoclist);
134671   sqlite3_free(pCsr->aMatchinfo);
134672   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
134673   sqlite3_free(pCsr);
134674   return SQLITE_OK;
134675 }
134676 
134677 /*
134678 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
134679 ** compose and prepare an SQL statement of the form:
134680 **
134681 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
134682 **
134683 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
134684 ** it. If an error occurs, return an SQLite error code.
134685 **
134686 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
134687 */
134688 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
134689   int rc = SQLITE_OK;
134690   if( pCsr->pStmt==0 ){
134691     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
134692     char *zSql;
134693     zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
134694     if( !zSql ) return SQLITE_NOMEM;
134695     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
134696     sqlite3_free(zSql);
134697   }
134698   *ppStmt = pCsr->pStmt;
134699   return rc;
134700 }
134701 
134702 /*
134703 ** Position the pCsr->pStmt statement so that it is on the row
134704 ** of the %_content table that contains the last match.  Return
134705 ** SQLITE_OK on success.
134706 */
134707 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
134708   int rc = SQLITE_OK;
134709   if( pCsr->isRequireSeek ){
134710     sqlite3_stmt *pStmt = 0;
134711 
134712     rc = fts3CursorSeekStmt(pCsr, &pStmt);
134713     if( rc==SQLITE_OK ){
134714       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
134715       pCsr->isRequireSeek = 0;
134716       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
134717         return SQLITE_OK;
134718       }else{
134719         rc = sqlite3_reset(pCsr->pStmt);
134720         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
134721           /* If no row was found and no error has occurred, then the %_content
134722           ** table is missing a row that is present in the full-text index.
134723           ** The data structures are corrupt.  */
134724           rc = FTS_CORRUPT_VTAB;
134725           pCsr->isEof = 1;
134726         }
134727       }
134728     }
134729   }
134730 
134731   if( rc!=SQLITE_OK && pContext ){
134732     sqlite3_result_error_code(pContext, rc);
134733   }
134734   return rc;
134735 }
134736 
134737 /*
134738 ** This function is used to process a single interior node when searching
134739 ** a b-tree for a term or term prefix. The node data is passed to this
134740 ** function via the zNode/nNode parameters. The term to search for is
134741 ** passed in zTerm/nTerm.
134742 **
134743 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
134744 ** of the child node that heads the sub-tree that may contain the term.
134745 **
134746 ** If piLast is not NULL, then *piLast is set to the right-most child node
134747 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
134748 ** a prefix.
134749 **
134750 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
134751 */
134752 static int fts3ScanInteriorNode(
134753   const char *zTerm,              /* Term to select leaves for */
134754   int nTerm,                      /* Size of term zTerm in bytes */
134755   const char *zNode,              /* Buffer containing segment interior node */
134756   int nNode,                      /* Size of buffer at zNode */
134757   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
134758   sqlite3_int64 *piLast           /* OUT: Selected child node */
134759 ){
134760   int rc = SQLITE_OK;             /* Return code */
134761   const char *zCsr = zNode;       /* Cursor to iterate through node */
134762   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
134763   char *zBuffer = 0;              /* Buffer to load terms into */
134764   int nAlloc = 0;                 /* Size of allocated buffer */
134765   int isFirstTerm = 1;            /* True when processing first term on page */
134766   sqlite3_int64 iChild;           /* Block id of child node to descend to */
134767 
134768   /* Skip over the 'height' varint that occurs at the start of every
134769   ** interior node. Then load the blockid of the left-child of the b-tree
134770   ** node into variable iChild.
134771   **
134772   ** Even if the data structure on disk is corrupted, this (reading two
134773   ** varints from the buffer) does not risk an overread. If zNode is a
134774   ** root node, then the buffer comes from a SELECT statement. SQLite does
134775   ** not make this guarantee explicitly, but in practice there are always
134776   ** either more than 20 bytes of allocated space following the nNode bytes of
134777   ** contents, or two zero bytes. Or, if the node is read from the %_segments
134778   ** table, then there are always 20 bytes of zeroed padding following the
134779   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
134780   */
134781   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
134782   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
134783   if( zCsr>zEnd ){
134784     return FTS_CORRUPT_VTAB;
134785   }
134786 
134787   while( zCsr<zEnd && (piFirst || piLast) ){
134788     int cmp;                      /* memcmp() result */
134789     int nSuffix;                  /* Size of term suffix */
134790     int nPrefix = 0;              /* Size of term prefix */
134791     int nBuffer;                  /* Total term size */
134792 
134793     /* Load the next term on the node into zBuffer. Use realloc() to expand
134794     ** the size of zBuffer if required.  */
134795     if( !isFirstTerm ){
134796       zCsr += fts3GetVarint32(zCsr, &nPrefix);
134797     }
134798     isFirstTerm = 0;
134799     zCsr += fts3GetVarint32(zCsr, &nSuffix);
134800 
134801     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
134802       rc = FTS_CORRUPT_VTAB;
134803       goto finish_scan;
134804     }
134805     if( nPrefix+nSuffix>nAlloc ){
134806       char *zNew;
134807       nAlloc = (nPrefix+nSuffix) * 2;
134808       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
134809       if( !zNew ){
134810         rc = SQLITE_NOMEM;
134811         goto finish_scan;
134812       }
134813       zBuffer = zNew;
134814     }
134815     assert( zBuffer );
134816     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
134817     nBuffer = nPrefix + nSuffix;
134818     zCsr += nSuffix;
134819 
134820     /* Compare the term we are searching for with the term just loaded from
134821     ** the interior node. If the specified term is greater than or equal
134822     ** to the term from the interior node, then all terms on the sub-tree
134823     ** headed by node iChild are smaller than zTerm. No need to search
134824     ** iChild.
134825     **
134826     ** If the interior node term is larger than the specified term, then
134827     ** the tree headed by iChild may contain the specified term.
134828     */
134829     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
134830     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
134831       *piFirst = iChild;
134832       piFirst = 0;
134833     }
134834 
134835     if( piLast && cmp<0 ){
134836       *piLast = iChild;
134837       piLast = 0;
134838     }
134839 
134840     iChild++;
134841   };
134842 
134843   if( piFirst ) *piFirst = iChild;
134844   if( piLast ) *piLast = iChild;
134845 
134846  finish_scan:
134847   sqlite3_free(zBuffer);
134848   return rc;
134849 }
134850 
134851 
134852 /*
134853 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
134854 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
134855 ** contains a term. This function searches the sub-tree headed by the zNode
134856 ** node for the range of leaf nodes that may contain the specified term
134857 ** or terms for which the specified term is a prefix.
134858 **
134859 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
134860 ** left-most leaf node in the tree that may contain the specified term.
134861 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
134862 ** right-most leaf node that may contain a term for which the specified
134863 ** term is a prefix.
134864 **
134865 ** It is possible that the range of returned leaf nodes does not contain
134866 ** the specified term or any terms for which it is a prefix. However, if the
134867 ** segment does contain any such terms, they are stored within the identified
134868 ** range. Because this function only inspects interior segment nodes (and
134869 ** never loads leaf nodes into memory), it is not possible to be sure.
134870 **
134871 ** If an error occurs, an error code other than SQLITE_OK is returned.
134872 */
134873 static int fts3SelectLeaf(
134874   Fts3Table *p,                   /* Virtual table handle */
134875   const char *zTerm,              /* Term to select leaves for */
134876   int nTerm,                      /* Size of term zTerm in bytes */
134877   const char *zNode,              /* Buffer containing segment interior node */
134878   int nNode,                      /* Size of buffer at zNode */
134879   sqlite3_int64 *piLeaf,          /* Selected leaf node */
134880   sqlite3_int64 *piLeaf2          /* Selected leaf node */
134881 ){
134882   int rc = SQLITE_OK;             /* Return code */
134883   int iHeight;                    /* Height of this node in tree */
134884 
134885   assert( piLeaf || piLeaf2 );
134886 
134887   fts3GetVarint32(zNode, &iHeight);
134888   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
134889   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
134890 
134891   if( rc==SQLITE_OK && iHeight>1 ){
134892     char *zBlob = 0;              /* Blob read from %_segments table */
134893     int nBlob = 0;                /* Size of zBlob in bytes */
134894 
134895     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
134896       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
134897       if( rc==SQLITE_OK ){
134898         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
134899       }
134900       sqlite3_free(zBlob);
134901       piLeaf = 0;
134902       zBlob = 0;
134903     }
134904 
134905     if( rc==SQLITE_OK ){
134906       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
134907     }
134908     if( rc==SQLITE_OK ){
134909       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
134910     }
134911     sqlite3_free(zBlob);
134912   }
134913 
134914   return rc;
134915 }
134916 
134917 /*
134918 ** This function is used to create delta-encoded serialized lists of FTS3
134919 ** varints. Each call to this function appends a single varint to a list.
134920 */
134921 static void fts3PutDeltaVarint(
134922   char **pp,                      /* IN/OUT: Output pointer */
134923   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
134924   sqlite3_int64 iVal              /* Write this value to the list */
134925 ){
134926   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
134927   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
134928   *piPrev = iVal;
134929 }
134930 
134931 /*
134932 ** When this function is called, *ppPoslist is assumed to point to the
134933 ** start of a position-list. After it returns, *ppPoslist points to the
134934 ** first byte after the position-list.
134935 **
134936 ** A position list is list of positions (delta encoded) and columns for
134937 ** a single document record of a doclist.  So, in other words, this
134938 ** routine advances *ppPoslist so that it points to the next docid in
134939 ** the doclist, or to the first byte past the end of the doclist.
134940 **
134941 ** If pp is not NULL, then the contents of the position list are copied
134942 ** to *pp. *pp is set to point to the first byte past the last byte copied
134943 ** before this function returns.
134944 */
134945 static void fts3PoslistCopy(char **pp, char **ppPoslist){
134946   char *pEnd = *ppPoslist;
134947   char c = 0;
134948 
134949   /* The end of a position list is marked by a zero encoded as an FTS3
134950   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
134951   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
134952   ** of some other, multi-byte, value.
134953   **
134954   ** The following while-loop moves pEnd to point to the first byte that is not
134955   ** immediately preceded by a byte with the 0x80 bit set. Then increments
134956   ** pEnd once more so that it points to the byte immediately following the
134957   ** last byte in the position-list.
134958   */
134959   while( *pEnd | c ){
134960     c = *pEnd++ & 0x80;
134961     testcase( c!=0 && (*pEnd)==0 );
134962   }
134963   pEnd++;  /* Advance past the POS_END terminator byte */
134964 
134965   if( pp ){
134966     int n = (int)(pEnd - *ppPoslist);
134967     char *p = *pp;
134968     memcpy(p, *ppPoslist, n);
134969     p += n;
134970     *pp = p;
134971   }
134972   *ppPoslist = pEnd;
134973 }
134974 
134975 /*
134976 ** When this function is called, *ppPoslist is assumed to point to the
134977 ** start of a column-list. After it returns, *ppPoslist points to the
134978 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
134979 **
134980 ** A column-list is list of delta-encoded positions for a single column
134981 ** within a single document within a doclist.
134982 **
134983 ** The column-list is terminated either by a POS_COLUMN varint (1) or
134984 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
134985 ** the POS_COLUMN or POS_END that terminates the column-list.
134986 **
134987 ** If pp is not NULL, then the contents of the column-list are copied
134988 ** to *pp. *pp is set to point to the first byte past the last byte copied
134989 ** before this function returns.  The POS_COLUMN or POS_END terminator
134990 ** is not copied into *pp.
134991 */
134992 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
134993   char *pEnd = *ppPoslist;
134994   char c = 0;
134995 
134996   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
134997   ** not part of a multi-byte varint.
134998   */
134999   while( 0xFE & (*pEnd | c) ){
135000     c = *pEnd++ & 0x80;
135001     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
135002   }
135003   if( pp ){
135004     int n = (int)(pEnd - *ppPoslist);
135005     char *p = *pp;
135006     memcpy(p, *ppPoslist, n);
135007     p += n;
135008     *pp = p;
135009   }
135010   *ppPoslist = pEnd;
135011 }
135012 
135013 /*
135014 ** Value used to signify the end of an position-list. This is safe because
135015 ** it is not possible to have a document with 2^31 terms.
135016 */
135017 #define POSITION_LIST_END 0x7fffffff
135018 
135019 /*
135020 ** This function is used to help parse position-lists. When this function is
135021 ** called, *pp may point to the start of the next varint in the position-list
135022 ** being parsed, or it may point to 1 byte past the end of the position-list
135023 ** (in which case **pp will be a terminator bytes POS_END (0) or
135024 ** (1)).
135025 **
135026 ** If *pp points past the end of the current position-list, set *pi to
135027 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
135028 ** increment the current value of *pi by the value read, and set *pp to
135029 ** point to the next value before returning.
135030 **
135031 ** Before calling this routine *pi must be initialized to the value of
135032 ** the previous position, or zero if we are reading the first position
135033 ** in the position-list.  Because positions are delta-encoded, the value
135034 ** of the previous position is needed in order to compute the value of
135035 ** the next position.
135036 */
135037 static void fts3ReadNextPos(
135038   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
135039   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
135040 ){
135041   if( (**pp)&0xFE ){
135042     fts3GetDeltaVarint(pp, pi);
135043     *pi -= 2;
135044   }else{
135045     *pi = POSITION_LIST_END;
135046   }
135047 }
135048 
135049 /*
135050 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
135051 ** the value of iCol encoded as a varint to *pp.   This will start a new
135052 ** column list.
135053 **
135054 ** Set *pp to point to the byte just after the last byte written before
135055 ** returning (do not modify it if iCol==0). Return the total number of bytes
135056 ** written (0 if iCol==0).
135057 */
135058 static int fts3PutColNumber(char **pp, int iCol){
135059   int n = 0;                      /* Number of bytes written */
135060   if( iCol ){
135061     char *p = *pp;                /* Output pointer */
135062     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
135063     *p = 0x01;
135064     *pp = &p[n];
135065   }
135066   return n;
135067 }
135068 
135069 /*
135070 ** Compute the union of two position lists.  The output written
135071 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
135072 ** order and with any duplicates removed.  All pointers are
135073 ** updated appropriately.   The caller is responsible for insuring
135074 ** that there is enough space in *pp to hold the complete output.
135075 */
135076 static void fts3PoslistMerge(
135077   char **pp,                      /* Output buffer */
135078   char **pp1,                     /* Left input list */
135079   char **pp2                      /* Right input list */
135080 ){
135081   char *p = *pp;
135082   char *p1 = *pp1;
135083   char *p2 = *pp2;
135084 
135085   while( *p1 || *p2 ){
135086     int iCol1;         /* The current column index in pp1 */
135087     int iCol2;         /* The current column index in pp2 */
135088 
135089     if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
135090     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
135091     else iCol1 = 0;
135092 
135093     if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
135094     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
135095     else iCol2 = 0;
135096 
135097     if( iCol1==iCol2 ){
135098       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
135099       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
135100       sqlite3_int64 iPrev = 0;
135101       int n = fts3PutColNumber(&p, iCol1);
135102       p1 += n;
135103       p2 += n;
135104 
135105       /* At this point, both p1 and p2 point to the start of column-lists
135106       ** for the same column (the column with index iCol1 and iCol2).
135107       ** A column-list is a list of non-negative delta-encoded varints, each
135108       ** incremented by 2 before being stored. Each list is terminated by a
135109       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
135110       ** and writes the results to buffer p. p is left pointing to the byte
135111       ** after the list written. No terminator (POS_END or POS_COLUMN) is
135112       ** written to the output.
135113       */
135114       fts3GetDeltaVarint(&p1, &i1);
135115       fts3GetDeltaVarint(&p2, &i2);
135116       do {
135117         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
135118         iPrev -= 2;
135119         if( i1==i2 ){
135120           fts3ReadNextPos(&p1, &i1);
135121           fts3ReadNextPos(&p2, &i2);
135122         }else if( i1<i2 ){
135123           fts3ReadNextPos(&p1, &i1);
135124         }else{
135125           fts3ReadNextPos(&p2, &i2);
135126         }
135127       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
135128     }else if( iCol1<iCol2 ){
135129       p1 += fts3PutColNumber(&p, iCol1);
135130       fts3ColumnlistCopy(&p, &p1);
135131     }else{
135132       p2 += fts3PutColNumber(&p, iCol2);
135133       fts3ColumnlistCopy(&p, &p2);
135134     }
135135   }
135136 
135137   *p++ = POS_END;
135138   *pp = p;
135139   *pp1 = p1 + 1;
135140   *pp2 = p2 + 1;
135141 }
135142 
135143 /*
135144 ** This function is used to merge two position lists into one. When it is
135145 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
135146 ** the part of a doclist that follows each document id. For example, if a row
135147 ** contains:
135148 **
135149 **     'a b c'|'x y z'|'a b b a'
135150 **
135151 ** Then the position list for this row for token 'b' would consist of:
135152 **
135153 **     0x02 0x01 0x02 0x03 0x03 0x00
135154 **
135155 ** When this function returns, both *pp1 and *pp2 are left pointing to the
135156 ** byte following the 0x00 terminator of their respective position lists.
135157 **
135158 ** If isSaveLeft is 0, an entry is added to the output position list for
135159 ** each position in *pp2 for which there exists one or more positions in
135160 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
135161 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
135162 ** slots before it.
135163 **
135164 ** e.g. nToken==1 searches for adjacent positions.
135165 */
135166 static int fts3PoslistPhraseMerge(
135167   char **pp,                      /* IN/OUT: Preallocated output buffer */
135168   int nToken,                     /* Maximum difference in token positions */
135169   int isSaveLeft,                 /* Save the left position */
135170   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
135171   char **pp1,                     /* IN/OUT: Left input list */
135172   char **pp2                      /* IN/OUT: Right input list */
135173 ){
135174   char *p = *pp;
135175   char *p1 = *pp1;
135176   char *p2 = *pp2;
135177   int iCol1 = 0;
135178   int iCol2 = 0;
135179 
135180   /* Never set both isSaveLeft and isExact for the same invocation. */
135181   assert( isSaveLeft==0 || isExact==0 );
135182 
135183   assert( p!=0 && *p1!=0 && *p2!=0 );
135184   if( *p1==POS_COLUMN ){
135185     p1++;
135186     p1 += fts3GetVarint32(p1, &iCol1);
135187   }
135188   if( *p2==POS_COLUMN ){
135189     p2++;
135190     p2 += fts3GetVarint32(p2, &iCol2);
135191   }
135192 
135193   while( 1 ){
135194     if( iCol1==iCol2 ){
135195       char *pSave = p;
135196       sqlite3_int64 iPrev = 0;
135197       sqlite3_int64 iPos1 = 0;
135198       sqlite3_int64 iPos2 = 0;
135199 
135200       if( iCol1 ){
135201         *p++ = POS_COLUMN;
135202         p += sqlite3Fts3PutVarint(p, iCol1);
135203       }
135204 
135205       assert( *p1!=POS_END && *p1!=POS_COLUMN );
135206       assert( *p2!=POS_END && *p2!=POS_COLUMN );
135207       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
135208       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
135209 
135210       while( 1 ){
135211         if( iPos2==iPos1+nToken
135212          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
135213         ){
135214           sqlite3_int64 iSave;
135215           iSave = isSaveLeft ? iPos1 : iPos2;
135216           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
135217           pSave = 0;
135218           assert( p );
135219         }
135220         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
135221           if( (*p2&0xFE)==0 ) break;
135222           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
135223         }else{
135224           if( (*p1&0xFE)==0 ) break;
135225           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
135226         }
135227       }
135228 
135229       if( pSave ){
135230         assert( pp && p );
135231         p = pSave;
135232       }
135233 
135234       fts3ColumnlistCopy(0, &p1);
135235       fts3ColumnlistCopy(0, &p2);
135236       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
135237       if( 0==*p1 || 0==*p2 ) break;
135238 
135239       p1++;
135240       p1 += fts3GetVarint32(p1, &iCol1);
135241       p2++;
135242       p2 += fts3GetVarint32(p2, &iCol2);
135243     }
135244 
135245     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
135246     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
135247     ** end of the position list, or the 0x01 that precedes the next
135248     ** column-number in the position list.
135249     */
135250     else if( iCol1<iCol2 ){
135251       fts3ColumnlistCopy(0, &p1);
135252       if( 0==*p1 ) break;
135253       p1++;
135254       p1 += fts3GetVarint32(p1, &iCol1);
135255     }else{
135256       fts3ColumnlistCopy(0, &p2);
135257       if( 0==*p2 ) break;
135258       p2++;
135259       p2 += fts3GetVarint32(p2, &iCol2);
135260     }
135261   }
135262 
135263   fts3PoslistCopy(0, &p2);
135264   fts3PoslistCopy(0, &p1);
135265   *pp1 = p1;
135266   *pp2 = p2;
135267   if( *pp==p ){
135268     return 0;
135269   }
135270   *p++ = 0x00;
135271   *pp = p;
135272   return 1;
135273 }
135274 
135275 /*
135276 ** Merge two position-lists as required by the NEAR operator. The argument
135277 ** position lists correspond to the left and right phrases of an expression
135278 ** like:
135279 **
135280 **     "phrase 1" NEAR "phrase number 2"
135281 **
135282 ** Position list *pp1 corresponds to the left-hand side of the NEAR
135283 ** expression and *pp2 to the right. As usual, the indexes in the position
135284 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
135285 ** in the example above).
135286 **
135287 ** The output position list - written to *pp - is a copy of *pp2 with those
135288 ** entries that are not sufficiently NEAR entries in *pp1 removed.
135289 */
135290 static int fts3PoslistNearMerge(
135291   char **pp,                      /* Output buffer */
135292   char *aTmp,                     /* Temporary buffer space */
135293   int nRight,                     /* Maximum difference in token positions */
135294   int nLeft,                      /* Maximum difference in token positions */
135295   char **pp1,                     /* IN/OUT: Left input list */
135296   char **pp2                      /* IN/OUT: Right input list */
135297 ){
135298   char *p1 = *pp1;
135299   char *p2 = *pp2;
135300 
135301   char *pTmp1 = aTmp;
135302   char *pTmp2;
135303   char *aTmp2;
135304   int res = 1;
135305 
135306   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
135307   aTmp2 = pTmp2 = pTmp1;
135308   *pp1 = p1;
135309   *pp2 = p2;
135310   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
135311   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
135312     fts3PoslistMerge(pp, &aTmp, &aTmp2);
135313   }else if( pTmp1!=aTmp ){
135314     fts3PoslistCopy(pp, &aTmp);
135315   }else if( pTmp2!=aTmp2 ){
135316     fts3PoslistCopy(pp, &aTmp2);
135317   }else{
135318     res = 0;
135319   }
135320 
135321   return res;
135322 }
135323 
135324 /*
135325 ** An instance of this function is used to merge together the (potentially
135326 ** large number of) doclists for each term that matches a prefix query.
135327 ** See function fts3TermSelectMerge() for details.
135328 */
135329 typedef struct TermSelect TermSelect;
135330 struct TermSelect {
135331   char *aaOutput[16];             /* Malloc'd output buffers */
135332   int anOutput[16];               /* Size each output buffer in bytes */
135333 };
135334 
135335 /*
135336 ** This function is used to read a single varint from a buffer. Parameter
135337 ** pEnd points 1 byte past the end of the buffer. When this function is
135338 ** called, if *pp points to pEnd or greater, then the end of the buffer
135339 ** has been reached. In this case *pp is set to 0 and the function returns.
135340 **
135341 ** If *pp does not point to or past pEnd, then a single varint is read
135342 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
135343 **
135344 ** If bDescIdx is false, the value read is added to *pVal before returning.
135345 ** If it is true, the value read is subtracted from *pVal before this
135346 ** function returns.
135347 */
135348 static void fts3GetDeltaVarint3(
135349   char **pp,                      /* IN/OUT: Point to read varint from */
135350   char *pEnd,                     /* End of buffer */
135351   int bDescIdx,                   /* True if docids are descending */
135352   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
135353 ){
135354   if( *pp>=pEnd ){
135355     *pp = 0;
135356   }else{
135357     sqlite3_int64 iVal;
135358     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
135359     if( bDescIdx ){
135360       *pVal -= iVal;
135361     }else{
135362       *pVal += iVal;
135363     }
135364   }
135365 }
135366 
135367 /*
135368 ** This function is used to write a single varint to a buffer. The varint
135369 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
135370 ** end of the value written.
135371 **
135372 ** If *pbFirst is zero when this function is called, the value written to
135373 ** the buffer is that of parameter iVal.
135374 **
135375 ** If *pbFirst is non-zero when this function is called, then the value
135376 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
135377 ** (if bDescIdx is non-zero).
135378 **
135379 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
135380 ** to the value of parameter iVal.
135381 */
135382 static void fts3PutDeltaVarint3(
135383   char **pp,                      /* IN/OUT: Output pointer */
135384   int bDescIdx,                   /* True for descending docids */
135385   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
135386   int *pbFirst,                   /* IN/OUT: True after first int written */
135387   sqlite3_int64 iVal              /* Write this value to the list */
135388 ){
135389   sqlite3_int64 iWrite;
135390   if( bDescIdx==0 || *pbFirst==0 ){
135391     iWrite = iVal - *piPrev;
135392   }else{
135393     iWrite = *piPrev - iVal;
135394   }
135395   assert( *pbFirst || *piPrev==0 );
135396   assert( *pbFirst==0 || iWrite>0 );
135397   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
135398   *piPrev = iVal;
135399   *pbFirst = 1;
135400 }
135401 
135402 
135403 /*
135404 ** This macro is used by various functions that merge doclists. The two
135405 ** arguments are 64-bit docid values. If the value of the stack variable
135406 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
135407 ** Otherwise, (i2-i1).
135408 **
135409 ** Using this makes it easier to write code that can merge doclists that are
135410 ** sorted in either ascending or descending order.
135411 */
135412 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
135413 
135414 /*
135415 ** This function does an "OR" merge of two doclists (output contains all
135416 ** positions contained in either argument doclist). If the docids in the
135417 ** input doclists are sorted in ascending order, parameter bDescDoclist
135418 ** should be false. If they are sorted in ascending order, it should be
135419 ** passed a non-zero value.
135420 **
135421 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
135422 ** containing the output doclist and SQLITE_OK is returned. In this case
135423 ** *pnOut is set to the number of bytes in the output doclist.
135424 **
135425 ** If an error occurs, an SQLite error code is returned. The output values
135426 ** are undefined in this case.
135427 */
135428 static int fts3DoclistOrMerge(
135429   int bDescDoclist,               /* True if arguments are desc */
135430   char *a1, int n1,               /* First doclist */
135431   char *a2, int n2,               /* Second doclist */
135432   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
135433 ){
135434   sqlite3_int64 i1 = 0;
135435   sqlite3_int64 i2 = 0;
135436   sqlite3_int64 iPrev = 0;
135437   char *pEnd1 = &a1[n1];
135438   char *pEnd2 = &a2[n2];
135439   char *p1 = a1;
135440   char *p2 = a2;
135441   char *p;
135442   char *aOut;
135443   int bFirstOut = 0;
135444 
135445   *paOut = 0;
135446   *pnOut = 0;
135447 
135448   /* Allocate space for the output. Both the input and output doclists
135449   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
135450   ** then the first docid in each list is simply encoded as a varint. For
135451   ** each subsequent docid, the varint stored is the difference between the
135452   ** current and previous docid (a positive number - since the list is in
135453   ** ascending order).
135454   **
135455   ** The first docid written to the output is therefore encoded using the
135456   ** same number of bytes as it is in whichever of the input lists it is
135457   ** read from. And each subsequent docid read from the same input list
135458   ** consumes either the same or less bytes as it did in the input (since
135459   ** the difference between it and the previous value in the output must
135460   ** be a positive value less than or equal to the delta value read from
135461   ** the input list). The same argument applies to all but the first docid
135462   ** read from the 'other' list. And to the contents of all position lists
135463   ** that will be copied and merged from the input to the output.
135464   **
135465   ** However, if the first docid copied to the output is a negative number,
135466   ** then the encoding of the first docid from the 'other' input list may
135467   ** be larger in the output than it was in the input (since the delta value
135468   ** may be a larger positive integer than the actual docid).
135469   **
135470   ** The space required to store the output is therefore the sum of the
135471   ** sizes of the two inputs, plus enough space for exactly one of the input
135472   ** docids to grow.
135473   **
135474   ** A symetric argument may be made if the doclists are in descending
135475   ** order.
135476   */
135477   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
135478   if( !aOut ) return SQLITE_NOMEM;
135479 
135480   p = aOut;
135481   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
135482   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
135483   while( p1 || p2 ){
135484     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
135485 
135486     if( p2 && p1 && iDiff==0 ){
135487       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
135488       fts3PoslistMerge(&p, &p1, &p2);
135489       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
135490       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
135491     }else if( !p2 || (p1 && iDiff<0) ){
135492       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
135493       fts3PoslistCopy(&p, &p1);
135494       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
135495     }else{
135496       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
135497       fts3PoslistCopy(&p, &p2);
135498       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
135499     }
135500   }
135501 
135502   *paOut = aOut;
135503   *pnOut = (int)(p-aOut);
135504   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
135505   return SQLITE_OK;
135506 }
135507 
135508 /*
135509 ** This function does a "phrase" merge of two doclists. In a phrase merge,
135510 ** the output contains a copy of each position from the right-hand input
135511 ** doclist for which there is a position in the left-hand input doclist
135512 ** exactly nDist tokens before it.
135513 **
135514 ** If the docids in the input doclists are sorted in ascending order,
135515 ** parameter bDescDoclist should be false. If they are sorted in ascending
135516 ** order, it should be passed a non-zero value.
135517 **
135518 ** The right-hand input doclist is overwritten by this function.
135519 */
135520 static int fts3DoclistPhraseMerge(
135521   int bDescDoclist,               /* True if arguments are desc */
135522   int nDist,                      /* Distance from left to right (1=adjacent) */
135523   char *aLeft, int nLeft,         /* Left doclist */
135524   char **paRight, int *pnRight    /* IN/OUT: Right/output doclist */
135525 ){
135526   sqlite3_int64 i1 = 0;
135527   sqlite3_int64 i2 = 0;
135528   sqlite3_int64 iPrev = 0;
135529   char *aRight = *paRight;
135530   char *pEnd1 = &aLeft[nLeft];
135531   char *pEnd2 = &aRight[*pnRight];
135532   char *p1 = aLeft;
135533   char *p2 = aRight;
135534   char *p;
135535   int bFirstOut = 0;
135536   char *aOut;
135537 
135538   assert( nDist>0 );
135539   if( bDescDoclist ){
135540     aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
135541     if( aOut==0 ) return SQLITE_NOMEM;
135542   }else{
135543     aOut = aRight;
135544   }
135545   p = aOut;
135546 
135547   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
135548   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
135549 
135550   while( p1 && p2 ){
135551     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
135552     if( iDiff==0 ){
135553       char *pSave = p;
135554       sqlite3_int64 iPrevSave = iPrev;
135555       int bFirstOutSave = bFirstOut;
135556 
135557       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
135558       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
135559         p = pSave;
135560         iPrev = iPrevSave;
135561         bFirstOut = bFirstOutSave;
135562       }
135563       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
135564       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
135565     }else if( iDiff<0 ){
135566       fts3PoslistCopy(0, &p1);
135567       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
135568     }else{
135569       fts3PoslistCopy(0, &p2);
135570       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
135571     }
135572   }
135573 
135574   *pnRight = (int)(p - aOut);
135575   if( bDescDoclist ){
135576     sqlite3_free(aRight);
135577     *paRight = aOut;
135578   }
135579 
135580   return SQLITE_OK;
135581 }
135582 
135583 /*
135584 ** Argument pList points to a position list nList bytes in size. This
135585 ** function checks to see if the position list contains any entries for
135586 ** a token in position 0 (of any column). If so, it writes argument iDelta
135587 ** to the output buffer pOut, followed by a position list consisting only
135588 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
135589 ** The value returned is the number of bytes written to pOut (if any).
135590 */
135591 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
135592   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
135593   char *pList,                    /* Position list (no 0x00 term) */
135594   int nList,                      /* Size of pList in bytes */
135595   char *pOut                      /* Write output here */
135596 ){
135597   int nOut = 0;
135598   int bWritten = 0;               /* True once iDelta has been written */
135599   char *p = pList;
135600   char *pEnd = &pList[nList];
135601 
135602   if( *p!=0x01 ){
135603     if( *p==0x02 ){
135604       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
135605       pOut[nOut++] = 0x02;
135606       bWritten = 1;
135607     }
135608     fts3ColumnlistCopy(0, &p);
135609   }
135610 
135611   while( p<pEnd && *p==0x01 ){
135612     sqlite3_int64 iCol;
135613     p++;
135614     p += sqlite3Fts3GetVarint(p, &iCol);
135615     if( *p==0x02 ){
135616       if( bWritten==0 ){
135617         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
135618         bWritten = 1;
135619       }
135620       pOut[nOut++] = 0x01;
135621       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
135622       pOut[nOut++] = 0x02;
135623     }
135624     fts3ColumnlistCopy(0, &p);
135625   }
135626   if( bWritten ){
135627     pOut[nOut++] = 0x00;
135628   }
135629 
135630   return nOut;
135631 }
135632 
135633 
135634 /*
135635 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
135636 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
135637 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
135638 **
135639 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
135640 ** the responsibility of the caller to free any doclists left in the
135641 ** TermSelect.aaOutput[] array.
135642 */
135643 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
135644   char *aOut = 0;
135645   int nOut = 0;
135646   int i;
135647 
135648   /* Loop through the doclists in the aaOutput[] array. Merge them all
135649   ** into a single doclist.
135650   */
135651   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
135652     if( pTS->aaOutput[i] ){
135653       if( !aOut ){
135654         aOut = pTS->aaOutput[i];
135655         nOut = pTS->anOutput[i];
135656         pTS->aaOutput[i] = 0;
135657       }else{
135658         int nNew;
135659         char *aNew;
135660 
135661         int rc = fts3DoclistOrMerge(p->bDescIdx,
135662             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
135663         );
135664         if( rc!=SQLITE_OK ){
135665           sqlite3_free(aOut);
135666           return rc;
135667         }
135668 
135669         sqlite3_free(pTS->aaOutput[i]);
135670         sqlite3_free(aOut);
135671         pTS->aaOutput[i] = 0;
135672         aOut = aNew;
135673         nOut = nNew;
135674       }
135675     }
135676   }
135677 
135678   pTS->aaOutput[0] = aOut;
135679   pTS->anOutput[0] = nOut;
135680   return SQLITE_OK;
135681 }
135682 
135683 /*
135684 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
135685 ** as the first argument. The merge is an "OR" merge (see function
135686 ** fts3DoclistOrMerge() for details).
135687 **
135688 ** This function is called with the doclist for each term that matches
135689 ** a queried prefix. It merges all these doclists into one, the doclist
135690 ** for the specified prefix. Since there can be a very large number of
135691 ** doclists to merge, the merging is done pair-wise using the TermSelect
135692 ** object.
135693 **
135694 ** This function returns SQLITE_OK if the merge is successful, or an
135695 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
135696 */
135697 static int fts3TermSelectMerge(
135698   Fts3Table *p,                   /* FTS table handle */
135699   TermSelect *pTS,                /* TermSelect object to merge into */
135700   char *aDoclist,                 /* Pointer to doclist */
135701   int nDoclist                    /* Size of aDoclist in bytes */
135702 ){
135703   if( pTS->aaOutput[0]==0 ){
135704     /* If this is the first term selected, copy the doclist to the output
135705     ** buffer using memcpy().
135706     **
135707     ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
135708     ** allocation. This is so as to ensure that the buffer is big enough
135709     ** to hold the current doclist AND'd with any other doclist. If the
135710     ** doclists are stored in order=ASC order, this padding would not be
135711     ** required (since the size of [doclistA AND doclistB] is always less
135712     ** than or equal to the size of [doclistA] in that case). But this is
135713     ** not true for order=DESC. For example, a doclist containing (1, -1)
135714     ** may be smaller than (-1), as in the first example the -1 may be stored
135715     ** as a single-byte delta, whereas in the second it must be stored as a
135716     ** FTS3_VARINT_MAX byte varint.
135717     **
135718     ** Similar padding is added in the fts3DoclistOrMerge() function.
135719     */
135720     pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
135721     pTS->anOutput[0] = nDoclist;
135722     if( pTS->aaOutput[0] ){
135723       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
135724     }else{
135725       return SQLITE_NOMEM;
135726     }
135727   }else{
135728     char *aMerge = aDoclist;
135729     int nMerge = nDoclist;
135730     int iOut;
135731 
135732     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
135733       if( pTS->aaOutput[iOut]==0 ){
135734         assert( iOut>0 );
135735         pTS->aaOutput[iOut] = aMerge;
135736         pTS->anOutput[iOut] = nMerge;
135737         break;
135738       }else{
135739         char *aNew;
135740         int nNew;
135741 
135742         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
135743             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
135744         );
135745         if( rc!=SQLITE_OK ){
135746           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
135747           return rc;
135748         }
135749 
135750         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
135751         sqlite3_free(pTS->aaOutput[iOut]);
135752         pTS->aaOutput[iOut] = 0;
135753 
135754         aMerge = aNew;
135755         nMerge = nNew;
135756         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
135757           pTS->aaOutput[iOut] = aMerge;
135758           pTS->anOutput[iOut] = nMerge;
135759         }
135760       }
135761     }
135762   }
135763   return SQLITE_OK;
135764 }
135765 
135766 /*
135767 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
135768 */
135769 static int fts3SegReaderCursorAppend(
135770   Fts3MultiSegReader *pCsr,
135771   Fts3SegReader *pNew
135772 ){
135773   if( (pCsr->nSegment%16)==0 ){
135774     Fts3SegReader **apNew;
135775     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
135776     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
135777     if( !apNew ){
135778       sqlite3Fts3SegReaderFree(pNew);
135779       return SQLITE_NOMEM;
135780     }
135781     pCsr->apSegment = apNew;
135782   }
135783   pCsr->apSegment[pCsr->nSegment++] = pNew;
135784   return SQLITE_OK;
135785 }
135786 
135787 /*
135788 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
135789 ** 8th argument.
135790 **
135791 ** This function returns SQLITE_OK if successful, or an SQLite error code
135792 ** otherwise.
135793 */
135794 static int fts3SegReaderCursor(
135795   Fts3Table *p,                   /* FTS3 table handle */
135796   int iLangid,                    /* Language id */
135797   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
135798   int iLevel,                     /* Level of segments to scan */
135799   const char *zTerm,              /* Term to query for */
135800   int nTerm,                      /* Size of zTerm in bytes */
135801   int isPrefix,                   /* True for a prefix search */
135802   int isScan,                     /* True to scan from zTerm to EOF */
135803   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
135804 ){
135805   int rc = SQLITE_OK;             /* Error code */
135806   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
135807   int rc2;                        /* Result of sqlite3_reset() */
135808 
135809   /* If iLevel is less than 0 and this is not a scan, include a seg-reader
135810   ** for the pending-terms. If this is a scan, then this call must be being
135811   ** made by an fts4aux module, not an FTS table. In this case calling
135812   ** Fts3SegReaderPending might segfault, as the data structures used by
135813   ** fts4aux are not completely populated. So it's easiest to filter these
135814   ** calls out here.  */
135815   if( iLevel<0 && p->aIndex ){
135816     Fts3SegReader *pSeg = 0;
135817     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
135818     if( rc==SQLITE_OK && pSeg ){
135819       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
135820     }
135821   }
135822 
135823   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
135824     if( rc==SQLITE_OK ){
135825       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
135826     }
135827 
135828     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
135829       Fts3SegReader *pSeg = 0;
135830 
135831       /* Read the values returned by the SELECT into local variables. */
135832       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
135833       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
135834       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
135835       int nRoot = sqlite3_column_bytes(pStmt, 4);
135836       char const *zRoot = sqlite3_column_blob(pStmt, 4);
135837 
135838       /* If zTerm is not NULL, and this segment is not stored entirely on its
135839       ** root node, the range of leaves scanned can be reduced. Do this. */
135840       if( iStartBlock && zTerm ){
135841         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
135842         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
135843         if( rc!=SQLITE_OK ) goto finished;
135844         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
135845       }
135846 
135847       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
135848           (isPrefix==0 && isScan==0),
135849           iStartBlock, iLeavesEndBlock,
135850           iEndBlock, zRoot, nRoot, &pSeg
135851       );
135852       if( rc!=SQLITE_OK ) goto finished;
135853       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
135854     }
135855   }
135856 
135857  finished:
135858   rc2 = sqlite3_reset(pStmt);
135859   if( rc==SQLITE_DONE ) rc = rc2;
135860 
135861   return rc;
135862 }
135863 
135864 /*
135865 ** Set up a cursor object for iterating through a full-text index or a
135866 ** single level therein.
135867 */
135868 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
135869   Fts3Table *p,                   /* FTS3 table handle */
135870   int iLangid,                    /* Language-id to search */
135871   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
135872   int iLevel,                     /* Level of segments to scan */
135873   const char *zTerm,              /* Term to query for */
135874   int nTerm,                      /* Size of zTerm in bytes */
135875   int isPrefix,                   /* True for a prefix search */
135876   int isScan,                     /* True to scan from zTerm to EOF */
135877   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
135878 ){
135879   assert( iIndex>=0 && iIndex<p->nIndex );
135880   assert( iLevel==FTS3_SEGCURSOR_ALL
135881       ||  iLevel==FTS3_SEGCURSOR_PENDING
135882       ||  iLevel>=0
135883   );
135884   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
135885   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
135886   assert( isPrefix==0 || isScan==0 );
135887 
135888   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
135889   return fts3SegReaderCursor(
135890       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
135891   );
135892 }
135893 
135894 /*
135895 ** In addition to its current configuration, have the Fts3MultiSegReader
135896 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
135897 **
135898 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
135899 */
135900 static int fts3SegReaderCursorAddZero(
135901   Fts3Table *p,                   /* FTS virtual table handle */
135902   int iLangid,
135903   const char *zTerm,              /* Term to scan doclist of */
135904   int nTerm,                      /* Number of bytes in zTerm */
135905   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
135906 ){
135907   return fts3SegReaderCursor(p,
135908       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
135909   );
135910 }
135911 
135912 /*
135913 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
135914 ** if isPrefix is true, to scan the doclist for all terms for which
135915 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
135916 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
135917 ** an SQLite error code.
135918 **
135919 ** It is the responsibility of the caller to free this object by eventually
135920 ** passing it to fts3SegReaderCursorFree()
135921 **
135922 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
135923 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
135924 */
135925 static int fts3TermSegReaderCursor(
135926   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
135927   const char *zTerm,              /* Term to query for */
135928   int nTerm,                      /* Size of zTerm in bytes */
135929   int isPrefix,                   /* True for a prefix search */
135930   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
135931 ){
135932   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
135933   int rc = SQLITE_NOMEM;          /* Return code */
135934 
135935   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
135936   if( pSegcsr ){
135937     int i;
135938     int bFound = 0;               /* True once an index has been found */
135939     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
135940 
135941     if( isPrefix ){
135942       for(i=1; bFound==0 && i<p->nIndex; i++){
135943         if( p->aIndex[i].nPrefix==nTerm ){
135944           bFound = 1;
135945           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
135946               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
135947           );
135948           pSegcsr->bLookup = 1;
135949         }
135950       }
135951 
135952       for(i=1; bFound==0 && i<p->nIndex; i++){
135953         if( p->aIndex[i].nPrefix==nTerm+1 ){
135954           bFound = 1;
135955           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
135956               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
135957           );
135958           if( rc==SQLITE_OK ){
135959             rc = fts3SegReaderCursorAddZero(
135960                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
135961             );
135962           }
135963         }
135964       }
135965     }
135966 
135967     if( bFound==0 ){
135968       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
135969           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
135970       );
135971       pSegcsr->bLookup = !isPrefix;
135972     }
135973   }
135974 
135975   *ppSegcsr = pSegcsr;
135976   return rc;
135977 }
135978 
135979 /*
135980 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
135981 */
135982 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
135983   sqlite3Fts3SegReaderFinish(pSegcsr);
135984   sqlite3_free(pSegcsr);
135985 }
135986 
135987 /*
135988 ** This function retrieves the doclist for the specified term (or term
135989 ** prefix) from the database.
135990 */
135991 static int fts3TermSelect(
135992   Fts3Table *p,                   /* Virtual table handle */
135993   Fts3PhraseToken *pTok,          /* Token to query for */
135994   int iColumn,                    /* Column to query (or -ve for all columns) */
135995   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
135996   char **ppOut                    /* OUT: Malloced result buffer */
135997 ){
135998   int rc;                         /* Return code */
135999   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
136000   TermSelect tsc;                 /* Object for pair-wise doclist merging */
136001   Fts3SegFilter filter;           /* Segment term filter configuration */
136002 
136003   pSegcsr = pTok->pSegcsr;
136004   memset(&tsc, 0, sizeof(TermSelect));
136005 
136006   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
136007         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
136008         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
136009         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
136010   filter.iCol = iColumn;
136011   filter.zTerm = pTok->z;
136012   filter.nTerm = pTok->n;
136013 
136014   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
136015   while( SQLITE_OK==rc
136016       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
136017   ){
136018     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
136019   }
136020 
136021   if( rc==SQLITE_OK ){
136022     rc = fts3TermSelectFinishMerge(p, &tsc);
136023   }
136024   if( rc==SQLITE_OK ){
136025     *ppOut = tsc.aaOutput[0];
136026     *pnOut = tsc.anOutput[0];
136027   }else{
136028     int i;
136029     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
136030       sqlite3_free(tsc.aaOutput[i]);
136031     }
136032   }
136033 
136034   fts3SegReaderCursorFree(pSegcsr);
136035   pTok->pSegcsr = 0;
136036   return rc;
136037 }
136038 
136039 /*
136040 ** This function counts the total number of docids in the doclist stored
136041 ** in buffer aList[], size nList bytes.
136042 **
136043 ** If the isPoslist argument is true, then it is assumed that the doclist
136044 ** contains a position-list following each docid. Otherwise, it is assumed
136045 ** that the doclist is simply a list of docids stored as delta encoded
136046 ** varints.
136047 */
136048 static int fts3DoclistCountDocids(char *aList, int nList){
136049   int nDoc = 0;                   /* Return value */
136050   if( aList ){
136051     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
136052     char *p = aList;              /* Cursor */
136053     while( p<aEnd ){
136054       nDoc++;
136055       while( (*p++)&0x80 );     /* Skip docid varint */
136056       fts3PoslistCopy(0, &p);   /* Skip over position list */
136057     }
136058   }
136059 
136060   return nDoc;
136061 }
136062 
136063 /*
136064 ** Advance the cursor to the next row in the %_content table that
136065 ** matches the search criteria.  For a MATCH search, this will be
136066 ** the next row that matches. For a full-table scan, this will be
136067 ** simply the next row in the %_content table.  For a docid lookup,
136068 ** this routine simply sets the EOF flag.
136069 **
136070 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
136071 ** even if we reach end-of-file.  The fts3EofMethod() will be called
136072 ** subsequently to determine whether or not an EOF was hit.
136073 */
136074 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
136075   int rc;
136076   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
136077   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
136078     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
136079       pCsr->isEof = 1;
136080       rc = sqlite3_reset(pCsr->pStmt);
136081     }else{
136082       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
136083       rc = SQLITE_OK;
136084     }
136085   }else{
136086     rc = fts3EvalNext((Fts3Cursor *)pCursor);
136087   }
136088   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
136089   return rc;
136090 }
136091 
136092 /*
136093 ** The following are copied from sqliteInt.h.
136094 **
136095 ** Constants for the largest and smallest possible 64-bit signed integers.
136096 ** These macros are designed to work correctly on both 32-bit and 64-bit
136097 ** compilers.
136098 */
136099 #ifndef SQLITE_AMALGAMATION
136100 # define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
136101 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
136102 #endif
136103 
136104 /*
136105 ** If the numeric type of argument pVal is "integer", then return it
136106 ** converted to a 64-bit signed integer. Otherwise, return a copy of
136107 ** the second parameter, iDefault.
136108 */
136109 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
136110   if( pVal ){
136111     int eType = sqlite3_value_numeric_type(pVal);
136112     if( eType==SQLITE_INTEGER ){
136113       return sqlite3_value_int64(pVal);
136114     }
136115   }
136116   return iDefault;
136117 }
136118 
136119 /*
136120 ** This is the xFilter interface for the virtual table.  See
136121 ** the virtual table xFilter method documentation for additional
136122 ** information.
136123 **
136124 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
136125 ** the %_content table.
136126 **
136127 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
136128 ** in the %_content table.
136129 **
136130 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
136131 ** column on the left-hand side of the MATCH operator is column
136132 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
136133 ** side of the MATCH operator.
136134 */
136135 static int fts3FilterMethod(
136136   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
136137   int idxNum,                     /* Strategy index */
136138   const char *idxStr,             /* Unused */
136139   int nVal,                       /* Number of elements in apVal */
136140   sqlite3_value **apVal           /* Arguments for the indexing scheme */
136141 ){
136142   int rc = SQLITE_OK;
136143   char *zSql;                     /* SQL statement used to access %_content */
136144   int eSearch;
136145   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
136146   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
136147 
136148   sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
136149   sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
136150   sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
136151   sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
136152   int iIdx;
136153 
136154   UNUSED_PARAMETER(idxStr);
136155   UNUSED_PARAMETER(nVal);
136156 
136157   eSearch = (idxNum & 0x0000FFFF);
136158   assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
136159   assert( p->pSegments==0 );
136160 
136161   /* Collect arguments into local variables */
136162   iIdx = 0;
136163   if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
136164   if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
136165   if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
136166   if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
136167   assert( iIdx==nVal );
136168 
136169   /* In case the cursor has been used before, clear it now. */
136170   sqlite3_finalize(pCsr->pStmt);
136171   sqlite3_free(pCsr->aDoclist);
136172   sqlite3_free(pCsr->aMatchinfo);
136173   sqlite3Fts3ExprFree(pCsr->pExpr);
136174   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
136175 
136176   /* Set the lower and upper bounds on docids to return */
136177   pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
136178   pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
136179 
136180   if( idxStr ){
136181     pCsr->bDesc = (idxStr[0]=='D');
136182   }else{
136183     pCsr->bDesc = p->bDescIdx;
136184   }
136185   pCsr->eSearch = (i16)eSearch;
136186 
136187   if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
136188     int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
136189     const char *zQuery = (const char *)sqlite3_value_text(pCons);
136190 
136191     if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
136192       return SQLITE_NOMEM;
136193     }
136194 
136195     pCsr->iLangid = 0;
136196     if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
136197 
136198     assert( p->base.zErrMsg==0 );
136199     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
136200         p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
136201         &p->base.zErrMsg
136202     );
136203     if( rc!=SQLITE_OK ){
136204       return rc;
136205     }
136206 
136207     rc = fts3EvalStart(pCsr);
136208     sqlite3Fts3SegmentsClose(p);
136209     if( rc!=SQLITE_OK ) return rc;
136210     pCsr->pNextId = pCsr->aDoclist;
136211     pCsr->iPrevId = 0;
136212   }
136213 
136214   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
136215   ** statement loops through all rows of the %_content table. For a
136216   ** full-text query or docid lookup, the statement retrieves a single
136217   ** row by docid.
136218   */
136219   if( eSearch==FTS3_FULLSCAN_SEARCH ){
136220     if( pDocidGe || pDocidLe ){
136221       zSql = sqlite3_mprintf(
136222           "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
136223           p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
136224           (pCsr->bDesc ? "DESC" : "ASC")
136225       );
136226     }else{
136227       zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
136228           p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
136229       );
136230     }
136231     if( zSql ){
136232       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
136233       sqlite3_free(zSql);
136234     }else{
136235       rc = SQLITE_NOMEM;
136236     }
136237   }else if( eSearch==FTS3_DOCID_SEARCH ){
136238     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
136239     if( rc==SQLITE_OK ){
136240       rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
136241     }
136242   }
136243   if( rc!=SQLITE_OK ) return rc;
136244 
136245   return fts3NextMethod(pCursor);
136246 }
136247 
136248 /*
136249 ** This is the xEof method of the virtual table. SQLite calls this
136250 ** routine to find out if it has reached the end of a result set.
136251 */
136252 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
136253   return ((Fts3Cursor *)pCursor)->isEof;
136254 }
136255 
136256 /*
136257 ** This is the xRowid method. The SQLite core calls this routine to
136258 ** retrieve the rowid for the current row of the result set. fts3
136259 ** exposes %_content.docid as the rowid for the virtual table. The
136260 ** rowid should be written to *pRowid.
136261 */
136262 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
136263   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
136264   *pRowid = pCsr->iPrevId;
136265   return SQLITE_OK;
136266 }
136267 
136268 /*
136269 ** This is the xColumn method, called by SQLite to request a value from
136270 ** the row that the supplied cursor currently points to.
136271 **
136272 ** If:
136273 **
136274 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
136275 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
136276 **   (iCol == p->nColumn+1) -> Docid column
136277 **   (iCol == p->nColumn+2) -> Langid column
136278 */
136279 static int fts3ColumnMethod(
136280   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
136281   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
136282   int iCol                        /* Index of column to read value from */
136283 ){
136284   int rc = SQLITE_OK;             /* Return Code */
136285   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
136286   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
136287 
136288   /* The column value supplied by SQLite must be in range. */
136289   assert( iCol>=0 && iCol<=p->nColumn+2 );
136290 
136291   if( iCol==p->nColumn+1 ){
136292     /* This call is a request for the "docid" column. Since "docid" is an
136293     ** alias for "rowid", use the xRowid() method to obtain the value.
136294     */
136295     sqlite3_result_int64(pCtx, pCsr->iPrevId);
136296   }else if( iCol==p->nColumn ){
136297     /* The extra column whose name is the same as the table.
136298     ** Return a blob which is a pointer to the cursor.  */
136299     sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
136300   }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
136301     sqlite3_result_int64(pCtx, pCsr->iLangid);
136302   }else{
136303     /* The requested column is either a user column (one that contains
136304     ** indexed data), or the language-id column.  */
136305     rc = fts3CursorSeek(0, pCsr);
136306 
136307     if( rc==SQLITE_OK ){
136308       if( iCol==p->nColumn+2 ){
136309         int iLangid = 0;
136310         if( p->zLanguageid ){
136311           iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
136312         }
136313         sqlite3_result_int(pCtx, iLangid);
136314       }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
136315         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
136316       }
136317     }
136318   }
136319 
136320   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
136321   return rc;
136322 }
136323 
136324 /*
136325 ** This function is the implementation of the xUpdate callback used by
136326 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
136327 ** inserted, updated or deleted.
136328 */
136329 static int fts3UpdateMethod(
136330   sqlite3_vtab *pVtab,            /* Virtual table handle */
136331   int nArg,                       /* Size of argument array */
136332   sqlite3_value **apVal,          /* Array of arguments */
136333   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
136334 ){
136335   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
136336 }
136337 
136338 /*
136339 ** Implementation of xSync() method. Flush the contents of the pending-terms
136340 ** hash-table to the database.
136341 */
136342 static int fts3SyncMethod(sqlite3_vtab *pVtab){
136343 
136344   /* Following an incremental-merge operation, assuming that the input
136345   ** segments are not completely consumed (the usual case), they are updated
136346   ** in place to remove the entries that have already been merged. This
136347   ** involves updating the leaf block that contains the smallest unmerged
136348   ** entry and each block (if any) between the leaf and the root node. So
136349   ** if the height of the input segment b-trees is N, and input segments
136350   ** are merged eight at a time, updating the input segments at the end
136351   ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
136352   ** small - often between 0 and 2. So the overhead of the incremental
136353   ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
136354   ** dwarfing the actual productive work accomplished, the incremental merge
136355   ** is only attempted if it will write at least 64 leaf blocks. Hence
136356   ** nMinMerge.
136357   **
136358   ** Of course, updating the input segments also involves deleting a bunch
136359   ** of blocks from the segments table. But this is not considered overhead
136360   ** as it would also be required by a crisis-merge that used the same input
136361   ** segments.
136362   */
136363   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
136364 
136365   Fts3Table *p = (Fts3Table*)pVtab;
136366   int rc = sqlite3Fts3PendingTermsFlush(p);
136367 
136368   if( rc==SQLITE_OK
136369    && p->nLeafAdd>(nMinMerge/16)
136370    && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
136371   ){
136372     int mxLevel = 0;              /* Maximum relative level value in db */
136373     int A;                        /* Incr-merge parameter A */
136374 
136375     rc = sqlite3Fts3MaxLevel(p, &mxLevel);
136376     assert( rc==SQLITE_OK || mxLevel==0 );
136377     A = p->nLeafAdd * mxLevel;
136378     A += (A/2);
136379     if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
136380   }
136381   sqlite3Fts3SegmentsClose(p);
136382   return rc;
136383 }
136384 
136385 /*
136386 ** If it is currently unknown whether or not the FTS table has an %_stat
136387 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
136388 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
136389 ** if an error occurs.
136390 */
136391 static int fts3SetHasStat(Fts3Table *p){
136392   int rc = SQLITE_OK;
136393   if( p->bHasStat==2 ){
136394     const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
136395     char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
136396     if( zSql ){
136397       sqlite3_stmt *pStmt = 0;
136398       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
136399       if( rc==SQLITE_OK ){
136400         int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
136401         rc = sqlite3_finalize(pStmt);
136402         if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
136403       }
136404       sqlite3_free(zSql);
136405     }else{
136406       rc = SQLITE_NOMEM;
136407     }
136408   }
136409   return rc;
136410 }
136411 
136412 /*
136413 ** Implementation of xBegin() method.
136414 */
136415 static int fts3BeginMethod(sqlite3_vtab *pVtab){
136416   Fts3Table *p = (Fts3Table*)pVtab;
136417   UNUSED_PARAMETER(pVtab);
136418   assert( p->pSegments==0 );
136419   assert( p->nPendingData==0 );
136420   assert( p->inTransaction!=1 );
136421   TESTONLY( p->inTransaction = 1 );
136422   TESTONLY( p->mxSavepoint = -1; );
136423   p->nLeafAdd = 0;
136424   return fts3SetHasStat(p);
136425 }
136426 
136427 /*
136428 ** Implementation of xCommit() method. This is a no-op. The contents of
136429 ** the pending-terms hash-table have already been flushed into the database
136430 ** by fts3SyncMethod().
136431 */
136432 static int fts3CommitMethod(sqlite3_vtab *pVtab){
136433   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
136434   UNUSED_PARAMETER(pVtab);
136435   assert( p->nPendingData==0 );
136436   assert( p->inTransaction!=0 );
136437   assert( p->pSegments==0 );
136438   TESTONLY( p->inTransaction = 0 );
136439   TESTONLY( p->mxSavepoint = -1; );
136440   return SQLITE_OK;
136441 }
136442 
136443 /*
136444 ** Implementation of xRollback(). Discard the contents of the pending-terms
136445 ** hash-table. Any changes made to the database are reverted by SQLite.
136446 */
136447 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
136448   Fts3Table *p = (Fts3Table*)pVtab;
136449   sqlite3Fts3PendingTermsClear(p);
136450   assert( p->inTransaction!=0 );
136451   TESTONLY( p->inTransaction = 0 );
136452   TESTONLY( p->mxSavepoint = -1; );
136453   return SQLITE_OK;
136454 }
136455 
136456 /*
136457 ** When called, *ppPoslist must point to the byte immediately following the
136458 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
136459 ** moves *ppPoslist so that it instead points to the first byte of the
136460 ** same position list.
136461 */
136462 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
136463   char *p = &(*ppPoslist)[-2];
136464   char c = 0;
136465 
136466   /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
136467   while( p>pStart && (c=*p--)==0 );
136468 
136469   /* Search backwards for a varint with value zero (the end of the previous
136470   ** poslist). This is an 0x00 byte preceded by some byte that does not
136471   ** have the 0x80 bit set.  */
136472   while( p>pStart && (*p & 0x80) | c ){
136473     c = *p--;
136474   }
136475   assert( p==pStart || c==0 );
136476 
136477   /* At this point p points to that preceding byte without the 0x80 bit
136478   ** set. So to find the start of the poslist, skip forward 2 bytes then
136479   ** over a varint.
136480   **
136481   ** Normally. The other case is that p==pStart and the poslist to return
136482   ** is the first in the doclist. In this case do not skip forward 2 bytes.
136483   ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
136484   ** is required for cases where the first byte of a doclist and the
136485   ** doclist is empty. For example, if the first docid is 10, a doclist
136486   ** that begins with:
136487   **
136488   **   0x0A 0x00 <next docid delta varint>
136489   */
136490   if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
136491   while( *p++&0x80 );
136492   *ppPoslist = p;
136493 }
136494 
136495 /*
136496 ** Helper function used by the implementation of the overloaded snippet(),
136497 ** offsets() and optimize() SQL functions.
136498 **
136499 ** If the value passed as the third argument is a blob of size
136500 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
136501 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
136502 ** message is written to context pContext and SQLITE_ERROR returned. The
136503 ** string passed via zFunc is used as part of the error message.
136504 */
136505 static int fts3FunctionArg(
136506   sqlite3_context *pContext,      /* SQL function call context */
136507   const char *zFunc,              /* Function name */
136508   sqlite3_value *pVal,            /* argv[0] passed to function */
136509   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
136510 ){
136511   Fts3Cursor *pRet;
136512   if( sqlite3_value_type(pVal)!=SQLITE_BLOB
136513    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
136514   ){
136515     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
136516     sqlite3_result_error(pContext, zErr, -1);
136517     sqlite3_free(zErr);
136518     return SQLITE_ERROR;
136519   }
136520   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
136521   *ppCsr = pRet;
136522   return SQLITE_OK;
136523 }
136524 
136525 /*
136526 ** Implementation of the snippet() function for FTS3
136527 */
136528 static void fts3SnippetFunc(
136529   sqlite3_context *pContext,      /* SQLite function call context */
136530   int nVal,                       /* Size of apVal[] array */
136531   sqlite3_value **apVal           /* Array of arguments */
136532 ){
136533   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
136534   const char *zStart = "<b>";
136535   const char *zEnd = "</b>";
136536   const char *zEllipsis = "<b>...</b>";
136537   int iCol = -1;
136538   int nToken = 15;                /* Default number of tokens in snippet */
136539 
136540   /* There must be at least one argument passed to this function (otherwise
136541   ** the non-overloaded version would have been called instead of this one).
136542   */
136543   assert( nVal>=1 );
136544 
136545   if( nVal>6 ){
136546     sqlite3_result_error(pContext,
136547         "wrong number of arguments to function snippet()", -1);
136548     return;
136549   }
136550   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
136551 
136552   switch( nVal ){
136553     case 6: nToken = sqlite3_value_int(apVal[5]);
136554     case 5: iCol = sqlite3_value_int(apVal[4]);
136555     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
136556     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
136557     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
136558   }
136559   if( !zEllipsis || !zEnd || !zStart ){
136560     sqlite3_result_error_nomem(pContext);
136561   }else if( nToken==0 ){
136562     sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
136563   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
136564     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
136565   }
136566 }
136567 
136568 /*
136569 ** Implementation of the offsets() function for FTS3
136570 */
136571 static void fts3OffsetsFunc(
136572   sqlite3_context *pContext,      /* SQLite function call context */
136573   int nVal,                       /* Size of argument array */
136574   sqlite3_value **apVal           /* Array of arguments */
136575 ){
136576   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
136577 
136578   UNUSED_PARAMETER(nVal);
136579 
136580   assert( nVal==1 );
136581   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
136582   assert( pCsr );
136583   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
136584     sqlite3Fts3Offsets(pContext, pCsr);
136585   }
136586 }
136587 
136588 /*
136589 ** Implementation of the special optimize() function for FTS3. This
136590 ** function merges all segments in the database to a single segment.
136591 ** Example usage is:
136592 **
136593 **   SELECT optimize(t) FROM t LIMIT 1;
136594 **
136595 ** where 't' is the name of an FTS3 table.
136596 */
136597 static void fts3OptimizeFunc(
136598   sqlite3_context *pContext,      /* SQLite function call context */
136599   int nVal,                       /* Size of argument array */
136600   sqlite3_value **apVal           /* Array of arguments */
136601 ){
136602   int rc;                         /* Return code */
136603   Fts3Table *p;                   /* Virtual table handle */
136604   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
136605 
136606   UNUSED_PARAMETER(nVal);
136607 
136608   assert( nVal==1 );
136609   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
136610   p = (Fts3Table *)pCursor->base.pVtab;
136611   assert( p );
136612 
136613   rc = sqlite3Fts3Optimize(p);
136614 
136615   switch( rc ){
136616     case SQLITE_OK:
136617       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
136618       break;
136619     case SQLITE_DONE:
136620       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
136621       break;
136622     default:
136623       sqlite3_result_error_code(pContext, rc);
136624       break;
136625   }
136626 }
136627 
136628 /*
136629 ** Implementation of the matchinfo() function for FTS3
136630 */
136631 static void fts3MatchinfoFunc(
136632   sqlite3_context *pContext,      /* SQLite function call context */
136633   int nVal,                       /* Size of argument array */
136634   sqlite3_value **apVal           /* Array of arguments */
136635 ){
136636   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
136637   assert( nVal==1 || nVal==2 );
136638   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
136639     const char *zArg = 0;
136640     if( nVal>1 ){
136641       zArg = (const char *)sqlite3_value_text(apVal[1]);
136642     }
136643     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
136644   }
136645 }
136646 
136647 /*
136648 ** This routine implements the xFindFunction method for the FTS3
136649 ** virtual table.
136650 */
136651 static int fts3FindFunctionMethod(
136652   sqlite3_vtab *pVtab,            /* Virtual table handle */
136653   int nArg,                       /* Number of SQL function arguments */
136654   const char *zName,              /* Name of SQL function */
136655   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
136656   void **ppArg                    /* Unused */
136657 ){
136658   struct Overloaded {
136659     const char *zName;
136660     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
136661   } aOverload[] = {
136662     { "snippet", fts3SnippetFunc },
136663     { "offsets", fts3OffsetsFunc },
136664     { "optimize", fts3OptimizeFunc },
136665     { "matchinfo", fts3MatchinfoFunc },
136666   };
136667   int i;                          /* Iterator variable */
136668 
136669   UNUSED_PARAMETER(pVtab);
136670   UNUSED_PARAMETER(nArg);
136671   UNUSED_PARAMETER(ppArg);
136672 
136673   for(i=0; i<SizeofArray(aOverload); i++){
136674     if( strcmp(zName, aOverload[i].zName)==0 ){
136675       *pxFunc = aOverload[i].xFunc;
136676       return 1;
136677     }
136678   }
136679 
136680   /* No function of the specified name was found. Return 0. */
136681   return 0;
136682 }
136683 
136684 /*
136685 ** Implementation of FTS3 xRename method. Rename an fts3 table.
136686 */
136687 static int fts3RenameMethod(
136688   sqlite3_vtab *pVtab,            /* Virtual table handle */
136689   const char *zName               /* New name of table */
136690 ){
136691   Fts3Table *p = (Fts3Table *)pVtab;
136692   sqlite3 *db = p->db;            /* Database connection */
136693   int rc;                         /* Return Code */
136694 
136695   /* At this point it must be known if the %_stat table exists or not.
136696   ** So bHasStat may not be 2.  */
136697   rc = fts3SetHasStat(p);
136698 
136699   /* As it happens, the pending terms table is always empty here. This is
136700   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
136701   ** always opens a savepoint transaction. And the xSavepoint() method
136702   ** flushes the pending terms table. But leave the (no-op) call to
136703   ** PendingTermsFlush() in in case that changes.
136704   */
136705   assert( p->nPendingData==0 );
136706   if( rc==SQLITE_OK ){
136707     rc = sqlite3Fts3PendingTermsFlush(p);
136708   }
136709 
136710   if( p->zContentTbl==0 ){
136711     fts3DbExec(&rc, db,
136712       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
136713       p->zDb, p->zName, zName
136714     );
136715   }
136716 
136717   if( p->bHasDocsize ){
136718     fts3DbExec(&rc, db,
136719       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
136720       p->zDb, p->zName, zName
136721     );
136722   }
136723   if( p->bHasStat ){
136724     fts3DbExec(&rc, db,
136725       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
136726       p->zDb, p->zName, zName
136727     );
136728   }
136729   fts3DbExec(&rc, db,
136730     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
136731     p->zDb, p->zName, zName
136732   );
136733   fts3DbExec(&rc, db,
136734     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
136735     p->zDb, p->zName, zName
136736   );
136737   return rc;
136738 }
136739 
136740 /*
136741 ** The xSavepoint() method.
136742 **
136743 ** Flush the contents of the pending-terms table to disk.
136744 */
136745 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
136746   int rc = SQLITE_OK;
136747   UNUSED_PARAMETER(iSavepoint);
136748   assert( ((Fts3Table *)pVtab)->inTransaction );
136749   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
136750   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
136751   if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
136752     rc = fts3SyncMethod(pVtab);
136753   }
136754   return rc;
136755 }
136756 
136757 /*
136758 ** The xRelease() method.
136759 **
136760 ** This is a no-op.
136761 */
136762 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
136763   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
136764   UNUSED_PARAMETER(iSavepoint);
136765   UNUSED_PARAMETER(pVtab);
136766   assert( p->inTransaction );
136767   assert( p->mxSavepoint >= iSavepoint );
136768   TESTONLY( p->mxSavepoint = iSavepoint-1 );
136769   return SQLITE_OK;
136770 }
136771 
136772 /*
136773 ** The xRollbackTo() method.
136774 **
136775 ** Discard the contents of the pending terms table.
136776 */
136777 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
136778   Fts3Table *p = (Fts3Table*)pVtab;
136779   UNUSED_PARAMETER(iSavepoint);
136780   assert( p->inTransaction );
136781   assert( p->mxSavepoint >= iSavepoint );
136782   TESTONLY( p->mxSavepoint = iSavepoint );
136783   sqlite3Fts3PendingTermsClear(p);
136784   return SQLITE_OK;
136785 }
136786 
136787 static const sqlite3_module fts3Module = {
136788   /* iVersion      */ 2,
136789   /* xCreate       */ fts3CreateMethod,
136790   /* xConnect      */ fts3ConnectMethod,
136791   /* xBestIndex    */ fts3BestIndexMethod,
136792   /* xDisconnect   */ fts3DisconnectMethod,
136793   /* xDestroy      */ fts3DestroyMethod,
136794   /* xOpen         */ fts3OpenMethod,
136795   /* xClose        */ fts3CloseMethod,
136796   /* xFilter       */ fts3FilterMethod,
136797   /* xNext         */ fts3NextMethod,
136798   /* xEof          */ fts3EofMethod,
136799   /* xColumn       */ fts3ColumnMethod,
136800   /* xRowid        */ fts3RowidMethod,
136801   /* xUpdate       */ fts3UpdateMethod,
136802   /* xBegin        */ fts3BeginMethod,
136803   /* xSync         */ fts3SyncMethod,
136804   /* xCommit       */ fts3CommitMethod,
136805   /* xRollback     */ fts3RollbackMethod,
136806   /* xFindFunction */ fts3FindFunctionMethod,
136807   /* xRename */       fts3RenameMethod,
136808   /* xSavepoint    */ fts3SavepointMethod,
136809   /* xRelease      */ fts3ReleaseMethod,
136810   /* xRollbackTo   */ fts3RollbackToMethod,
136811 };
136812 
136813 /*
136814 ** This function is registered as the module destructor (called when an
136815 ** FTS3 enabled database connection is closed). It frees the memory
136816 ** allocated for the tokenizer hash table.
136817 */
136818 static void hashDestroy(void *p){
136819   Fts3Hash *pHash = (Fts3Hash *)p;
136820   sqlite3Fts3HashClear(pHash);
136821   sqlite3_free(pHash);
136822 }
136823 
136824 /*
136825 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
136826 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
136827 ** respectively. The following three forward declarations are for functions
136828 ** declared in these files used to retrieve the respective implementations.
136829 **
136830 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
136831 ** to by the argument to point to the "simple" tokenizer implementation.
136832 ** And so on.
136833 */
136834 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
136835 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
136836 #ifndef SQLITE_DISABLE_FTS3_UNICODE
136837 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
136838 #endif
136839 #ifdef SQLITE_ENABLE_ICU
136840 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
136841 #endif
136842 
136843 /*
136844 ** Initialize the fts3 extension. If this extension is built as part
136845 ** of the sqlite library, then this function is called directly by
136846 ** SQLite. If fts3 is built as a dynamically loadable extension, this
136847 ** function is called by the sqlite3_extension_init() entry point.
136848 */
136849 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
136850   int rc = SQLITE_OK;
136851   Fts3Hash *pHash = 0;
136852   const sqlite3_tokenizer_module *pSimple = 0;
136853   const sqlite3_tokenizer_module *pPorter = 0;
136854 #ifndef SQLITE_DISABLE_FTS3_UNICODE
136855   const sqlite3_tokenizer_module *pUnicode = 0;
136856 #endif
136857 
136858 #ifdef SQLITE_ENABLE_ICU
136859   const sqlite3_tokenizer_module *pIcu = 0;
136860   sqlite3Fts3IcuTokenizerModule(&pIcu);
136861 #endif
136862 
136863 #ifndef SQLITE_DISABLE_FTS3_UNICODE
136864   sqlite3Fts3UnicodeTokenizer(&pUnicode);
136865 #endif
136866 
136867 #ifdef SQLITE_TEST
136868   rc = sqlite3Fts3InitTerm(db);
136869   if( rc!=SQLITE_OK ) return rc;
136870 #endif
136871 
136872   rc = sqlite3Fts3InitAux(db);
136873   if( rc!=SQLITE_OK ) return rc;
136874 
136875   sqlite3Fts3SimpleTokenizerModule(&pSimple);
136876   sqlite3Fts3PorterTokenizerModule(&pPorter);
136877 
136878   /* Allocate and initialize the hash-table used to store tokenizers. */
136879   pHash = sqlite3_malloc(sizeof(Fts3Hash));
136880   if( !pHash ){
136881     rc = SQLITE_NOMEM;
136882   }else{
136883     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
136884   }
136885 
136886   /* Load the built-in tokenizers into the hash table */
136887   if( rc==SQLITE_OK ){
136888     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
136889      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
136890 
136891 #ifndef SQLITE_DISABLE_FTS3_UNICODE
136892      || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
136893 #endif
136894 #ifdef SQLITE_ENABLE_ICU
136895      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
136896 #endif
136897     ){
136898       rc = SQLITE_NOMEM;
136899     }
136900   }
136901 
136902 #ifdef SQLITE_TEST
136903   if( rc==SQLITE_OK ){
136904     rc = sqlite3Fts3ExprInitTestInterface(db);
136905   }
136906 #endif
136907 
136908   /* Create the virtual table wrapper around the hash-table and overload
136909   ** the two scalar functions. If this is successful, register the
136910   ** module with sqlite.
136911   */
136912   if( SQLITE_OK==rc
136913    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
136914    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
136915    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
136916    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
136917    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
136918    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
136919   ){
136920     rc = sqlite3_create_module_v2(
136921         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
136922     );
136923     if( rc==SQLITE_OK ){
136924       rc = sqlite3_create_module_v2(
136925           db, "fts4", &fts3Module, (void *)pHash, 0
136926       );
136927     }
136928     if( rc==SQLITE_OK ){
136929       rc = sqlite3Fts3InitTok(db, (void *)pHash);
136930     }
136931     return rc;
136932   }
136933 
136934 
136935   /* An error has occurred. Delete the hash table and return the error code. */
136936   assert( rc!=SQLITE_OK );
136937   if( pHash ){
136938     sqlite3Fts3HashClear(pHash);
136939     sqlite3_free(pHash);
136940   }
136941   return rc;
136942 }
136943 
136944 /*
136945 ** Allocate an Fts3MultiSegReader for each token in the expression headed
136946 ** by pExpr.
136947 **
136948 ** An Fts3SegReader object is a cursor that can seek or scan a range of
136949 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
136950 ** Fts3SegReader objects internally to provide an interface to seek or scan
136951 ** within the union of all segments of a b-tree. Hence the name.
136952 **
136953 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
136954 ** segment b-tree (if the term is not a prefix or it is a prefix for which
136955 ** there exists prefix b-tree of the right length) then it may be traversed
136956 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
136957 ** doclist and then traversed.
136958 */
136959 static void fts3EvalAllocateReaders(
136960   Fts3Cursor *pCsr,               /* FTS cursor handle */
136961   Fts3Expr *pExpr,                /* Allocate readers for this expression */
136962   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
136963   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
136964   int *pRc                        /* IN/OUT: Error code */
136965 ){
136966   if( pExpr && SQLITE_OK==*pRc ){
136967     if( pExpr->eType==FTSQUERY_PHRASE ){
136968       int i;
136969       int nToken = pExpr->pPhrase->nToken;
136970       *pnToken += nToken;
136971       for(i=0; i<nToken; i++){
136972         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
136973         int rc = fts3TermSegReaderCursor(pCsr,
136974             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
136975         );
136976         if( rc!=SQLITE_OK ){
136977           *pRc = rc;
136978           return;
136979         }
136980       }
136981       assert( pExpr->pPhrase->iDoclistToken==0 );
136982       pExpr->pPhrase->iDoclistToken = -1;
136983     }else{
136984       *pnOr += (pExpr->eType==FTSQUERY_OR);
136985       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
136986       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
136987     }
136988   }
136989 }
136990 
136991 /*
136992 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
136993 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
136994 **
136995 ** This function assumes that pList points to a buffer allocated using
136996 ** sqlite3_malloc(). This function takes responsibility for eventually
136997 ** freeing the buffer.
136998 **
136999 ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
137000 */
137001 static int fts3EvalPhraseMergeToken(
137002   Fts3Table *pTab,                /* FTS Table pointer */
137003   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
137004   int iToken,                     /* Token pList/nList corresponds to */
137005   char *pList,                    /* Pointer to doclist */
137006   int nList                       /* Number of bytes in pList */
137007 ){
137008   int rc = SQLITE_OK;
137009   assert( iToken!=p->iDoclistToken );
137010 
137011   if( pList==0 ){
137012     sqlite3_free(p->doclist.aAll);
137013     p->doclist.aAll = 0;
137014     p->doclist.nAll = 0;
137015   }
137016 
137017   else if( p->iDoclistToken<0 ){
137018     p->doclist.aAll = pList;
137019     p->doclist.nAll = nList;
137020   }
137021 
137022   else if( p->doclist.aAll==0 ){
137023     sqlite3_free(pList);
137024   }
137025 
137026   else {
137027     char *pLeft;
137028     char *pRight;
137029     int nLeft;
137030     int nRight;
137031     int nDiff;
137032 
137033     if( p->iDoclistToken<iToken ){
137034       pLeft = p->doclist.aAll;
137035       nLeft = p->doclist.nAll;
137036       pRight = pList;
137037       nRight = nList;
137038       nDiff = iToken - p->iDoclistToken;
137039     }else{
137040       pRight = p->doclist.aAll;
137041       nRight = p->doclist.nAll;
137042       pLeft = pList;
137043       nLeft = nList;
137044       nDiff = p->iDoclistToken - iToken;
137045     }
137046 
137047     rc = fts3DoclistPhraseMerge(
137048         pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
137049     );
137050     sqlite3_free(pLeft);
137051     p->doclist.aAll = pRight;
137052     p->doclist.nAll = nRight;
137053   }
137054 
137055   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
137056   return rc;
137057 }
137058 
137059 /*
137060 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
137061 ** does not take deferred tokens into account.
137062 **
137063 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
137064 */
137065 static int fts3EvalPhraseLoad(
137066   Fts3Cursor *pCsr,               /* FTS Cursor handle */
137067   Fts3Phrase *p                   /* Phrase object */
137068 ){
137069   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
137070   int iToken;
137071   int rc = SQLITE_OK;
137072 
137073   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
137074     Fts3PhraseToken *pToken = &p->aToken[iToken];
137075     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
137076 
137077     if( pToken->pSegcsr ){
137078       int nThis = 0;
137079       char *pThis = 0;
137080       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
137081       if( rc==SQLITE_OK ){
137082         rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
137083       }
137084     }
137085     assert( pToken->pSegcsr==0 );
137086   }
137087 
137088   return rc;
137089 }
137090 
137091 /*
137092 ** This function is called on each phrase after the position lists for
137093 ** any deferred tokens have been loaded into memory. It updates the phrases
137094 ** current position list to include only those positions that are really
137095 ** instances of the phrase (after considering deferred tokens). If this
137096 ** means that the phrase does not appear in the current row, doclist.pList
137097 ** and doclist.nList are both zeroed.
137098 **
137099 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
137100 */
137101 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
137102   int iToken;                     /* Used to iterate through phrase tokens */
137103   char *aPoslist = 0;             /* Position list for deferred tokens */
137104   int nPoslist = 0;               /* Number of bytes in aPoslist */
137105   int iPrev = -1;                 /* Token number of previous deferred token */
137106 
137107   assert( pPhrase->doclist.bFreeList==0 );
137108 
137109   for(iToken=0; iToken<pPhrase->nToken; iToken++){
137110     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
137111     Fts3DeferredToken *pDeferred = pToken->pDeferred;
137112 
137113     if( pDeferred ){
137114       char *pList;
137115       int nList;
137116       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
137117       if( rc!=SQLITE_OK ) return rc;
137118 
137119       if( pList==0 ){
137120         sqlite3_free(aPoslist);
137121         pPhrase->doclist.pList = 0;
137122         pPhrase->doclist.nList = 0;
137123         return SQLITE_OK;
137124 
137125       }else if( aPoslist==0 ){
137126         aPoslist = pList;
137127         nPoslist = nList;
137128 
137129       }else{
137130         char *aOut = pList;
137131         char *p1 = aPoslist;
137132         char *p2 = aOut;
137133 
137134         assert( iPrev>=0 );
137135         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
137136         sqlite3_free(aPoslist);
137137         aPoslist = pList;
137138         nPoslist = (int)(aOut - aPoslist);
137139         if( nPoslist==0 ){
137140           sqlite3_free(aPoslist);
137141           pPhrase->doclist.pList = 0;
137142           pPhrase->doclist.nList = 0;
137143           return SQLITE_OK;
137144         }
137145       }
137146       iPrev = iToken;
137147     }
137148   }
137149 
137150   if( iPrev>=0 ){
137151     int nMaxUndeferred = pPhrase->iDoclistToken;
137152     if( nMaxUndeferred<0 ){
137153       pPhrase->doclist.pList = aPoslist;
137154       pPhrase->doclist.nList = nPoslist;
137155       pPhrase->doclist.iDocid = pCsr->iPrevId;
137156       pPhrase->doclist.bFreeList = 1;
137157     }else{
137158       int nDistance;
137159       char *p1;
137160       char *p2;
137161       char *aOut;
137162 
137163       if( nMaxUndeferred>iPrev ){
137164         p1 = aPoslist;
137165         p2 = pPhrase->doclist.pList;
137166         nDistance = nMaxUndeferred - iPrev;
137167       }else{
137168         p1 = pPhrase->doclist.pList;
137169         p2 = aPoslist;
137170         nDistance = iPrev - nMaxUndeferred;
137171       }
137172 
137173       aOut = (char *)sqlite3_malloc(nPoslist+8);
137174       if( !aOut ){
137175         sqlite3_free(aPoslist);
137176         return SQLITE_NOMEM;
137177       }
137178 
137179       pPhrase->doclist.pList = aOut;
137180       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
137181         pPhrase->doclist.bFreeList = 1;
137182         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
137183       }else{
137184         sqlite3_free(aOut);
137185         pPhrase->doclist.pList = 0;
137186         pPhrase->doclist.nList = 0;
137187       }
137188       sqlite3_free(aPoslist);
137189     }
137190   }
137191 
137192   return SQLITE_OK;
137193 }
137194 
137195 /*
137196 ** Maximum number of tokens a phrase may have to be considered for the
137197 ** incremental doclists strategy.
137198 */
137199 #define MAX_INCR_PHRASE_TOKENS 4
137200 
137201 /*
137202 ** This function is called for each Fts3Phrase in a full-text query
137203 ** expression to initialize the mechanism for returning rows. Once this
137204 ** function has been called successfully on an Fts3Phrase, it may be
137205 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
137206 **
137207 ** If parameter bOptOk is true, then the phrase may (or may not) use the
137208 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
137209 ** memory within this call.
137210 **
137211 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
137212 */
137213 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
137214   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
137215   int rc = SQLITE_OK;             /* Error code */
137216   int i;
137217 
137218   /* Determine if doclists may be loaded from disk incrementally. This is
137219   ** possible if the bOptOk argument is true, the FTS doclists will be
137220   ** scanned in forward order, and the phrase consists of
137221   ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
137222   ** tokens or prefix tokens that cannot use a prefix-index.  */
137223   int bHaveIncr = 0;
137224   int bIncrOk = (bOptOk
137225    && pCsr->bDesc==pTab->bDescIdx
137226    && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
137227    && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
137228 #ifdef SQLITE_TEST
137229    && pTab->bNoIncrDoclist==0
137230 #endif
137231   );
137232   for(i=0; bIncrOk==1 && i<p->nToken; i++){
137233     Fts3PhraseToken *pToken = &p->aToken[i];
137234     if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
137235       bIncrOk = 0;
137236     }
137237     if( pToken->pSegcsr ) bHaveIncr = 1;
137238   }
137239 
137240   if( bIncrOk && bHaveIncr ){
137241     /* Use the incremental approach. */
137242     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
137243     for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
137244       Fts3PhraseToken *pToken = &p->aToken[i];
137245       Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
137246       if( pSegcsr ){
137247         rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
137248       }
137249     }
137250     p->bIncr = 1;
137251   }else{
137252     /* Load the full doclist for the phrase into memory. */
137253     rc = fts3EvalPhraseLoad(pCsr, p);
137254     p->bIncr = 0;
137255   }
137256 
137257   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
137258   return rc;
137259 }
137260 
137261 /*
137262 ** This function is used to iterate backwards (from the end to start)
137263 ** through doclists. It is used by this module to iterate through phrase
137264 ** doclists in reverse and by the fts3_write.c module to iterate through
137265 ** pending-terms lists when writing to databases with "order=desc".
137266 **
137267 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
137268 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
137269 ** function iterates from the end of the doclist to the beginning.
137270 */
137271 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
137272   int bDescIdx,                   /* True if the doclist is desc */
137273   char *aDoclist,                 /* Pointer to entire doclist */
137274   int nDoclist,                   /* Length of aDoclist in bytes */
137275   char **ppIter,                  /* IN/OUT: Iterator pointer */
137276   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
137277   int *pnList,                    /* OUT: List length pointer */
137278   u8 *pbEof                       /* OUT: End-of-file flag */
137279 ){
137280   char *p = *ppIter;
137281 
137282   assert( nDoclist>0 );
137283   assert( *pbEof==0 );
137284   assert( p || *piDocid==0 );
137285   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
137286 
137287   if( p==0 ){
137288     sqlite3_int64 iDocid = 0;
137289     char *pNext = 0;
137290     char *pDocid = aDoclist;
137291     char *pEnd = &aDoclist[nDoclist];
137292     int iMul = 1;
137293 
137294     while( pDocid<pEnd ){
137295       sqlite3_int64 iDelta;
137296       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
137297       iDocid += (iMul * iDelta);
137298       pNext = pDocid;
137299       fts3PoslistCopy(0, &pDocid);
137300       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
137301       iMul = (bDescIdx ? -1 : 1);
137302     }
137303 
137304     *pnList = (int)(pEnd - pNext);
137305     *ppIter = pNext;
137306     *piDocid = iDocid;
137307   }else{
137308     int iMul = (bDescIdx ? -1 : 1);
137309     sqlite3_int64 iDelta;
137310     fts3GetReverseVarint(&p, aDoclist, &iDelta);
137311     *piDocid -= (iMul * iDelta);
137312 
137313     if( p==aDoclist ){
137314       *pbEof = 1;
137315     }else{
137316       char *pSave = p;
137317       fts3ReversePoslist(aDoclist, &p);
137318       *pnList = (int)(pSave - p);
137319     }
137320     *ppIter = p;
137321   }
137322 }
137323 
137324 /*
137325 ** Iterate forwards through a doclist.
137326 */
137327 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
137328   int bDescIdx,                   /* True if the doclist is desc */
137329   char *aDoclist,                 /* Pointer to entire doclist */
137330   int nDoclist,                   /* Length of aDoclist in bytes */
137331   char **ppIter,                  /* IN/OUT: Iterator pointer */
137332   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
137333   u8 *pbEof                       /* OUT: End-of-file flag */
137334 ){
137335   char *p = *ppIter;
137336 
137337   assert( nDoclist>0 );
137338   assert( *pbEof==0 );
137339   assert( p || *piDocid==0 );
137340   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
137341 
137342   if( p==0 ){
137343     p = aDoclist;
137344     p += sqlite3Fts3GetVarint(p, piDocid);
137345   }else{
137346     fts3PoslistCopy(0, &p);
137347     if( p>=&aDoclist[nDoclist] ){
137348       *pbEof = 1;
137349     }else{
137350       sqlite3_int64 iVar;
137351       p += sqlite3Fts3GetVarint(p, &iVar);
137352       *piDocid += ((bDescIdx ? -1 : 1) * iVar);
137353     }
137354   }
137355 
137356   *ppIter = p;
137357 }
137358 
137359 /*
137360 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
137361 ** to true if EOF is reached.
137362 */
137363 static void fts3EvalDlPhraseNext(
137364   Fts3Table *pTab,
137365   Fts3Doclist *pDL,
137366   u8 *pbEof
137367 ){
137368   char *pIter;                            /* Used to iterate through aAll */
137369   char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
137370 
137371   if( pDL->pNextDocid ){
137372     pIter = pDL->pNextDocid;
137373   }else{
137374     pIter = pDL->aAll;
137375   }
137376 
137377   if( pIter>=pEnd ){
137378     /* We have already reached the end of this doclist. EOF. */
137379     *pbEof = 1;
137380   }else{
137381     sqlite3_int64 iDelta;
137382     pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
137383     if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
137384       pDL->iDocid += iDelta;
137385     }else{
137386       pDL->iDocid -= iDelta;
137387     }
137388     pDL->pList = pIter;
137389     fts3PoslistCopy(0, &pIter);
137390     pDL->nList = (int)(pIter - pDL->pList);
137391 
137392     /* pIter now points just past the 0x00 that terminates the position-
137393     ** list for document pDL->iDocid. However, if this position-list was
137394     ** edited in place by fts3EvalNearTrim(), then pIter may not actually
137395     ** point to the start of the next docid value. The following line deals
137396     ** with this case by advancing pIter past the zero-padding added by
137397     ** fts3EvalNearTrim().  */
137398     while( pIter<pEnd && *pIter==0 ) pIter++;
137399 
137400     pDL->pNextDocid = pIter;
137401     assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
137402     *pbEof = 0;
137403   }
137404 }
137405 
137406 /*
137407 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
137408 */
137409 typedef struct TokenDoclist TokenDoclist;
137410 struct TokenDoclist {
137411   int bIgnore;
137412   sqlite3_int64 iDocid;
137413   char *pList;
137414   int nList;
137415 };
137416 
137417 /*
137418 ** Token pToken is an incrementally loaded token that is part of a
137419 ** multi-token phrase. Advance it to the next matching document in the
137420 ** database and populate output variable *p with the details of the new
137421 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
137422 **
137423 ** If an error occurs, return an SQLite error code. Otherwise, return
137424 ** SQLITE_OK.
137425 */
137426 static int incrPhraseTokenNext(
137427   Fts3Table *pTab,                /* Virtual table handle */
137428   Fts3Phrase *pPhrase,            /* Phrase to advance token of */
137429   int iToken,                     /* Specific token to advance */
137430   TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
137431   u8 *pbEof                       /* OUT: True if iterator is at EOF */
137432 ){
137433   int rc = SQLITE_OK;
137434 
137435   if( pPhrase->iDoclistToken==iToken ){
137436     assert( p->bIgnore==0 );
137437     assert( pPhrase->aToken[iToken].pSegcsr==0 );
137438     fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
137439     p->pList = pPhrase->doclist.pList;
137440     p->nList = pPhrase->doclist.nList;
137441     p->iDocid = pPhrase->doclist.iDocid;
137442   }else{
137443     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
137444     assert( pToken->pDeferred==0 );
137445     assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
137446     if( pToken->pSegcsr ){
137447       assert( p->bIgnore==0 );
137448       rc = sqlite3Fts3MsrIncrNext(
137449           pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
137450       );
137451       if( p->pList==0 ) *pbEof = 1;
137452     }else{
137453       p->bIgnore = 1;
137454     }
137455   }
137456 
137457   return rc;
137458 }
137459 
137460 
137461 /*
137462 ** The phrase iterator passed as the second argument:
137463 **
137464 **   * features at least one token that uses an incremental doclist, and
137465 **
137466 **   * does not contain any deferred tokens.
137467 **
137468 ** Advance it to the next matching documnent in the database and populate
137469 ** the Fts3Doclist.pList and nList fields.
137470 **
137471 ** If there is no "next" entry and no error occurs, then *pbEof is set to
137472 ** 1 before returning. Otherwise, if no error occurs and the iterator is
137473 ** successfully advanced, *pbEof is set to 0.
137474 **
137475 ** If an error occurs, return an SQLite error code. Otherwise, return
137476 ** SQLITE_OK.
137477 */
137478 static int fts3EvalIncrPhraseNext(
137479   Fts3Cursor *pCsr,               /* FTS Cursor handle */
137480   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
137481   u8 *pbEof                       /* OUT: Set to 1 if EOF */
137482 ){
137483   int rc = SQLITE_OK;
137484   Fts3Doclist *pDL = &p->doclist;
137485   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
137486   u8 bEof = 0;
137487 
137488   /* This is only called if it is guaranteed that the phrase has at least
137489   ** one incremental token. In which case the bIncr flag is set. */
137490   assert( p->bIncr==1 );
137491 
137492   if( p->nToken==1 && p->bIncr ){
137493     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
137494         &pDL->iDocid, &pDL->pList, &pDL->nList
137495     );
137496     if( pDL->pList==0 ) bEof = 1;
137497   }else{
137498     int bDescDoclist = pCsr->bDesc;
137499     struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
137500 
137501     memset(a, 0, sizeof(a));
137502     assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
137503     assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
137504 
137505     while( bEof==0 ){
137506       int bMaxSet = 0;
137507       sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
137508       int i;                      /* Used to iterate through tokens */
137509 
137510       /* Advance the iterator for each token in the phrase once. */
137511       for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
137512         rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
137513         if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
137514           iMax = a[i].iDocid;
137515           bMaxSet = 1;
137516         }
137517       }
137518       assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
137519       assert( rc!=SQLITE_OK || bMaxSet );
137520 
137521       /* Keep advancing iterators until they all point to the same document */
137522       for(i=0; i<p->nToken; i++){
137523         while( rc==SQLITE_OK && bEof==0
137524             && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
137525         ){
137526           rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
137527           if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
137528             iMax = a[i].iDocid;
137529             i = 0;
137530           }
137531         }
137532       }
137533 
137534       /* Check if the current entries really are a phrase match */
137535       if( bEof==0 ){
137536         int nList = 0;
137537         int nByte = a[p->nToken-1].nList;
137538         char *aDoclist = sqlite3_malloc(nByte+1);
137539         if( !aDoclist ) return SQLITE_NOMEM;
137540         memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
137541 
137542         for(i=0; i<(p->nToken-1); i++){
137543           if( a[i].bIgnore==0 ){
137544             char *pL = a[i].pList;
137545             char *pR = aDoclist;
137546             char *pOut = aDoclist;
137547             int nDist = p->nToken-1-i;
137548             int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
137549             if( res==0 ) break;
137550             nList = (int)(pOut - aDoclist);
137551           }
137552         }
137553         if( i==(p->nToken-1) ){
137554           pDL->iDocid = iMax;
137555           pDL->pList = aDoclist;
137556           pDL->nList = nList;
137557           pDL->bFreeList = 1;
137558           break;
137559         }
137560         sqlite3_free(aDoclist);
137561       }
137562     }
137563   }
137564 
137565   *pbEof = bEof;
137566   return rc;
137567 }
137568 
137569 /*
137570 ** Attempt to move the phrase iterator to point to the next matching docid.
137571 ** If an error occurs, return an SQLite error code. Otherwise, return
137572 ** SQLITE_OK.
137573 **
137574 ** If there is no "next" entry and no error occurs, then *pbEof is set to
137575 ** 1 before returning. Otherwise, if no error occurs and the iterator is
137576 ** successfully advanced, *pbEof is set to 0.
137577 */
137578 static int fts3EvalPhraseNext(
137579   Fts3Cursor *pCsr,               /* FTS Cursor handle */
137580   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
137581   u8 *pbEof                       /* OUT: Set to 1 if EOF */
137582 ){
137583   int rc = SQLITE_OK;
137584   Fts3Doclist *pDL = &p->doclist;
137585   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
137586 
137587   if( p->bIncr ){
137588     rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
137589   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
137590     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
137591         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
137592     );
137593     pDL->pList = pDL->pNextDocid;
137594   }else{
137595     fts3EvalDlPhraseNext(pTab, pDL, pbEof);
137596   }
137597 
137598   return rc;
137599 }
137600 
137601 /*
137602 **
137603 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
137604 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
137605 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
137606 ** expressions for which all descendent tokens are deferred.
137607 **
137608 ** If parameter bOptOk is zero, then it is guaranteed that the
137609 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
137610 ** each phrase in the expression (subject to deferred token processing).
137611 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
137612 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
137613 **
137614 ** If an error occurs within this function, *pRc is set to an SQLite error
137615 ** code before returning.
137616 */
137617 static void fts3EvalStartReaders(
137618   Fts3Cursor *pCsr,               /* FTS Cursor handle */
137619   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
137620   int *pRc                        /* IN/OUT: Error code */
137621 ){
137622   if( pExpr && SQLITE_OK==*pRc ){
137623     if( pExpr->eType==FTSQUERY_PHRASE ){
137624       int nToken = pExpr->pPhrase->nToken;
137625       if( nToken ){
137626         int i;
137627         for(i=0; i<nToken; i++){
137628           if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
137629         }
137630         pExpr->bDeferred = (i==nToken);
137631       }
137632       *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
137633     }else{
137634       fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
137635       fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
137636       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
137637     }
137638   }
137639 }
137640 
137641 /*
137642 ** An array of the following structures is assembled as part of the process
137643 ** of selecting tokens to defer before the query starts executing (as part
137644 ** of the xFilter() method). There is one element in the array for each
137645 ** token in the FTS expression.
137646 **
137647 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
137648 ** to phrases that are connected only by AND and NEAR operators (not OR or
137649 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
137650 ** separately. The root of a tokens AND/NEAR cluster is stored in
137651 ** Fts3TokenAndCost.pRoot.
137652 */
137653 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
137654 struct Fts3TokenAndCost {
137655   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
137656   int iToken;                     /* Position of token in phrase */
137657   Fts3PhraseToken *pToken;        /* The token itself */
137658   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
137659   int nOvfl;                      /* Number of overflow pages to load doclist */
137660   int iCol;                       /* The column the token must match */
137661 };
137662 
137663 /*
137664 ** This function is used to populate an allocated Fts3TokenAndCost array.
137665 **
137666 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
137667 ** Otherwise, if an error occurs during execution, *pRc is set to an
137668 ** SQLite error code.
137669 */
137670 static void fts3EvalTokenCosts(
137671   Fts3Cursor *pCsr,               /* FTS Cursor handle */
137672   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
137673   Fts3Expr *pExpr,                /* Expression to consider */
137674   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
137675   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
137676   int *pRc                        /* IN/OUT: Error code */
137677 ){
137678   if( *pRc==SQLITE_OK ){
137679     if( pExpr->eType==FTSQUERY_PHRASE ){
137680       Fts3Phrase *pPhrase = pExpr->pPhrase;
137681       int i;
137682       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
137683         Fts3TokenAndCost *pTC = (*ppTC)++;
137684         pTC->pPhrase = pPhrase;
137685         pTC->iToken = i;
137686         pTC->pRoot = pRoot;
137687         pTC->pToken = &pPhrase->aToken[i];
137688         pTC->iCol = pPhrase->iColumn;
137689         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
137690       }
137691     }else if( pExpr->eType!=FTSQUERY_NOT ){
137692       assert( pExpr->eType==FTSQUERY_OR
137693            || pExpr->eType==FTSQUERY_AND
137694            || pExpr->eType==FTSQUERY_NEAR
137695       );
137696       assert( pExpr->pLeft && pExpr->pRight );
137697       if( pExpr->eType==FTSQUERY_OR ){
137698         pRoot = pExpr->pLeft;
137699         **ppOr = pRoot;
137700         (*ppOr)++;
137701       }
137702       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
137703       if( pExpr->eType==FTSQUERY_OR ){
137704         pRoot = pExpr->pRight;
137705         **ppOr = pRoot;
137706         (*ppOr)++;
137707       }
137708       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
137709     }
137710   }
137711 }
137712 
137713 /*
137714 ** Determine the average document (row) size in pages. If successful,
137715 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
137716 ** an SQLite error code.
137717 **
137718 ** The average document size in pages is calculated by first calculating
137719 ** determining the average size in bytes, B. If B is less than the amount
137720 ** of data that will fit on a single leaf page of an intkey table in
137721 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
137722 ** the number of overflow pages consumed by a record B bytes in size.
137723 */
137724 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
137725   if( pCsr->nRowAvg==0 ){
137726     /* The average document size, which is required to calculate the cost
137727     ** of each doclist, has not yet been determined. Read the required
137728     ** data from the %_stat table to calculate it.
137729     **
137730     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
137731     ** varints, where nCol is the number of columns in the FTS3 table.
137732     ** The first varint is the number of documents currently stored in
137733     ** the table. The following nCol varints contain the total amount of
137734     ** data stored in all rows of each column of the table, from left
137735     ** to right.
137736     */
137737     int rc;
137738     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
137739     sqlite3_stmt *pStmt;
137740     sqlite3_int64 nDoc = 0;
137741     sqlite3_int64 nByte = 0;
137742     const char *pEnd;
137743     const char *a;
137744 
137745     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
137746     if( rc!=SQLITE_OK ) return rc;
137747     a = sqlite3_column_blob(pStmt, 0);
137748     assert( a );
137749 
137750     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
137751     a += sqlite3Fts3GetVarint(a, &nDoc);
137752     while( a<pEnd ){
137753       a += sqlite3Fts3GetVarint(a, &nByte);
137754     }
137755     if( nDoc==0 || nByte==0 ){
137756       sqlite3_reset(pStmt);
137757       return FTS_CORRUPT_VTAB;
137758     }
137759 
137760     pCsr->nDoc = nDoc;
137761     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
137762     assert( pCsr->nRowAvg>0 );
137763     rc = sqlite3_reset(pStmt);
137764     if( rc!=SQLITE_OK ) return rc;
137765   }
137766 
137767   *pnPage = pCsr->nRowAvg;
137768   return SQLITE_OK;
137769 }
137770 
137771 /*
137772 ** This function is called to select the tokens (if any) that will be
137773 ** deferred. The array aTC[] has already been populated when this is
137774 ** called.
137775 **
137776 ** This function is called once for each AND/NEAR cluster in the
137777 ** expression. Each invocation determines which tokens to defer within
137778 ** the cluster with root node pRoot. See comments above the definition
137779 ** of struct Fts3TokenAndCost for more details.
137780 **
137781 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
137782 ** called on each token to defer. Otherwise, an SQLite error code is
137783 ** returned.
137784 */
137785 static int fts3EvalSelectDeferred(
137786   Fts3Cursor *pCsr,               /* FTS Cursor handle */
137787   Fts3Expr *pRoot,                /* Consider tokens with this root node */
137788   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
137789   int nTC                         /* Number of entries in aTC[] */
137790 ){
137791   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
137792   int nDocSize = 0;               /* Number of pages per doc loaded */
137793   int rc = SQLITE_OK;             /* Return code */
137794   int ii;                         /* Iterator variable for various purposes */
137795   int nOvfl = 0;                  /* Total overflow pages used by doclists */
137796   int nToken = 0;                 /* Total number of tokens in cluster */
137797 
137798   int nMinEst = 0;                /* The minimum count for any phrase so far. */
137799   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
137800 
137801   /* Tokens are never deferred for FTS tables created using the content=xxx
137802   ** option. The reason being that it is not guaranteed that the content
137803   ** table actually contains the same data as the index. To prevent this from
137804   ** causing any problems, the deferred token optimization is completely
137805   ** disabled for content=xxx tables. */
137806   if( pTab->zContentTbl ){
137807     return SQLITE_OK;
137808   }
137809 
137810   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
137811   ** associated with the tokens spill onto overflow pages, or if there is
137812   ** only 1 token, exit early. No tokens to defer in this case. */
137813   for(ii=0; ii<nTC; ii++){
137814     if( aTC[ii].pRoot==pRoot ){
137815       nOvfl += aTC[ii].nOvfl;
137816       nToken++;
137817     }
137818   }
137819   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
137820 
137821   /* Obtain the average docsize (in pages). */
137822   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
137823   assert( rc!=SQLITE_OK || nDocSize>0 );
137824 
137825 
137826   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
137827   ** of the number of overflow pages that will be loaded by the pager layer
137828   ** to retrieve the entire doclist for the token from the full-text index.
137829   ** Load the doclists for tokens that are either:
137830   **
137831   **   a. The cheapest token in the entire query (i.e. the one visited by the
137832   **      first iteration of this loop), or
137833   **
137834   **   b. Part of a multi-token phrase.
137835   **
137836   ** After each token doclist is loaded, merge it with the others from the
137837   ** same phrase and count the number of documents that the merged doclist
137838   ** contains. Set variable "nMinEst" to the smallest number of documents in
137839   ** any phrase doclist for which 1 or more token doclists have been loaded.
137840   ** Let nOther be the number of other phrases for which it is certain that
137841   ** one or more tokens will not be deferred.
137842   **
137843   ** Then, for each token, defer it if loading the doclist would result in
137844   ** loading N or more overflow pages into memory, where N is computed as:
137845   **
137846   **    (nMinEst + 4^nOther - 1) / (4^nOther)
137847   */
137848   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
137849     int iTC;                      /* Used to iterate through aTC[] array. */
137850     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
137851 
137852     /* Set pTC to point to the cheapest remaining token. */
137853     for(iTC=0; iTC<nTC; iTC++){
137854       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
137855        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
137856       ){
137857         pTC = &aTC[iTC];
137858       }
137859     }
137860     assert( pTC );
137861 
137862     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
137863       /* The number of overflow pages to load for this (and therefore all
137864       ** subsequent) tokens is greater than the estimated number of pages
137865       ** that will be loaded if all subsequent tokens are deferred.
137866       */
137867       Fts3PhraseToken *pToken = pTC->pToken;
137868       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
137869       fts3SegReaderCursorFree(pToken->pSegcsr);
137870       pToken->pSegcsr = 0;
137871     }else{
137872       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
137873       ** for-loop. Except, limit the value to 2^24 to prevent it from
137874       ** overflowing the 32-bit integer it is stored in. */
137875       if( ii<12 ) nLoad4 = nLoad4*4;
137876 
137877       if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
137878         /* Either this is the cheapest token in the entire query, or it is
137879         ** part of a multi-token phrase. Either way, the entire doclist will
137880         ** (eventually) be loaded into memory. It may as well be now. */
137881         Fts3PhraseToken *pToken = pTC->pToken;
137882         int nList = 0;
137883         char *pList = 0;
137884         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
137885         assert( rc==SQLITE_OK || pList==0 );
137886         if( rc==SQLITE_OK ){
137887           rc = fts3EvalPhraseMergeToken(
137888               pTab, pTC->pPhrase, pTC->iToken,pList,nList
137889           );
137890         }
137891         if( rc==SQLITE_OK ){
137892           int nCount;
137893           nCount = fts3DoclistCountDocids(
137894               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
137895           );
137896           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
137897         }
137898       }
137899     }
137900     pTC->pToken = 0;
137901   }
137902 
137903   return rc;
137904 }
137905 
137906 /*
137907 ** This function is called from within the xFilter method. It initializes
137908 ** the full-text query currently stored in pCsr->pExpr. To iterate through
137909 ** the results of a query, the caller does:
137910 **
137911 **    fts3EvalStart(pCsr);
137912 **    while( 1 ){
137913 **      fts3EvalNext(pCsr);
137914 **      if( pCsr->bEof ) break;
137915 **      ... return row pCsr->iPrevId to the caller ...
137916 **    }
137917 */
137918 static int fts3EvalStart(Fts3Cursor *pCsr){
137919   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
137920   int rc = SQLITE_OK;
137921   int nToken = 0;
137922   int nOr = 0;
137923 
137924   /* Allocate a MultiSegReader for each token in the expression. */
137925   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
137926 
137927   /* Determine which, if any, tokens in the expression should be deferred. */
137928 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
137929   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
137930     Fts3TokenAndCost *aTC;
137931     Fts3Expr **apOr;
137932     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
137933         sizeof(Fts3TokenAndCost) * nToken
137934       + sizeof(Fts3Expr *) * nOr * 2
137935     );
137936     apOr = (Fts3Expr **)&aTC[nToken];
137937 
137938     if( !aTC ){
137939       rc = SQLITE_NOMEM;
137940     }else{
137941       int ii;
137942       Fts3TokenAndCost *pTC = aTC;
137943       Fts3Expr **ppOr = apOr;
137944 
137945       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
137946       nToken = (int)(pTC-aTC);
137947       nOr = (int)(ppOr-apOr);
137948 
137949       if( rc==SQLITE_OK ){
137950         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
137951         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
137952           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
137953         }
137954       }
137955 
137956       sqlite3_free(aTC);
137957     }
137958   }
137959 #endif
137960 
137961   fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
137962   return rc;
137963 }
137964 
137965 /*
137966 ** Invalidate the current position list for phrase pPhrase.
137967 */
137968 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
137969   if( pPhrase->doclist.bFreeList ){
137970     sqlite3_free(pPhrase->doclist.pList);
137971   }
137972   pPhrase->doclist.pList = 0;
137973   pPhrase->doclist.nList = 0;
137974   pPhrase->doclist.bFreeList = 0;
137975 }
137976 
137977 /*
137978 ** This function is called to edit the position list associated with
137979 ** the phrase object passed as the fifth argument according to a NEAR
137980 ** condition. For example:
137981 **
137982 **     abc NEAR/5 "def ghi"
137983 **
137984 ** Parameter nNear is passed the NEAR distance of the expression (5 in
137985 ** the example above). When this function is called, *paPoslist points to
137986 ** the position list, and *pnToken is the number of phrase tokens in, the
137987 ** phrase on the other side of the NEAR operator to pPhrase. For example,
137988 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
137989 ** the position list associated with phrase "abc".
137990 **
137991 ** All positions in the pPhrase position list that are not sufficiently
137992 ** close to a position in the *paPoslist position list are removed. If this
137993 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
137994 **
137995 ** Before returning, *paPoslist is set to point to the position lsit
137996 ** associated with pPhrase. And *pnToken is set to the number of tokens in
137997 ** pPhrase.
137998 */
137999 static int fts3EvalNearTrim(
138000   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
138001   char *aTmp,                     /* Temporary space to use */
138002   char **paPoslist,               /* IN/OUT: Position list */
138003   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
138004   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
138005 ){
138006   int nParam1 = nNear + pPhrase->nToken;
138007   int nParam2 = nNear + *pnToken;
138008   int nNew;
138009   char *p2;
138010   char *pOut;
138011   int res;
138012 
138013   assert( pPhrase->doclist.pList );
138014 
138015   p2 = pOut = pPhrase->doclist.pList;
138016   res = fts3PoslistNearMerge(
138017     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
138018   );
138019   if( res ){
138020     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
138021     assert( pPhrase->doclist.pList[nNew]=='\0' );
138022     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
138023     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
138024     pPhrase->doclist.nList = nNew;
138025     *paPoslist = pPhrase->doclist.pList;
138026     *pnToken = pPhrase->nToken;
138027   }
138028 
138029   return res;
138030 }
138031 
138032 /*
138033 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
138034 ** Otherwise, it advances the expression passed as the second argument to
138035 ** point to the next matching row in the database. Expressions iterate through
138036 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
138037 ** or descending if it is non-zero.
138038 **
138039 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
138040 ** successful, the following variables in pExpr are set:
138041 **
138042 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
138043 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
138044 **
138045 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
138046 ** at EOF, then the following variables are populated with the position list
138047 ** for the phrase for the visited row:
138048 **
138049 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
138050 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
138051 **
138052 ** It says above that this function advances the expression to the next
138053 ** matching row. This is usually true, but there are the following exceptions:
138054 **
138055 **   1. Deferred tokens are not taken into account. If a phrase consists
138056 **      entirely of deferred tokens, it is assumed to match every row in
138057 **      the db. In this case the position-list is not populated at all.
138058 **
138059 **      Or, if a phrase contains one or more deferred tokens and one or
138060 **      more non-deferred tokens, then the expression is advanced to the
138061 **      next possible match, considering only non-deferred tokens. In other
138062 **      words, if the phrase is "A B C", and "B" is deferred, the expression
138063 **      is advanced to the next row that contains an instance of "A * C",
138064 **      where "*" may match any single token. The position list in this case
138065 **      is populated as for "A * C" before returning.
138066 **
138067 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
138068 **      advanced to point to the next row that matches "x AND y".
138069 **
138070 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
138071 ** really a match, taking into account deferred tokens and NEAR operators.
138072 */
138073 static void fts3EvalNextRow(
138074   Fts3Cursor *pCsr,               /* FTS Cursor handle */
138075   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
138076   int *pRc                        /* IN/OUT: Error code */
138077 ){
138078   if( *pRc==SQLITE_OK ){
138079     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
138080     assert( pExpr->bEof==0 );
138081     pExpr->bStart = 1;
138082 
138083     switch( pExpr->eType ){
138084       case FTSQUERY_NEAR:
138085       case FTSQUERY_AND: {
138086         Fts3Expr *pLeft = pExpr->pLeft;
138087         Fts3Expr *pRight = pExpr->pRight;
138088         assert( !pLeft->bDeferred || !pRight->bDeferred );
138089 
138090         if( pLeft->bDeferred ){
138091           /* LHS is entirely deferred. So we assume it matches every row.
138092           ** Advance the RHS iterator to find the next row visited. */
138093           fts3EvalNextRow(pCsr, pRight, pRc);
138094           pExpr->iDocid = pRight->iDocid;
138095           pExpr->bEof = pRight->bEof;
138096         }else if( pRight->bDeferred ){
138097           /* RHS is entirely deferred. So we assume it matches every row.
138098           ** Advance the LHS iterator to find the next row visited. */
138099           fts3EvalNextRow(pCsr, pLeft, pRc);
138100           pExpr->iDocid = pLeft->iDocid;
138101           pExpr->bEof = pLeft->bEof;
138102         }else{
138103           /* Neither the RHS or LHS are deferred. */
138104           fts3EvalNextRow(pCsr, pLeft, pRc);
138105           fts3EvalNextRow(pCsr, pRight, pRc);
138106           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
138107             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
138108             if( iDiff==0 ) break;
138109             if( iDiff<0 ){
138110               fts3EvalNextRow(pCsr, pLeft, pRc);
138111             }else{
138112               fts3EvalNextRow(pCsr, pRight, pRc);
138113             }
138114           }
138115           pExpr->iDocid = pLeft->iDocid;
138116           pExpr->bEof = (pLeft->bEof || pRight->bEof);
138117           if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
138118             if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
138119               Fts3Doclist *pDl = &pRight->pPhrase->doclist;
138120               while( *pRc==SQLITE_OK && pRight->bEof==0 ){
138121                 memset(pDl->pList, 0, pDl->nList);
138122                 fts3EvalNextRow(pCsr, pRight, pRc);
138123               }
138124             }
138125             if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
138126               Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
138127               while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
138128                 memset(pDl->pList, 0, pDl->nList);
138129                 fts3EvalNextRow(pCsr, pLeft, pRc);
138130               }
138131             }
138132           }
138133         }
138134         break;
138135       }
138136 
138137       case FTSQUERY_OR: {
138138         Fts3Expr *pLeft = pExpr->pLeft;
138139         Fts3Expr *pRight = pExpr->pRight;
138140         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
138141 
138142         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
138143         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
138144 
138145         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
138146           fts3EvalNextRow(pCsr, pLeft, pRc);
138147         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
138148           fts3EvalNextRow(pCsr, pRight, pRc);
138149         }else{
138150           fts3EvalNextRow(pCsr, pLeft, pRc);
138151           fts3EvalNextRow(pCsr, pRight, pRc);
138152         }
138153 
138154         pExpr->bEof = (pLeft->bEof && pRight->bEof);
138155         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
138156         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
138157           pExpr->iDocid = pLeft->iDocid;
138158         }else{
138159           pExpr->iDocid = pRight->iDocid;
138160         }
138161 
138162         break;
138163       }
138164 
138165       case FTSQUERY_NOT: {
138166         Fts3Expr *pLeft = pExpr->pLeft;
138167         Fts3Expr *pRight = pExpr->pRight;
138168 
138169         if( pRight->bStart==0 ){
138170           fts3EvalNextRow(pCsr, pRight, pRc);
138171           assert( *pRc!=SQLITE_OK || pRight->bStart );
138172         }
138173 
138174         fts3EvalNextRow(pCsr, pLeft, pRc);
138175         if( pLeft->bEof==0 ){
138176           while( !*pRc
138177               && !pRight->bEof
138178               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
138179           ){
138180             fts3EvalNextRow(pCsr, pRight, pRc);
138181           }
138182         }
138183         pExpr->iDocid = pLeft->iDocid;
138184         pExpr->bEof = pLeft->bEof;
138185         break;
138186       }
138187 
138188       default: {
138189         Fts3Phrase *pPhrase = pExpr->pPhrase;
138190         fts3EvalInvalidatePoslist(pPhrase);
138191         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
138192         pExpr->iDocid = pPhrase->doclist.iDocid;
138193         break;
138194       }
138195     }
138196   }
138197 }
138198 
138199 /*
138200 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
138201 ** cluster, then this function returns 1 immediately.
138202 **
138203 ** Otherwise, it checks if the current row really does match the NEAR
138204 ** expression, using the data currently stored in the position lists
138205 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
138206 **
138207 ** If the current row is a match, the position list associated with each
138208 ** phrase in the NEAR expression is edited in place to contain only those
138209 ** phrase instances sufficiently close to their peers to satisfy all NEAR
138210 ** constraints. In this case it returns 1. If the NEAR expression does not
138211 ** match the current row, 0 is returned. The position lists may or may not
138212 ** be edited if 0 is returned.
138213 */
138214 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
138215   int res = 1;
138216 
138217   /* The following block runs if pExpr is the root of a NEAR query.
138218   ** For example, the query:
138219   **
138220   **         "w" NEAR "x" NEAR "y" NEAR "z"
138221   **
138222   ** which is represented in tree form as:
138223   **
138224   **                               |
138225   **                          +--NEAR--+      <-- root of NEAR query
138226   **                          |        |
138227   **                     +--NEAR--+   "z"
138228   **                     |        |
138229   **                +--NEAR--+   "y"
138230   **                |        |
138231   **               "w"      "x"
138232   **
138233   ** The right-hand child of a NEAR node is always a phrase. The
138234   ** left-hand child may be either a phrase or a NEAR node. There are
138235   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
138236   */
138237   if( *pRc==SQLITE_OK
138238    && pExpr->eType==FTSQUERY_NEAR
138239    && pExpr->bEof==0
138240    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
138241   ){
138242     Fts3Expr *p;
138243     int nTmp = 0;                 /* Bytes of temp space */
138244     char *aTmp;                   /* Temp space for PoslistNearMerge() */
138245 
138246     /* Allocate temporary working space. */
138247     for(p=pExpr; p->pLeft; p=p->pLeft){
138248       nTmp += p->pRight->pPhrase->doclist.nList;
138249     }
138250     nTmp += p->pPhrase->doclist.nList;
138251     if( nTmp==0 ){
138252       res = 0;
138253     }else{
138254       aTmp = sqlite3_malloc(nTmp*2);
138255       if( !aTmp ){
138256         *pRc = SQLITE_NOMEM;
138257         res = 0;
138258       }else{
138259         char *aPoslist = p->pPhrase->doclist.pList;
138260         int nToken = p->pPhrase->nToken;
138261 
138262         for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
138263           Fts3Phrase *pPhrase = p->pRight->pPhrase;
138264           int nNear = p->nNear;
138265           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
138266         }
138267 
138268         aPoslist = pExpr->pRight->pPhrase->doclist.pList;
138269         nToken = pExpr->pRight->pPhrase->nToken;
138270         for(p=pExpr->pLeft; p && res; p=p->pLeft){
138271           int nNear;
138272           Fts3Phrase *pPhrase;
138273           assert( p->pParent && p->pParent->pLeft==p );
138274           nNear = p->pParent->nNear;
138275           pPhrase = (
138276               p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
138277               );
138278           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
138279         }
138280       }
138281 
138282       sqlite3_free(aTmp);
138283     }
138284   }
138285 
138286   return res;
138287 }
138288 
138289 /*
138290 ** This function is a helper function for fts3EvalTestDeferredAndNear().
138291 ** Assuming no error occurs or has occurred, It returns non-zero if the
138292 ** expression passed as the second argument matches the row that pCsr
138293 ** currently points to, or zero if it does not.
138294 **
138295 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
138296 ** If an error occurs during execution of this function, *pRc is set to
138297 ** the appropriate SQLite error code. In this case the returned value is
138298 ** undefined.
138299 */
138300 static int fts3EvalTestExpr(
138301   Fts3Cursor *pCsr,               /* FTS cursor handle */
138302   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
138303   int *pRc                        /* IN/OUT: Error code */
138304 ){
138305   int bHit = 1;                   /* Return value */
138306   if( *pRc==SQLITE_OK ){
138307     switch( pExpr->eType ){
138308       case FTSQUERY_NEAR:
138309       case FTSQUERY_AND:
138310         bHit = (
138311             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
138312          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
138313          && fts3EvalNearTest(pExpr, pRc)
138314         );
138315 
138316         /* If the NEAR expression does not match any rows, zero the doclist for
138317         ** all phrases involved in the NEAR. This is because the snippet(),
138318         ** offsets() and matchinfo() functions are not supposed to recognize
138319         ** any instances of phrases that are part of unmatched NEAR queries.
138320         ** For example if this expression:
138321         **
138322         **    ... MATCH 'a OR (b NEAR c)'
138323         **
138324         ** is matched against a row containing:
138325         **
138326         **        'a b d e'
138327         **
138328         ** then any snippet() should ony highlight the "a" term, not the "b"
138329         ** (as "b" is part of a non-matching NEAR clause).
138330         */
138331         if( bHit==0
138332          && pExpr->eType==FTSQUERY_NEAR
138333          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
138334         ){
138335           Fts3Expr *p;
138336           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
138337             if( p->pRight->iDocid==pCsr->iPrevId ){
138338               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
138339             }
138340           }
138341           if( p->iDocid==pCsr->iPrevId ){
138342             fts3EvalInvalidatePoslist(p->pPhrase);
138343           }
138344         }
138345 
138346         break;
138347 
138348       case FTSQUERY_OR: {
138349         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
138350         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
138351         bHit = bHit1 || bHit2;
138352         break;
138353       }
138354 
138355       case FTSQUERY_NOT:
138356         bHit = (
138357             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
138358          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
138359         );
138360         break;
138361 
138362       default: {
138363 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
138364         if( pCsr->pDeferred
138365          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
138366         ){
138367           Fts3Phrase *pPhrase = pExpr->pPhrase;
138368           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
138369           if( pExpr->bDeferred ){
138370             fts3EvalInvalidatePoslist(pPhrase);
138371           }
138372           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
138373           bHit = (pPhrase->doclist.pList!=0);
138374           pExpr->iDocid = pCsr->iPrevId;
138375         }else
138376 #endif
138377         {
138378           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
138379         }
138380         break;
138381       }
138382     }
138383   }
138384   return bHit;
138385 }
138386 
138387 /*
138388 ** This function is called as the second part of each xNext operation when
138389 ** iterating through the results of a full-text query. At this point the
138390 ** cursor points to a row that matches the query expression, with the
138391 ** following caveats:
138392 **
138393 **   * Up until this point, "NEAR" operators in the expression have been
138394 **     treated as "AND".
138395 **
138396 **   * Deferred tokens have not yet been considered.
138397 **
138398 ** If *pRc is not SQLITE_OK when this function is called, it immediately
138399 ** returns 0. Otherwise, it tests whether or not after considering NEAR
138400 ** operators and deferred tokens the current row is still a match for the
138401 ** expression. It returns 1 if both of the following are true:
138402 **
138403 **   1. *pRc is SQLITE_OK when this function returns, and
138404 **
138405 **   2. After scanning the current FTS table row for the deferred tokens,
138406 **      it is determined that the row does *not* match the query.
138407 **
138408 ** Or, if no error occurs and it seems the current row does match the FTS
138409 ** query, return 0.
138410 */
138411 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
138412   int rc = *pRc;
138413   int bMiss = 0;
138414   if( rc==SQLITE_OK ){
138415 
138416     /* If there are one or more deferred tokens, load the current row into
138417     ** memory and scan it to determine the position list for each deferred
138418     ** token. Then, see if this row is really a match, considering deferred
138419     ** tokens and NEAR operators (neither of which were taken into account
138420     ** earlier, by fts3EvalNextRow()).
138421     */
138422     if( pCsr->pDeferred ){
138423       rc = fts3CursorSeek(0, pCsr);
138424       if( rc==SQLITE_OK ){
138425         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
138426       }
138427     }
138428     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
138429 
138430     /* Free the position-lists accumulated for each deferred token above. */
138431     sqlite3Fts3FreeDeferredDoclists(pCsr);
138432     *pRc = rc;
138433   }
138434   return (rc==SQLITE_OK && bMiss);
138435 }
138436 
138437 /*
138438 ** Advance to the next document that matches the FTS expression in
138439 ** Fts3Cursor.pExpr.
138440 */
138441 static int fts3EvalNext(Fts3Cursor *pCsr){
138442   int rc = SQLITE_OK;             /* Return Code */
138443   Fts3Expr *pExpr = pCsr->pExpr;
138444   assert( pCsr->isEof==0 );
138445   if( pExpr==0 ){
138446     pCsr->isEof = 1;
138447   }else{
138448     do {
138449       if( pCsr->isRequireSeek==0 ){
138450         sqlite3_reset(pCsr->pStmt);
138451       }
138452       assert( sqlite3_data_count(pCsr->pStmt)==0 );
138453       fts3EvalNextRow(pCsr, pExpr, &rc);
138454       pCsr->isEof = pExpr->bEof;
138455       pCsr->isRequireSeek = 1;
138456       pCsr->isMatchinfoNeeded = 1;
138457       pCsr->iPrevId = pExpr->iDocid;
138458     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
138459   }
138460 
138461   /* Check if the cursor is past the end of the docid range specified
138462   ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
138463   if( rc==SQLITE_OK && (
138464         (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
138465      || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
138466   )){
138467     pCsr->isEof = 1;
138468   }
138469 
138470   return rc;
138471 }
138472 
138473 /*
138474 ** Restart interation for expression pExpr so that the next call to
138475 ** fts3EvalNext() visits the first row. Do not allow incremental
138476 ** loading or merging of phrase doclists for this iteration.
138477 **
138478 ** If *pRc is other than SQLITE_OK when this function is called, it is
138479 ** a no-op. If an error occurs within this function, *pRc is set to an
138480 ** SQLite error code before returning.
138481 */
138482 static void fts3EvalRestart(
138483   Fts3Cursor *pCsr,
138484   Fts3Expr *pExpr,
138485   int *pRc
138486 ){
138487   if( pExpr && *pRc==SQLITE_OK ){
138488     Fts3Phrase *pPhrase = pExpr->pPhrase;
138489 
138490     if( pPhrase ){
138491       fts3EvalInvalidatePoslist(pPhrase);
138492       if( pPhrase->bIncr ){
138493         int i;
138494         for(i=0; i<pPhrase->nToken; i++){
138495           Fts3PhraseToken *pToken = &pPhrase->aToken[i];
138496           assert( pToken->pDeferred==0 );
138497           if( pToken->pSegcsr ){
138498             sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
138499           }
138500         }
138501         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
138502       }
138503       pPhrase->doclist.pNextDocid = 0;
138504       pPhrase->doclist.iDocid = 0;
138505       pPhrase->pOrPoslist = 0;
138506     }
138507 
138508     pExpr->iDocid = 0;
138509     pExpr->bEof = 0;
138510     pExpr->bStart = 0;
138511 
138512     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
138513     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
138514   }
138515 }
138516 
138517 /*
138518 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
138519 ** expression rooted at pExpr, the cursor iterates through all rows matched
138520 ** by pExpr, calling this function for each row. This function increments
138521 ** the values in Fts3Expr.aMI[] according to the position-list currently
138522 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
138523 ** expression nodes.
138524 */
138525 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
138526   if( pExpr ){
138527     Fts3Phrase *pPhrase = pExpr->pPhrase;
138528     if( pPhrase && pPhrase->doclist.pList ){
138529       int iCol = 0;
138530       char *p = pPhrase->doclist.pList;
138531 
138532       assert( *p );
138533       while( 1 ){
138534         u8 c = 0;
138535         int iCnt = 0;
138536         while( 0xFE & (*p | c) ){
138537           if( (c&0x80)==0 ) iCnt++;
138538           c = *p++ & 0x80;
138539         }
138540 
138541         /* aMI[iCol*3 + 1] = Number of occurrences
138542         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
138543         */
138544         pExpr->aMI[iCol*3 + 1] += iCnt;
138545         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
138546         if( *p==0x00 ) break;
138547         p++;
138548         p += fts3GetVarint32(p, &iCol);
138549       }
138550     }
138551 
138552     fts3EvalUpdateCounts(pExpr->pLeft);
138553     fts3EvalUpdateCounts(pExpr->pRight);
138554   }
138555 }
138556 
138557 /*
138558 ** Expression pExpr must be of type FTSQUERY_PHRASE.
138559 **
138560 ** If it is not already allocated and populated, this function allocates and
138561 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
138562 ** of a NEAR expression, then it also allocates and populates the same array
138563 ** for all other phrases that are part of the NEAR expression.
138564 **
138565 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
138566 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
138567 */
138568 static int fts3EvalGatherStats(
138569   Fts3Cursor *pCsr,               /* Cursor object */
138570   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
138571 ){
138572   int rc = SQLITE_OK;             /* Return code */
138573 
138574   assert( pExpr->eType==FTSQUERY_PHRASE );
138575   if( pExpr->aMI==0 ){
138576     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
138577     Fts3Expr *pRoot;                /* Root of NEAR expression */
138578     Fts3Expr *p;                    /* Iterator used for several purposes */
138579 
138580     sqlite3_int64 iPrevId = pCsr->iPrevId;
138581     sqlite3_int64 iDocid;
138582     u8 bEof;
138583 
138584     /* Find the root of the NEAR expression */
138585     pRoot = pExpr;
138586     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
138587       pRoot = pRoot->pParent;
138588     }
138589     iDocid = pRoot->iDocid;
138590     bEof = pRoot->bEof;
138591     assert( pRoot->bStart );
138592 
138593     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
138594     for(p=pRoot; p; p=p->pLeft){
138595       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
138596       assert( pE->aMI==0 );
138597       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
138598       if( !pE->aMI ) return SQLITE_NOMEM;
138599       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
138600     }
138601 
138602     fts3EvalRestart(pCsr, pRoot, &rc);
138603 
138604     while( pCsr->isEof==0 && rc==SQLITE_OK ){
138605 
138606       do {
138607         /* Ensure the %_content statement is reset. */
138608         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
138609         assert( sqlite3_data_count(pCsr->pStmt)==0 );
138610 
138611         /* Advance to the next document */
138612         fts3EvalNextRow(pCsr, pRoot, &rc);
138613         pCsr->isEof = pRoot->bEof;
138614         pCsr->isRequireSeek = 1;
138615         pCsr->isMatchinfoNeeded = 1;
138616         pCsr->iPrevId = pRoot->iDocid;
138617       }while( pCsr->isEof==0
138618            && pRoot->eType==FTSQUERY_NEAR
138619            && fts3EvalTestDeferredAndNear(pCsr, &rc)
138620       );
138621 
138622       if( rc==SQLITE_OK && pCsr->isEof==0 ){
138623         fts3EvalUpdateCounts(pRoot);
138624       }
138625     }
138626 
138627     pCsr->isEof = 0;
138628     pCsr->iPrevId = iPrevId;
138629 
138630     if( bEof ){
138631       pRoot->bEof = bEof;
138632     }else{
138633       /* Caution: pRoot may iterate through docids in ascending or descending
138634       ** order. For this reason, even though it seems more defensive, the
138635       ** do loop can not be written:
138636       **
138637       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
138638       */
138639       fts3EvalRestart(pCsr, pRoot, &rc);
138640       do {
138641         fts3EvalNextRow(pCsr, pRoot, &rc);
138642         assert( pRoot->bEof==0 );
138643       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
138644       fts3EvalTestDeferredAndNear(pCsr, &rc);
138645     }
138646   }
138647   return rc;
138648 }
138649 
138650 /*
138651 ** This function is used by the matchinfo() module to query a phrase
138652 ** expression node for the following information:
138653 **
138654 **   1. The total number of occurrences of the phrase in each column of
138655 **      the FTS table (considering all rows), and
138656 **
138657 **   2. For each column, the number of rows in the table for which the
138658 **      column contains at least one instance of the phrase.
138659 **
138660 ** If no error occurs, SQLITE_OK is returned and the values for each column
138661 ** written into the array aiOut as follows:
138662 **
138663 **   aiOut[iCol*3 + 1] = Number of occurrences
138664 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
138665 **
138666 ** Caveats:
138667 **
138668 **   * If a phrase consists entirely of deferred tokens, then all output
138669 **     values are set to the number of documents in the table. In other
138670 **     words we assume that very common tokens occur exactly once in each
138671 **     column of each row of the table.
138672 **
138673 **   * If a phrase contains some deferred tokens (and some non-deferred
138674 **     tokens), count the potential occurrence identified by considering
138675 **     the non-deferred tokens instead of actual phrase occurrences.
138676 **
138677 **   * If the phrase is part of a NEAR expression, then only phrase instances
138678 **     that meet the NEAR constraint are included in the counts.
138679 */
138680 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
138681   Fts3Cursor *pCsr,               /* FTS cursor handle */
138682   Fts3Expr *pExpr,                /* Phrase expression */
138683   u32 *aiOut                      /* Array to write results into (see above) */
138684 ){
138685   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
138686   int rc = SQLITE_OK;
138687   int iCol;
138688 
138689   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
138690     assert( pCsr->nDoc>0 );
138691     for(iCol=0; iCol<pTab->nColumn; iCol++){
138692       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
138693       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
138694     }
138695   }else{
138696     rc = fts3EvalGatherStats(pCsr, pExpr);
138697     if( rc==SQLITE_OK ){
138698       assert( pExpr->aMI );
138699       for(iCol=0; iCol<pTab->nColumn; iCol++){
138700         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
138701         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
138702       }
138703     }
138704   }
138705 
138706   return rc;
138707 }
138708 
138709 /*
138710 ** The expression pExpr passed as the second argument to this function
138711 ** must be of type FTSQUERY_PHRASE.
138712 **
138713 ** The returned value is either NULL or a pointer to a buffer containing
138714 ** a position-list indicating the occurrences of the phrase in column iCol
138715 ** of the current row.
138716 **
138717 ** More specifically, the returned buffer contains 1 varint for each
138718 ** occurrence of the phrase in the column, stored using the normal (delta+2)
138719 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
138720 ** if the requested column contains "a b X c d X X" and the position-list
138721 ** for 'X' is requested, the buffer returned may contain:
138722 **
138723 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
138724 **
138725 ** This function works regardless of whether or not the phrase is deferred,
138726 ** incremental, or neither.
138727 */
138728 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
138729   Fts3Cursor *pCsr,               /* FTS3 cursor object */
138730   Fts3Expr *pExpr,                /* Phrase to return doclist for */
138731   int iCol,                       /* Column to return position list for */
138732   char **ppOut                    /* OUT: Pointer to position list */
138733 ){
138734   Fts3Phrase *pPhrase = pExpr->pPhrase;
138735   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
138736   char *pIter;
138737   int iThis;
138738   sqlite3_int64 iDocid;
138739 
138740   /* If this phrase is applies specifically to some column other than
138741   ** column iCol, return a NULL pointer.  */
138742   *ppOut = 0;
138743   assert( iCol>=0 && iCol<pTab->nColumn );
138744   if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
138745     return SQLITE_OK;
138746   }
138747 
138748   iDocid = pExpr->iDocid;
138749   pIter = pPhrase->doclist.pList;
138750   if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
138751     int rc = SQLITE_OK;
138752     int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
138753     int bOr = 0;
138754     u8 bEof = 0;
138755     u8 bTreeEof = 0;
138756     Fts3Expr *p;                  /* Used to iterate from pExpr to root */
138757     Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
138758 
138759     /* Check if this phrase descends from an OR expression node. If not,
138760     ** return NULL. Otherwise, the entry that corresponds to docid
138761     ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
138762     ** tree that the node is part of has been marked as EOF, but the node
138763     ** itself is not EOF, then it may point to an earlier entry. */
138764     pNear = pExpr;
138765     for(p=pExpr->pParent; p; p=p->pParent){
138766       if( p->eType==FTSQUERY_OR ) bOr = 1;
138767       if( p->eType==FTSQUERY_NEAR ) pNear = p;
138768       if( p->bEof ) bTreeEof = 1;
138769     }
138770     if( bOr==0 ) return SQLITE_OK;
138771 
138772     /* This is the descendent of an OR node. In this case we cannot use
138773     ** an incremental phrase. Load the entire doclist for the phrase
138774     ** into memory in this case.  */
138775     if( pPhrase->bIncr ){
138776       int bEofSave = pNear->bEof;
138777       fts3EvalRestart(pCsr, pNear, &rc);
138778       while( rc==SQLITE_OK && !pNear->bEof ){
138779         fts3EvalNextRow(pCsr, pNear, &rc);
138780         if( bEofSave==0 && pNear->iDocid==iDocid ) break;
138781       }
138782       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
138783     }
138784     if( bTreeEof ){
138785       while( rc==SQLITE_OK && !pNear->bEof ){
138786         fts3EvalNextRow(pCsr, pNear, &rc);
138787       }
138788     }
138789     if( rc!=SQLITE_OK ) return rc;
138790 
138791     pIter = pPhrase->pOrPoslist;
138792     iDocid = pPhrase->iOrDocid;
138793     if( pCsr->bDesc==bDescDoclist ){
138794       bEof = !pPhrase->doclist.nAll ||
138795                  (pIter >= (pPhrase->doclist.aAll + pPhrase->doclist.nAll));
138796       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
138797         sqlite3Fts3DoclistNext(
138798             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
138799             &pIter, &iDocid, &bEof
138800         );
138801       }
138802     }else{
138803       bEof = !pPhrase->doclist.nAll || (pIter && pIter<=pPhrase->doclist.aAll);
138804       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
138805         int dummy;
138806         sqlite3Fts3DoclistPrev(
138807             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
138808             &pIter, &iDocid, &dummy, &bEof
138809         );
138810       }
138811     }
138812     pPhrase->pOrPoslist = pIter;
138813     pPhrase->iOrDocid = iDocid;
138814 
138815     if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
138816   }
138817   if( pIter==0 ) return SQLITE_OK;
138818 
138819   if( *pIter==0x01 ){
138820     pIter++;
138821     pIter += fts3GetVarint32(pIter, &iThis);
138822   }else{
138823     iThis = 0;
138824   }
138825   while( iThis<iCol ){
138826     fts3ColumnlistCopy(0, &pIter);
138827     if( *pIter==0x00 ) return SQLITE_OK;
138828     pIter++;
138829     pIter += fts3GetVarint32(pIter, &iThis);
138830   }
138831   if( *pIter==0x00 ){
138832     pIter = 0;
138833   }
138834 
138835   *ppOut = ((iCol==iThis)?pIter:0);
138836   return SQLITE_OK;
138837 }
138838 
138839 /*
138840 ** Free all components of the Fts3Phrase structure that were allocated by
138841 ** the eval module. Specifically, this means to free:
138842 **
138843 **   * the contents of pPhrase->doclist, and
138844 **   * any Fts3MultiSegReader objects held by phrase tokens.
138845 */
138846 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
138847   if( pPhrase ){
138848     int i;
138849     sqlite3_free(pPhrase->doclist.aAll);
138850     fts3EvalInvalidatePoslist(pPhrase);
138851     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
138852     for(i=0; i<pPhrase->nToken; i++){
138853       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
138854       pPhrase->aToken[i].pSegcsr = 0;
138855     }
138856   }
138857 }
138858 
138859 
138860 /*
138861 ** Return SQLITE_CORRUPT_VTAB.
138862 */
138863 #ifdef SQLITE_DEBUG
138864 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
138865   return SQLITE_CORRUPT_VTAB;
138866 }
138867 #endif
138868 
138869 #if !SQLITE_CORE
138870 /*
138871 ** Initialize API pointer table, if required.
138872 */
138873 #ifdef _WIN32
138874 __declspec(dllexport)
138875 #endif
138876 SQLITE_API int SQLITE_STDCALL sqlite3_fts3_init(
138877   sqlite3 *db,
138878   char **pzErrMsg,
138879   const sqlite3_api_routines *pApi
138880 ){
138881   SQLITE_EXTENSION_INIT2(pApi)
138882   return sqlite3Fts3Init(db);
138883 }
138884 #endif
138885 
138886 #endif
138887 
138888 /************** End of fts3.c ************************************************/
138889 /************** Begin file fts3_aux.c ****************************************/
138890 /*
138891 ** 2011 Jan 27
138892 **
138893 ** The author disclaims copyright to this source code.  In place of
138894 ** a legal notice, here is a blessing:
138895 **
138896 **    May you do good and not evil.
138897 **    May you find forgiveness for yourself and forgive others.
138898 **    May you share freely, never taking more than you give.
138899 **
138900 ******************************************************************************
138901 **
138902 */
138903 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
138904 
138905 /* #include <string.h> */
138906 /* #include <assert.h> */
138907 
138908 typedef struct Fts3auxTable Fts3auxTable;
138909 typedef struct Fts3auxCursor Fts3auxCursor;
138910 
138911 struct Fts3auxTable {
138912   sqlite3_vtab base;              /* Base class used by SQLite core */
138913   Fts3Table *pFts3Tab;
138914 };
138915 
138916 struct Fts3auxCursor {
138917   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
138918   Fts3MultiSegReader csr;        /* Must be right after "base" */
138919   Fts3SegFilter filter;
138920   char *zStop;
138921   int nStop;                      /* Byte-length of string zStop */
138922   int iLangid;                    /* Language id to query */
138923   int isEof;                      /* True if cursor is at EOF */
138924   sqlite3_int64 iRowid;           /* Current rowid */
138925 
138926   int iCol;                       /* Current value of 'col' column */
138927   int nStat;                      /* Size of aStat[] array */
138928   struct Fts3auxColstats {
138929     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
138930     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
138931   } *aStat;
138932 };
138933 
138934 /*
138935 ** Schema of the terms table.
138936 */
138937 #define FTS3_AUX_SCHEMA \
138938   "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
138939 
138940 /*
138941 ** This function does all the work for both the xConnect and xCreate methods.
138942 ** These tables have no persistent representation of their own, so xConnect
138943 ** and xCreate are identical operations.
138944 */
138945 static int fts3auxConnectMethod(
138946   sqlite3 *db,                    /* Database connection */
138947   void *pUnused,                  /* Unused */
138948   int argc,                       /* Number of elements in argv array */
138949   const char * const *argv,       /* xCreate/xConnect argument array */
138950   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
138951   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
138952 ){
138953   char const *zDb;                /* Name of database (e.g. "main") */
138954   char const *zFts3;              /* Name of fts3 table */
138955   int nDb;                        /* Result of strlen(zDb) */
138956   int nFts3;                      /* Result of strlen(zFts3) */
138957   int nByte;                      /* Bytes of space to allocate here */
138958   int rc;                         /* value returned by declare_vtab() */
138959   Fts3auxTable *p;                /* Virtual table object to return */
138960 
138961   UNUSED_PARAMETER(pUnused);
138962 
138963   /* The user should invoke this in one of two forms:
138964   **
138965   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
138966   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
138967   */
138968   if( argc!=4 && argc!=5 ) goto bad_args;
138969 
138970   zDb = argv[1];
138971   nDb = (int)strlen(zDb);
138972   if( argc==5 ){
138973     if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
138974       zDb = argv[3];
138975       nDb = (int)strlen(zDb);
138976       zFts3 = argv[4];
138977     }else{
138978       goto bad_args;
138979     }
138980   }else{
138981     zFts3 = argv[3];
138982   }
138983   nFts3 = (int)strlen(zFts3);
138984 
138985   rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
138986   if( rc!=SQLITE_OK ) return rc;
138987 
138988   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
138989   p = (Fts3auxTable *)sqlite3_malloc(nByte);
138990   if( !p ) return SQLITE_NOMEM;
138991   memset(p, 0, nByte);
138992 
138993   p->pFts3Tab = (Fts3Table *)&p[1];
138994   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
138995   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
138996   p->pFts3Tab->db = db;
138997   p->pFts3Tab->nIndex = 1;
138998 
138999   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
139000   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
139001   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
139002 
139003   *ppVtab = (sqlite3_vtab *)p;
139004   return SQLITE_OK;
139005 
139006  bad_args:
139007   sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
139008   return SQLITE_ERROR;
139009 }
139010 
139011 /*
139012 ** This function does the work for both the xDisconnect and xDestroy methods.
139013 ** These tables have no persistent representation of their own, so xDisconnect
139014 ** and xDestroy are identical operations.
139015 */
139016 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
139017   Fts3auxTable *p = (Fts3auxTable *)pVtab;
139018   Fts3Table *pFts3 = p->pFts3Tab;
139019   int i;
139020 
139021   /* Free any prepared statements held */
139022   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
139023     sqlite3_finalize(pFts3->aStmt[i]);
139024   }
139025   sqlite3_free(pFts3->zSegmentsTbl);
139026   sqlite3_free(p);
139027   return SQLITE_OK;
139028 }
139029 
139030 #define FTS4AUX_EQ_CONSTRAINT 1
139031 #define FTS4AUX_GE_CONSTRAINT 2
139032 #define FTS4AUX_LE_CONSTRAINT 4
139033 
139034 /*
139035 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
139036 */
139037 static int fts3auxBestIndexMethod(
139038   sqlite3_vtab *pVTab,
139039   sqlite3_index_info *pInfo
139040 ){
139041   int i;
139042   int iEq = -1;
139043   int iGe = -1;
139044   int iLe = -1;
139045   int iLangid = -1;
139046   int iNext = 1;                  /* Next free argvIndex value */
139047 
139048   UNUSED_PARAMETER(pVTab);
139049 
139050   /* This vtab delivers always results in "ORDER BY term ASC" order. */
139051   if( pInfo->nOrderBy==1
139052    && pInfo->aOrderBy[0].iColumn==0
139053    && pInfo->aOrderBy[0].desc==0
139054   ){
139055     pInfo->orderByConsumed = 1;
139056   }
139057 
139058   /* Search for equality and range constraints on the "term" column.
139059   ** And equality constraints on the hidden "languageid" column. */
139060   for(i=0; i<pInfo->nConstraint; i++){
139061     if( pInfo->aConstraint[i].usable ){
139062       int op = pInfo->aConstraint[i].op;
139063       int iCol = pInfo->aConstraint[i].iColumn;
139064 
139065       if( iCol==0 ){
139066         if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
139067         if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
139068         if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
139069         if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
139070         if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
139071       }
139072       if( iCol==4 ){
139073         if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
139074       }
139075     }
139076   }
139077 
139078   if( iEq>=0 ){
139079     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
139080     pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
139081     pInfo->estimatedCost = 5;
139082   }else{
139083     pInfo->idxNum = 0;
139084     pInfo->estimatedCost = 20000;
139085     if( iGe>=0 ){
139086       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
139087       pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
139088       pInfo->estimatedCost /= 2;
139089     }
139090     if( iLe>=0 ){
139091       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
139092       pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
139093       pInfo->estimatedCost /= 2;
139094     }
139095   }
139096   if( iLangid>=0 ){
139097     pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
139098     pInfo->estimatedCost--;
139099   }
139100 
139101   return SQLITE_OK;
139102 }
139103 
139104 /*
139105 ** xOpen - Open a cursor.
139106 */
139107 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
139108   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
139109 
139110   UNUSED_PARAMETER(pVTab);
139111 
139112   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
139113   if( !pCsr ) return SQLITE_NOMEM;
139114   memset(pCsr, 0, sizeof(Fts3auxCursor));
139115 
139116   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
139117   return SQLITE_OK;
139118 }
139119 
139120 /*
139121 ** xClose - Close a cursor.
139122 */
139123 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
139124   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
139125   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
139126 
139127   sqlite3Fts3SegmentsClose(pFts3);
139128   sqlite3Fts3SegReaderFinish(&pCsr->csr);
139129   sqlite3_free((void *)pCsr->filter.zTerm);
139130   sqlite3_free(pCsr->zStop);
139131   sqlite3_free(pCsr->aStat);
139132   sqlite3_free(pCsr);
139133   return SQLITE_OK;
139134 }
139135 
139136 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
139137   if( nSize>pCsr->nStat ){
139138     struct Fts3auxColstats *aNew;
139139     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
139140         sizeof(struct Fts3auxColstats) * nSize
139141     );
139142     if( aNew==0 ) return SQLITE_NOMEM;
139143     memset(&aNew[pCsr->nStat], 0,
139144         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
139145     );
139146     pCsr->aStat = aNew;
139147     pCsr->nStat = nSize;
139148   }
139149   return SQLITE_OK;
139150 }
139151 
139152 /*
139153 ** xNext - Advance the cursor to the next row, if any.
139154 */
139155 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
139156   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
139157   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
139158   int rc;
139159 
139160   /* Increment our pretend rowid value. */
139161   pCsr->iRowid++;
139162 
139163   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
139164     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
139165   }
139166 
139167   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
139168   if( rc==SQLITE_ROW ){
139169     int i = 0;
139170     int nDoclist = pCsr->csr.nDoclist;
139171     char *aDoclist = pCsr->csr.aDoclist;
139172     int iCol;
139173 
139174     int eState = 0;
139175 
139176     if( pCsr->zStop ){
139177       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
139178       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
139179       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
139180         pCsr->isEof = 1;
139181         return SQLITE_OK;
139182       }
139183     }
139184 
139185     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
139186     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
139187     iCol = 0;
139188 
139189     while( i<nDoclist ){
139190       sqlite3_int64 v = 0;
139191 
139192       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
139193       switch( eState ){
139194         /* State 0. In this state the integer just read was a docid. */
139195         case 0:
139196           pCsr->aStat[0].nDoc++;
139197           eState = 1;
139198           iCol = 0;
139199           break;
139200 
139201         /* State 1. In this state we are expecting either a 1, indicating
139202         ** that the following integer will be a column number, or the
139203         ** start of a position list for column 0.
139204         **
139205         ** The only difference between state 1 and state 2 is that if the
139206         ** integer encountered in state 1 is not 0 or 1, then we need to
139207         ** increment the column 0 "nDoc" count for this term.
139208         */
139209         case 1:
139210           assert( iCol==0 );
139211           if( v>1 ){
139212             pCsr->aStat[1].nDoc++;
139213           }
139214           eState = 2;
139215           /* fall through */
139216 
139217         case 2:
139218           if( v==0 ){       /* 0x00. Next integer will be a docid. */
139219             eState = 0;
139220           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
139221             eState = 3;
139222           }else{            /* 2 or greater. A position. */
139223             pCsr->aStat[iCol+1].nOcc++;
139224             pCsr->aStat[0].nOcc++;
139225           }
139226           break;
139227 
139228         /* State 3. The integer just read is a column number. */
139229         default: assert( eState==3 );
139230           iCol = (int)v;
139231           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
139232           pCsr->aStat[iCol+1].nDoc++;
139233           eState = 2;
139234           break;
139235       }
139236     }
139237 
139238     pCsr->iCol = 0;
139239     rc = SQLITE_OK;
139240   }else{
139241     pCsr->isEof = 1;
139242   }
139243   return rc;
139244 }
139245 
139246 /*
139247 ** xFilter - Initialize a cursor to point at the start of its data.
139248 */
139249 static int fts3auxFilterMethod(
139250   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
139251   int idxNum,                     /* Strategy index */
139252   const char *idxStr,             /* Unused */
139253   int nVal,                       /* Number of elements in apVal */
139254   sqlite3_value **apVal           /* Arguments for the indexing scheme */
139255 ){
139256   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
139257   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
139258   int rc;
139259   int isScan = 0;
139260   int iLangVal = 0;               /* Language id to query */
139261 
139262   int iEq = -1;                   /* Index of term=? value in apVal */
139263   int iGe = -1;                   /* Index of term>=? value in apVal */
139264   int iLe = -1;                   /* Index of term<=? value in apVal */
139265   int iLangid = -1;               /* Index of languageid=? value in apVal */
139266   int iNext = 0;
139267 
139268   UNUSED_PARAMETER(nVal);
139269   UNUSED_PARAMETER(idxStr);
139270 
139271   assert( idxStr==0 );
139272   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
139273        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
139274        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
139275   );
139276 
139277   if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
139278     iEq = iNext++;
139279   }else{
139280     isScan = 1;
139281     if( idxNum & FTS4AUX_GE_CONSTRAINT ){
139282       iGe = iNext++;
139283     }
139284     if( idxNum & FTS4AUX_LE_CONSTRAINT ){
139285       iLe = iNext++;
139286     }
139287   }
139288   if( iNext<nVal ){
139289     iLangid = iNext++;
139290   }
139291 
139292   /* In case this cursor is being reused, close and zero it. */
139293   testcase(pCsr->filter.zTerm);
139294   sqlite3Fts3SegReaderFinish(&pCsr->csr);
139295   sqlite3_free((void *)pCsr->filter.zTerm);
139296   sqlite3_free(pCsr->aStat);
139297   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
139298 
139299   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
139300   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
139301 
139302   if( iEq>=0 || iGe>=0 ){
139303     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
139304     assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
139305     if( zStr ){
139306       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
139307       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
139308       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
139309     }
139310   }
139311 
139312   if( iLe>=0 ){
139313     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
139314     pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
139315     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
139316   }
139317 
139318   if( iLangid>=0 ){
139319     iLangVal = sqlite3_value_int(apVal[iLangid]);
139320 
139321     /* If the user specified a negative value for the languageid, use zero
139322     ** instead. This works, as the "languageid=?" constraint will also
139323     ** be tested by the VDBE layer. The test will always be false (since
139324     ** this module will not return a row with a negative languageid), and
139325     ** so the overall query will return zero rows.  */
139326     if( iLangVal<0 ) iLangVal = 0;
139327   }
139328   pCsr->iLangid = iLangVal;
139329 
139330   rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
139331       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
139332   );
139333   if( rc==SQLITE_OK ){
139334     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
139335   }
139336 
139337   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
139338   return rc;
139339 }
139340 
139341 /*
139342 ** xEof - Return true if the cursor is at EOF, or false otherwise.
139343 */
139344 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
139345   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
139346   return pCsr->isEof;
139347 }
139348 
139349 /*
139350 ** xColumn - Return a column value.
139351 */
139352 static int fts3auxColumnMethod(
139353   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
139354   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
139355   int iCol                        /* Index of column to read value from */
139356 ){
139357   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
139358 
139359   assert( p->isEof==0 );
139360   switch( iCol ){
139361     case 0: /* term */
139362       sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
139363       break;
139364 
139365     case 1: /* col */
139366       if( p->iCol ){
139367         sqlite3_result_int(pCtx, p->iCol-1);
139368       }else{
139369         sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
139370       }
139371       break;
139372 
139373     case 2: /* documents */
139374       sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
139375       break;
139376 
139377     case 3: /* occurrences */
139378       sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
139379       break;
139380 
139381     default: /* languageid */
139382       assert( iCol==4 );
139383       sqlite3_result_int(pCtx, p->iLangid);
139384       break;
139385   }
139386 
139387   return SQLITE_OK;
139388 }
139389 
139390 /*
139391 ** xRowid - Return the current rowid for the cursor.
139392 */
139393 static int fts3auxRowidMethod(
139394   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
139395   sqlite_int64 *pRowid            /* OUT: Rowid value */
139396 ){
139397   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
139398   *pRowid = pCsr->iRowid;
139399   return SQLITE_OK;
139400 }
139401 
139402 /*
139403 ** Register the fts3aux module with database connection db. Return SQLITE_OK
139404 ** if successful or an error code if sqlite3_create_module() fails.
139405 */
139406 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
139407   static const sqlite3_module fts3aux_module = {
139408      0,                           /* iVersion      */
139409      fts3auxConnectMethod,        /* xCreate       */
139410      fts3auxConnectMethod,        /* xConnect      */
139411      fts3auxBestIndexMethod,      /* xBestIndex    */
139412      fts3auxDisconnectMethod,     /* xDisconnect   */
139413      fts3auxDisconnectMethod,     /* xDestroy      */
139414      fts3auxOpenMethod,           /* xOpen         */
139415      fts3auxCloseMethod,          /* xClose        */
139416      fts3auxFilterMethod,         /* xFilter       */
139417      fts3auxNextMethod,           /* xNext         */
139418      fts3auxEofMethod,            /* xEof          */
139419      fts3auxColumnMethod,         /* xColumn       */
139420      fts3auxRowidMethod,          /* xRowid        */
139421      0,                           /* xUpdate       */
139422      0,                           /* xBegin        */
139423      0,                           /* xSync         */
139424      0,                           /* xCommit       */
139425      0,                           /* xRollback     */
139426      0,                           /* xFindFunction */
139427      0,                           /* xRename       */
139428      0,                           /* xSavepoint    */
139429      0,                           /* xRelease      */
139430      0                            /* xRollbackTo   */
139431   };
139432   int rc;                         /* Return code */
139433 
139434   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
139435   return rc;
139436 }
139437 
139438 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
139439 
139440 /************** End of fts3_aux.c ********************************************/
139441 /************** Begin file fts3_expr.c ***************************************/
139442 /*
139443 ** 2008 Nov 28
139444 **
139445 ** The author disclaims copyright to this source code.  In place of
139446 ** a legal notice, here is a blessing:
139447 **
139448 **    May you do good and not evil.
139449 **    May you find forgiveness for yourself and forgive others.
139450 **    May you share freely, never taking more than you give.
139451 **
139452 ******************************************************************************
139453 **
139454 ** This module contains code that implements a parser for fts3 query strings
139455 ** (the right-hand argument to the MATCH operator). Because the supported
139456 ** syntax is relatively simple, the whole tokenizer/parser system is
139457 ** hand-coded.
139458 */
139459 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
139460 
139461 /*
139462 ** By default, this module parses the legacy syntax that has been
139463 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
139464 ** is defined, then it uses the new syntax. The differences between
139465 ** the new and the old syntaxes are:
139466 **
139467 **  a) The new syntax supports parenthesis. The old does not.
139468 **
139469 **  b) The new syntax supports the AND and NOT operators. The old does not.
139470 **
139471 **  c) The old syntax supports the "-" token qualifier. This is not
139472 **     supported by the new syntax (it is replaced by the NOT operator).
139473 **
139474 **  d) When using the old syntax, the OR operator has a greater precedence
139475 **     than an implicit AND. When using the new, both implicity and explicit
139476 **     AND operators have a higher precedence than OR.
139477 **
139478 ** If compiled with SQLITE_TEST defined, then this module exports the
139479 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
139480 ** to zero causes the module to use the old syntax. If it is set to
139481 ** non-zero the new syntax is activated. This is so both syntaxes can
139482 ** be tested using a single build of testfixture.
139483 **
139484 ** The following describes the syntax supported by the fts3 MATCH
139485 ** operator in a similar format to that used by the lemon parser
139486 ** generator. This module does not use actually lemon, it uses a
139487 ** custom parser.
139488 **
139489 **   query ::= andexpr (OR andexpr)*.
139490 **
139491 **   andexpr ::= notexpr (AND? notexpr)*.
139492 **
139493 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
139494 **   notexpr ::= LP query RP.
139495 **
139496 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
139497 **
139498 **   distance_opt ::= .
139499 **   distance_opt ::= / INTEGER.
139500 **
139501 **   phrase ::= TOKEN.
139502 **   phrase ::= COLUMN:TOKEN.
139503 **   phrase ::= "TOKEN TOKEN TOKEN...".
139504 */
139505 
139506 #ifdef SQLITE_TEST
139507 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
139508 #else
139509 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
139510 #  define sqlite3_fts3_enable_parentheses 1
139511 # else
139512 #  define sqlite3_fts3_enable_parentheses 0
139513 # endif
139514 #endif
139515 
139516 /*
139517 ** Default span for NEAR operators.
139518 */
139519 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
139520 
139521 /* #include <string.h> */
139522 /* #include <assert.h> */
139523 
139524 /*
139525 ** isNot:
139526 **   This variable is used by function getNextNode(). When getNextNode() is
139527 **   called, it sets ParseContext.isNot to true if the 'next node' is a
139528 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
139529 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
139530 **   zero.
139531 */
139532 typedef struct ParseContext ParseContext;
139533 struct ParseContext {
139534   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
139535   int iLangid;                        /* Language id used with tokenizer */
139536   const char **azCol;                 /* Array of column names for fts3 table */
139537   int bFts4;                          /* True to allow FTS4-only syntax */
139538   int nCol;                           /* Number of entries in azCol[] */
139539   int iDefaultCol;                    /* Default column to query */
139540   int isNot;                          /* True if getNextNode() sees a unary - */
139541   sqlite3_context *pCtx;              /* Write error message here */
139542   int nNest;                          /* Number of nested brackets */
139543 };
139544 
139545 /*
139546 ** This function is equivalent to the standard isspace() function.
139547 **
139548 ** The standard isspace() can be awkward to use safely, because although it
139549 ** is defined to accept an argument of type int, its behavior when passed
139550 ** an integer that falls outside of the range of the unsigned char type
139551 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
139552 ** is defined to accept an argument of type char, and always returns 0 for
139553 ** any values that fall outside of the range of the unsigned char type (i.e.
139554 ** negative values).
139555 */
139556 static int fts3isspace(char c){
139557   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
139558 }
139559 
139560 /*
139561 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
139562 ** zero the memory before returning a pointer to it. If unsuccessful,
139563 ** return NULL.
139564 */
139565 static void *fts3MallocZero(int nByte){
139566   void *pRet = sqlite3_malloc(nByte);
139567   if( pRet ) memset(pRet, 0, nByte);
139568   return pRet;
139569 }
139570 
139571 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
139572   sqlite3_tokenizer *pTokenizer,
139573   int iLangid,
139574   const char *z,
139575   int n,
139576   sqlite3_tokenizer_cursor **ppCsr
139577 ){
139578   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
139579   sqlite3_tokenizer_cursor *pCsr = 0;
139580   int rc;
139581 
139582   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
139583   assert( rc==SQLITE_OK || pCsr==0 );
139584   if( rc==SQLITE_OK ){
139585     pCsr->pTokenizer = pTokenizer;
139586     if( pModule->iVersion>=1 ){
139587       rc = pModule->xLanguageid(pCsr, iLangid);
139588       if( rc!=SQLITE_OK ){
139589         pModule->xClose(pCsr);
139590         pCsr = 0;
139591       }
139592     }
139593   }
139594   *ppCsr = pCsr;
139595   return rc;
139596 }
139597 
139598 /*
139599 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
139600 ** call fts3ExprParse(). So this forward declaration is required.
139601 */
139602 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
139603 
139604 /*
139605 ** Extract the next token from buffer z (length n) using the tokenizer
139606 ** and other information (column names etc.) in pParse. Create an Fts3Expr
139607 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
139608 ** single token and set *ppExpr to point to it. If the end of the buffer is
139609 ** reached before a token is found, set *ppExpr to zero. It is the
139610 ** responsibility of the caller to eventually deallocate the allocated
139611 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
139612 **
139613 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
139614 ** fails.
139615 */
139616 static int getNextToken(
139617   ParseContext *pParse,                   /* fts3 query parse context */
139618   int iCol,                               /* Value for Fts3Phrase.iColumn */
139619   const char *z, int n,                   /* Input string */
139620   Fts3Expr **ppExpr,                      /* OUT: expression */
139621   int *pnConsumed                         /* OUT: Number of bytes consumed */
139622 ){
139623   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
139624   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
139625   int rc;
139626   sqlite3_tokenizer_cursor *pCursor;
139627   Fts3Expr *pRet = 0;
139628   int i = 0;
139629 
139630   /* Set variable i to the maximum number of bytes of input to tokenize. */
139631   for(i=0; i<n; i++){
139632     if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
139633     if( z[i]=='"' ) break;
139634   }
139635 
139636   *pnConsumed = i;
139637   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
139638   if( rc==SQLITE_OK ){
139639     const char *zToken;
139640     int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
139641     int nByte;                               /* total space to allocate */
139642 
139643     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
139644     if( rc==SQLITE_OK ){
139645       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
139646       pRet = (Fts3Expr *)fts3MallocZero(nByte);
139647       if( !pRet ){
139648         rc = SQLITE_NOMEM;
139649       }else{
139650         pRet->eType = FTSQUERY_PHRASE;
139651         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
139652         pRet->pPhrase->nToken = 1;
139653         pRet->pPhrase->iColumn = iCol;
139654         pRet->pPhrase->aToken[0].n = nToken;
139655         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
139656         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
139657 
139658         if( iEnd<n && z[iEnd]=='*' ){
139659           pRet->pPhrase->aToken[0].isPrefix = 1;
139660           iEnd++;
139661         }
139662 
139663         while( 1 ){
139664           if( !sqlite3_fts3_enable_parentheses
139665            && iStart>0 && z[iStart-1]=='-'
139666           ){
139667             pParse->isNot = 1;
139668             iStart--;
139669           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
139670             pRet->pPhrase->aToken[0].bFirst = 1;
139671             iStart--;
139672           }else{
139673             break;
139674           }
139675         }
139676 
139677       }
139678       *pnConsumed = iEnd;
139679     }else if( i && rc==SQLITE_DONE ){
139680       rc = SQLITE_OK;
139681     }
139682 
139683     pModule->xClose(pCursor);
139684   }
139685 
139686   *ppExpr = pRet;
139687   return rc;
139688 }
139689 
139690 
139691 /*
139692 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
139693 ** then free the old allocation.
139694 */
139695 static void *fts3ReallocOrFree(void *pOrig, int nNew){
139696   void *pRet = sqlite3_realloc(pOrig, nNew);
139697   if( !pRet ){
139698     sqlite3_free(pOrig);
139699   }
139700   return pRet;
139701 }
139702 
139703 /*
139704 ** Buffer zInput, length nInput, contains the contents of a quoted string
139705 ** that appeared as part of an fts3 query expression. Neither quote character
139706 ** is included in the buffer. This function attempts to tokenize the entire
139707 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
139708 ** containing the results.
139709 **
139710 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
139711 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
139712 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
139713 ** to 0.
139714 */
139715 static int getNextString(
139716   ParseContext *pParse,                   /* fts3 query parse context */
139717   const char *zInput, int nInput,         /* Input string */
139718   Fts3Expr **ppExpr                       /* OUT: expression */
139719 ){
139720   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
139721   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
139722   int rc;
139723   Fts3Expr *p = 0;
139724   sqlite3_tokenizer_cursor *pCursor = 0;
139725   char *zTemp = 0;
139726   int nTemp = 0;
139727 
139728   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
139729   int nToken = 0;
139730 
139731   /* The final Fts3Expr data structure, including the Fts3Phrase,
139732   ** Fts3PhraseToken structures token buffers are all stored as a single
139733   ** allocation so that the expression can be freed with a single call to
139734   ** sqlite3_free(). Setting this up requires a two pass approach.
139735   **
139736   ** The first pass, in the block below, uses a tokenizer cursor to iterate
139737   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
139738   ** to assemble data in two dynamic buffers:
139739   **
139740   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
139741   **             structure, followed by the array of Fts3PhraseToken
139742   **             structures. This pass only populates the Fts3PhraseToken array.
139743   **
139744   **   Buffer zTemp: Contains copies of all tokens.
139745   **
139746   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
139747   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
139748   ** structures.
139749   */
139750   rc = sqlite3Fts3OpenTokenizer(
139751       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
139752   if( rc==SQLITE_OK ){
139753     int ii;
139754     for(ii=0; rc==SQLITE_OK; ii++){
139755       const char *zByte;
139756       int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
139757       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
139758       if( rc==SQLITE_OK ){
139759         Fts3PhraseToken *pToken;
139760 
139761         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
139762         if( !p ) goto no_mem;
139763 
139764         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
139765         if( !zTemp ) goto no_mem;
139766 
139767         assert( nToken==ii );
139768         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
139769         memset(pToken, 0, sizeof(Fts3PhraseToken));
139770 
139771         memcpy(&zTemp[nTemp], zByte, nByte);
139772         nTemp += nByte;
139773 
139774         pToken->n = nByte;
139775         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
139776         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
139777         nToken = ii+1;
139778       }
139779     }
139780 
139781     pModule->xClose(pCursor);
139782     pCursor = 0;
139783   }
139784 
139785   if( rc==SQLITE_DONE ){
139786     int jj;
139787     char *zBuf = 0;
139788 
139789     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
139790     if( !p ) goto no_mem;
139791     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
139792     p->eType = FTSQUERY_PHRASE;
139793     p->pPhrase = (Fts3Phrase *)&p[1];
139794     p->pPhrase->iColumn = pParse->iDefaultCol;
139795     p->pPhrase->nToken = nToken;
139796 
139797     zBuf = (char *)&p->pPhrase->aToken[nToken];
139798     if( zTemp ){
139799       memcpy(zBuf, zTemp, nTemp);
139800       sqlite3_free(zTemp);
139801     }else{
139802       assert( nTemp==0 );
139803     }
139804 
139805     for(jj=0; jj<p->pPhrase->nToken; jj++){
139806       p->pPhrase->aToken[jj].z = zBuf;
139807       zBuf += p->pPhrase->aToken[jj].n;
139808     }
139809     rc = SQLITE_OK;
139810   }
139811 
139812   *ppExpr = p;
139813   return rc;
139814 no_mem:
139815 
139816   if( pCursor ){
139817     pModule->xClose(pCursor);
139818   }
139819   sqlite3_free(zTemp);
139820   sqlite3_free(p);
139821   *ppExpr = 0;
139822   return SQLITE_NOMEM;
139823 }
139824 
139825 /*
139826 ** The output variable *ppExpr is populated with an allocated Fts3Expr
139827 ** structure, or set to 0 if the end of the input buffer is reached.
139828 **
139829 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
139830 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
139831 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
139832 */
139833 static int getNextNode(
139834   ParseContext *pParse,                   /* fts3 query parse context */
139835   const char *z, int n,                   /* Input string */
139836   Fts3Expr **ppExpr,                      /* OUT: expression */
139837   int *pnConsumed                         /* OUT: Number of bytes consumed */
139838 ){
139839   static const struct Fts3Keyword {
139840     char *z;                              /* Keyword text */
139841     unsigned char n;                      /* Length of the keyword */
139842     unsigned char parenOnly;              /* Only valid in paren mode */
139843     unsigned char eType;                  /* Keyword code */
139844   } aKeyword[] = {
139845     { "OR" ,  2, 0, FTSQUERY_OR   },
139846     { "AND",  3, 1, FTSQUERY_AND  },
139847     { "NOT",  3, 1, FTSQUERY_NOT  },
139848     { "NEAR", 4, 0, FTSQUERY_NEAR }
139849   };
139850   int ii;
139851   int iCol;
139852   int iColLen;
139853   int rc;
139854   Fts3Expr *pRet = 0;
139855 
139856   const char *zInput = z;
139857   int nInput = n;
139858 
139859   pParse->isNot = 0;
139860 
139861   /* Skip over any whitespace before checking for a keyword, an open or
139862   ** close bracket, or a quoted string.
139863   */
139864   while( nInput>0 && fts3isspace(*zInput) ){
139865     nInput--;
139866     zInput++;
139867   }
139868   if( nInput==0 ){
139869     return SQLITE_DONE;
139870   }
139871 
139872   /* See if we are dealing with a keyword. */
139873   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
139874     const struct Fts3Keyword *pKey = &aKeyword[ii];
139875 
139876     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
139877       continue;
139878     }
139879 
139880     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
139881       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
139882       int nKey = pKey->n;
139883       char cNext;
139884 
139885       /* If this is a "NEAR" keyword, check for an explicit nearness. */
139886       if( pKey->eType==FTSQUERY_NEAR ){
139887         assert( nKey==4 );
139888         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
139889           nNear = 0;
139890           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
139891             nNear = nNear * 10 + (zInput[nKey] - '0');
139892           }
139893         }
139894       }
139895 
139896       /* At this point this is probably a keyword. But for that to be true,
139897       ** the next byte must contain either whitespace, an open or close
139898       ** parenthesis, a quote character, or EOF.
139899       */
139900       cNext = zInput[nKey];
139901       if( fts3isspace(cNext)
139902        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
139903       ){
139904         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
139905         if( !pRet ){
139906           return SQLITE_NOMEM;
139907         }
139908         pRet->eType = pKey->eType;
139909         pRet->nNear = nNear;
139910         *ppExpr = pRet;
139911         *pnConsumed = (int)((zInput - z) + nKey);
139912         return SQLITE_OK;
139913       }
139914 
139915       /* Turns out that wasn't a keyword after all. This happens if the
139916       ** user has supplied a token such as "ORacle". Continue.
139917       */
139918     }
139919   }
139920 
139921   /* See if we are dealing with a quoted phrase. If this is the case, then
139922   ** search for the closing quote and pass the whole string to getNextString()
139923   ** for processing. This is easy to do, as fts3 has no syntax for escaping
139924   ** a quote character embedded in a string.
139925   */
139926   if( *zInput=='"' ){
139927     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
139928     *pnConsumed = (int)((zInput - z) + ii + 1);
139929     if( ii==nInput ){
139930       return SQLITE_ERROR;
139931     }
139932     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
139933   }
139934 
139935   if( sqlite3_fts3_enable_parentheses ){
139936     if( *zInput=='(' ){
139937       int nConsumed = 0;
139938       pParse->nNest++;
139939       rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
139940       if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
139941       *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
139942       return rc;
139943     }else if( *zInput==')' ){
139944       pParse->nNest--;
139945       *pnConsumed = (int)((zInput - z) + 1);
139946       *ppExpr = 0;
139947       return SQLITE_DONE;
139948     }
139949   }
139950 
139951   /* If control flows to this point, this must be a regular token, or
139952   ** the end of the input. Read a regular token using the sqlite3_tokenizer
139953   ** interface. Before doing so, figure out if there is an explicit
139954   ** column specifier for the token.
139955   **
139956   ** TODO: Strangely, it is not possible to associate a column specifier
139957   ** with a quoted phrase, only with a single token. Not sure if this was
139958   ** an implementation artifact or an intentional decision when fts3 was
139959   ** first implemented. Whichever it was, this module duplicates the
139960   ** limitation.
139961   */
139962   iCol = pParse->iDefaultCol;
139963   iColLen = 0;
139964   for(ii=0; ii<pParse->nCol; ii++){
139965     const char *zStr = pParse->azCol[ii];
139966     int nStr = (int)strlen(zStr);
139967     if( nInput>nStr && zInput[nStr]==':'
139968      && sqlite3_strnicmp(zStr, zInput, nStr)==0
139969     ){
139970       iCol = ii;
139971       iColLen = (int)((zInput - z) + nStr + 1);
139972       break;
139973     }
139974   }
139975   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
139976   *pnConsumed += iColLen;
139977   return rc;
139978 }
139979 
139980 /*
139981 ** The argument is an Fts3Expr structure for a binary operator (any type
139982 ** except an FTSQUERY_PHRASE). Return an integer value representing the
139983 ** precedence of the operator. Lower values have a higher precedence (i.e.
139984 ** group more tightly). For example, in the C language, the == operator
139985 ** groups more tightly than ||, and would therefore have a higher precedence.
139986 **
139987 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
139988 ** is defined), the order of the operators in precedence from highest to
139989 ** lowest is:
139990 **
139991 **   NEAR
139992 **   NOT
139993 **   AND (including implicit ANDs)
139994 **   OR
139995 **
139996 ** Note that when using the old query syntax, the OR operator has a higher
139997 ** precedence than the AND operator.
139998 */
139999 static int opPrecedence(Fts3Expr *p){
140000   assert( p->eType!=FTSQUERY_PHRASE );
140001   if( sqlite3_fts3_enable_parentheses ){
140002     return p->eType;
140003   }else if( p->eType==FTSQUERY_NEAR ){
140004     return 1;
140005   }else if( p->eType==FTSQUERY_OR ){
140006     return 2;
140007   }
140008   assert( p->eType==FTSQUERY_AND );
140009   return 3;
140010 }
140011 
140012 /*
140013 ** Argument ppHead contains a pointer to the current head of a query
140014 ** expression tree being parsed. pPrev is the expression node most recently
140015 ** inserted into the tree. This function adds pNew, which is always a binary
140016 ** operator node, into the expression tree based on the relative precedence
140017 ** of pNew and the existing nodes of the tree. This may result in the head
140018 ** of the tree changing, in which case *ppHead is set to the new root node.
140019 */
140020 static void insertBinaryOperator(
140021   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
140022   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
140023   Fts3Expr *pNew           /* New binary node to insert into expression tree */
140024 ){
140025   Fts3Expr *pSplit = pPrev;
140026   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
140027     pSplit = pSplit->pParent;
140028   }
140029 
140030   if( pSplit->pParent ){
140031     assert( pSplit->pParent->pRight==pSplit );
140032     pSplit->pParent->pRight = pNew;
140033     pNew->pParent = pSplit->pParent;
140034   }else{
140035     *ppHead = pNew;
140036   }
140037   pNew->pLeft = pSplit;
140038   pSplit->pParent = pNew;
140039 }
140040 
140041 /*
140042 ** Parse the fts3 query expression found in buffer z, length n. This function
140043 ** returns either when the end of the buffer is reached or an unmatched
140044 ** closing bracket - ')' - is encountered.
140045 **
140046 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
140047 ** parsed form of the expression and *pnConsumed is set to the number of
140048 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
140049 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
140050 */
140051 static int fts3ExprParse(
140052   ParseContext *pParse,                   /* fts3 query parse context */
140053   const char *z, int n,                   /* Text of MATCH query */
140054   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
140055   int *pnConsumed                         /* OUT: Number of bytes consumed */
140056 ){
140057   Fts3Expr *pRet = 0;
140058   Fts3Expr *pPrev = 0;
140059   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
140060   int nIn = n;
140061   const char *zIn = z;
140062   int rc = SQLITE_OK;
140063   int isRequirePhrase = 1;
140064 
140065   while( rc==SQLITE_OK ){
140066     Fts3Expr *p = 0;
140067     int nByte = 0;
140068 
140069     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
140070     assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
140071     if( rc==SQLITE_OK ){
140072       if( p ){
140073         int isPhrase;
140074 
140075         if( !sqlite3_fts3_enable_parentheses
140076             && p->eType==FTSQUERY_PHRASE && pParse->isNot
140077         ){
140078           /* Create an implicit NOT operator. */
140079           Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
140080           if( !pNot ){
140081             sqlite3Fts3ExprFree(p);
140082             rc = SQLITE_NOMEM;
140083             goto exprparse_out;
140084           }
140085           pNot->eType = FTSQUERY_NOT;
140086           pNot->pRight = p;
140087           p->pParent = pNot;
140088           if( pNotBranch ){
140089             pNot->pLeft = pNotBranch;
140090             pNotBranch->pParent = pNot;
140091           }
140092           pNotBranch = pNot;
140093           p = pPrev;
140094         }else{
140095           int eType = p->eType;
140096           isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
140097 
140098           /* The isRequirePhrase variable is set to true if a phrase or
140099           ** an expression contained in parenthesis is required. If a
140100           ** binary operator (AND, OR, NOT or NEAR) is encounted when
140101           ** isRequirePhrase is set, this is a syntax error.
140102           */
140103           if( !isPhrase && isRequirePhrase ){
140104             sqlite3Fts3ExprFree(p);
140105             rc = SQLITE_ERROR;
140106             goto exprparse_out;
140107           }
140108 
140109           if( isPhrase && !isRequirePhrase ){
140110             /* Insert an implicit AND operator. */
140111             Fts3Expr *pAnd;
140112             assert( pRet && pPrev );
140113             pAnd = fts3MallocZero(sizeof(Fts3Expr));
140114             if( !pAnd ){
140115               sqlite3Fts3ExprFree(p);
140116               rc = SQLITE_NOMEM;
140117               goto exprparse_out;
140118             }
140119             pAnd->eType = FTSQUERY_AND;
140120             insertBinaryOperator(&pRet, pPrev, pAnd);
140121             pPrev = pAnd;
140122           }
140123 
140124           /* This test catches attempts to make either operand of a NEAR
140125            ** operator something other than a phrase. For example, either of
140126            ** the following:
140127            **
140128            **    (bracketed expression) NEAR phrase
140129            **    phrase NEAR (bracketed expression)
140130            **
140131            ** Return an error in either case.
140132            */
140133           if( pPrev && (
140134             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
140135          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
140136           )){
140137             sqlite3Fts3ExprFree(p);
140138             rc = SQLITE_ERROR;
140139             goto exprparse_out;
140140           }
140141 
140142           if( isPhrase ){
140143             if( pRet ){
140144               assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
140145               pPrev->pRight = p;
140146               p->pParent = pPrev;
140147             }else{
140148               pRet = p;
140149             }
140150           }else{
140151             insertBinaryOperator(&pRet, pPrev, p);
140152           }
140153           isRequirePhrase = !isPhrase;
140154         }
140155         pPrev = p;
140156       }
140157       assert( nByte>0 );
140158     }
140159     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
140160     nIn -= nByte;
140161     zIn += nByte;
140162   }
140163 
140164   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
140165     rc = SQLITE_ERROR;
140166   }
140167 
140168   if( rc==SQLITE_DONE ){
140169     rc = SQLITE_OK;
140170     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
140171       if( !pRet ){
140172         rc = SQLITE_ERROR;
140173       }else{
140174         Fts3Expr *pIter = pNotBranch;
140175         while( pIter->pLeft ){
140176           pIter = pIter->pLeft;
140177         }
140178         pIter->pLeft = pRet;
140179         pRet->pParent = pIter;
140180         pRet = pNotBranch;
140181       }
140182     }
140183   }
140184   *pnConsumed = n - nIn;
140185 
140186 exprparse_out:
140187   if( rc!=SQLITE_OK ){
140188     sqlite3Fts3ExprFree(pRet);
140189     sqlite3Fts3ExprFree(pNotBranch);
140190     pRet = 0;
140191   }
140192   *ppExpr = pRet;
140193   return rc;
140194 }
140195 
140196 /*
140197 ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
140198 ** as the only argument is more than nMaxDepth.
140199 */
140200 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
140201   int rc = SQLITE_OK;
140202   if( p ){
140203     if( nMaxDepth<0 ){
140204       rc = SQLITE_TOOBIG;
140205     }else{
140206       rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
140207       if( rc==SQLITE_OK ){
140208         rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
140209       }
140210     }
140211   }
140212   return rc;
140213 }
140214 
140215 /*
140216 ** This function attempts to transform the expression tree at (*pp) to
140217 ** an equivalent but more balanced form. The tree is modified in place.
140218 ** If successful, SQLITE_OK is returned and (*pp) set to point to the
140219 ** new root expression node.
140220 **
140221 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
140222 **
140223 ** Otherwise, if an error occurs, an SQLite error code is returned and
140224 ** expression (*pp) freed.
140225 */
140226 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
140227   int rc = SQLITE_OK;             /* Return code */
140228   Fts3Expr *pRoot = *pp;          /* Initial root node */
140229   Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
140230   int eType = pRoot->eType;       /* Type of node in this tree */
140231 
140232   if( nMaxDepth==0 ){
140233     rc = SQLITE_ERROR;
140234   }
140235 
140236   if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
140237     Fts3Expr **apLeaf;
140238     apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
140239     if( 0==apLeaf ){
140240       rc = SQLITE_NOMEM;
140241     }else{
140242       memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
140243     }
140244 
140245     if( rc==SQLITE_OK ){
140246       int i;
140247       Fts3Expr *p;
140248 
140249       /* Set $p to point to the left-most leaf in the tree of eType nodes. */
140250       for(p=pRoot; p->eType==eType; p=p->pLeft){
140251         assert( p->pParent==0 || p->pParent->pLeft==p );
140252         assert( p->pLeft && p->pRight );
140253       }
140254 
140255       /* This loop runs once for each leaf in the tree of eType nodes. */
140256       while( 1 ){
140257         int iLvl;
140258         Fts3Expr *pParent = p->pParent;     /* Current parent of p */
140259 
140260         assert( pParent==0 || pParent->pLeft==p );
140261         p->pParent = 0;
140262         if( pParent ){
140263           pParent->pLeft = 0;
140264         }else{
140265           pRoot = 0;
140266         }
140267         rc = fts3ExprBalance(&p, nMaxDepth-1);
140268         if( rc!=SQLITE_OK ) break;
140269 
140270         for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
140271           if( apLeaf[iLvl]==0 ){
140272             apLeaf[iLvl] = p;
140273             p = 0;
140274           }else{
140275             assert( pFree );
140276             pFree->pLeft = apLeaf[iLvl];
140277             pFree->pRight = p;
140278             pFree->pLeft->pParent = pFree;
140279             pFree->pRight->pParent = pFree;
140280 
140281             p = pFree;
140282             pFree = pFree->pParent;
140283             p->pParent = 0;
140284             apLeaf[iLvl] = 0;
140285           }
140286         }
140287         if( p ){
140288           sqlite3Fts3ExprFree(p);
140289           rc = SQLITE_TOOBIG;
140290           break;
140291         }
140292 
140293         /* If that was the last leaf node, break out of the loop */
140294         if( pParent==0 ) break;
140295 
140296         /* Set $p to point to the next leaf in the tree of eType nodes */
140297         for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
140298 
140299         /* Remove pParent from the original tree. */
140300         assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
140301         pParent->pRight->pParent = pParent->pParent;
140302         if( pParent->pParent ){
140303           pParent->pParent->pLeft = pParent->pRight;
140304         }else{
140305           assert( pParent==pRoot );
140306           pRoot = pParent->pRight;
140307         }
140308 
140309         /* Link pParent into the free node list. It will be used as an
140310         ** internal node of the new tree.  */
140311         pParent->pParent = pFree;
140312         pFree = pParent;
140313       }
140314 
140315       if( rc==SQLITE_OK ){
140316         p = 0;
140317         for(i=0; i<nMaxDepth; i++){
140318           if( apLeaf[i] ){
140319             if( p==0 ){
140320               p = apLeaf[i];
140321               p->pParent = 0;
140322             }else{
140323               assert( pFree!=0 );
140324               pFree->pRight = p;
140325               pFree->pLeft = apLeaf[i];
140326               pFree->pLeft->pParent = pFree;
140327               pFree->pRight->pParent = pFree;
140328 
140329               p = pFree;
140330               pFree = pFree->pParent;
140331               p->pParent = 0;
140332             }
140333           }
140334         }
140335         pRoot = p;
140336       }else{
140337         /* An error occurred. Delete the contents of the apLeaf[] array
140338         ** and pFree list. Everything else is cleaned up by the call to
140339         ** sqlite3Fts3ExprFree(pRoot) below.  */
140340         Fts3Expr *pDel;
140341         for(i=0; i<nMaxDepth; i++){
140342           sqlite3Fts3ExprFree(apLeaf[i]);
140343         }
140344         while( (pDel=pFree)!=0 ){
140345           pFree = pDel->pParent;
140346           sqlite3_free(pDel);
140347         }
140348       }
140349 
140350       assert( pFree==0 );
140351       sqlite3_free( apLeaf );
140352     }
140353   }
140354 
140355   if( rc!=SQLITE_OK ){
140356     sqlite3Fts3ExprFree(pRoot);
140357     pRoot = 0;
140358   }
140359   *pp = pRoot;
140360   return rc;
140361 }
140362 
140363 /*
140364 ** This function is similar to sqlite3Fts3ExprParse(), with the following
140365 ** differences:
140366 **
140367 **   1. It does not do expression rebalancing.
140368 **   2. It does not check that the expression does not exceed the
140369 **      maximum allowable depth.
140370 **   3. Even if it fails, *ppExpr may still be set to point to an
140371 **      expression tree. It should be deleted using sqlite3Fts3ExprFree()
140372 **      in this case.
140373 */
140374 static int fts3ExprParseUnbalanced(
140375   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
140376   int iLangid,                        /* Language id for tokenizer */
140377   char **azCol,                       /* Array of column names for fts3 table */
140378   int bFts4,                          /* True to allow FTS4-only syntax */
140379   int nCol,                           /* Number of entries in azCol[] */
140380   int iDefaultCol,                    /* Default column to query */
140381   const char *z, int n,               /* Text of MATCH query */
140382   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
140383 ){
140384   int nParsed;
140385   int rc;
140386   ParseContext sParse;
140387 
140388   memset(&sParse, 0, sizeof(ParseContext));
140389   sParse.pTokenizer = pTokenizer;
140390   sParse.iLangid = iLangid;
140391   sParse.azCol = (const char **)azCol;
140392   sParse.nCol = nCol;
140393   sParse.iDefaultCol = iDefaultCol;
140394   sParse.bFts4 = bFts4;
140395   if( z==0 ){
140396     *ppExpr = 0;
140397     return SQLITE_OK;
140398   }
140399   if( n<0 ){
140400     n = (int)strlen(z);
140401   }
140402   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
140403   assert( rc==SQLITE_OK || *ppExpr==0 );
140404 
140405   /* Check for mismatched parenthesis */
140406   if( rc==SQLITE_OK && sParse.nNest ){
140407     rc = SQLITE_ERROR;
140408   }
140409 
140410   return rc;
140411 }
140412 
140413 /*
140414 ** Parameters z and n contain a pointer to and length of a buffer containing
140415 ** an fts3 query expression, respectively. This function attempts to parse the
140416 ** query expression and create a tree of Fts3Expr structures representing the
140417 ** parsed expression. If successful, *ppExpr is set to point to the head
140418 ** of the parsed expression tree and SQLITE_OK is returned. If an error
140419 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
140420 ** error) is returned and *ppExpr is set to 0.
140421 **
140422 ** If parameter n is a negative number, then z is assumed to point to a
140423 ** nul-terminated string and the length is determined using strlen().
140424 **
140425 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
140426 ** use to normalize query tokens while parsing the expression. The azCol[]
140427 ** array, which is assumed to contain nCol entries, should contain the names
140428 ** of each column in the target fts3 table, in order from left to right.
140429 ** Column names must be nul-terminated strings.
140430 **
140431 ** The iDefaultCol parameter should be passed the index of the table column
140432 ** that appears on the left-hand-side of the MATCH operator (the default
140433 ** column to match against for tokens for which a column name is not explicitly
140434 ** specified as part of the query string), or -1 if tokens may by default
140435 ** match any table column.
140436 */
140437 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
140438   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
140439   int iLangid,                        /* Language id for tokenizer */
140440   char **azCol,                       /* Array of column names for fts3 table */
140441   int bFts4,                          /* True to allow FTS4-only syntax */
140442   int nCol,                           /* Number of entries in azCol[] */
140443   int iDefaultCol,                    /* Default column to query */
140444   const char *z, int n,               /* Text of MATCH query */
140445   Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
140446   char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
140447 ){
140448   int rc = fts3ExprParseUnbalanced(
140449       pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
140450   );
140451 
140452   /* Rebalance the expression. And check that its depth does not exceed
140453   ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
140454   if( rc==SQLITE_OK && *ppExpr ){
140455     rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
140456     if( rc==SQLITE_OK ){
140457       rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
140458     }
140459   }
140460 
140461   if( rc!=SQLITE_OK ){
140462     sqlite3Fts3ExprFree(*ppExpr);
140463     *ppExpr = 0;
140464     if( rc==SQLITE_TOOBIG ){
140465       sqlite3Fts3ErrMsg(pzErr,
140466           "FTS expression tree is too large (maximum depth %d)",
140467           SQLITE_FTS3_MAX_EXPR_DEPTH
140468       );
140469       rc = SQLITE_ERROR;
140470     }else if( rc==SQLITE_ERROR ){
140471       sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
140472     }
140473   }
140474 
140475   return rc;
140476 }
140477 
140478 /*
140479 ** Free a single node of an expression tree.
140480 */
140481 static void fts3FreeExprNode(Fts3Expr *p){
140482   assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
140483   sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
140484   sqlite3_free(p->aMI);
140485   sqlite3_free(p);
140486 }
140487 
140488 /*
140489 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
140490 **
140491 ** This function would be simpler if it recursively called itself. But
140492 ** that would mean passing a sufficiently large expression to ExprParse()
140493 ** could cause a stack overflow.
140494 */
140495 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
140496   Fts3Expr *p;
140497   assert( pDel==0 || pDel->pParent==0 );
140498   for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
140499     assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
140500   }
140501   while( p ){
140502     Fts3Expr *pParent = p->pParent;
140503     fts3FreeExprNode(p);
140504     if( pParent && p==pParent->pLeft && pParent->pRight ){
140505       p = pParent->pRight;
140506       while( p && (p->pLeft || p->pRight) ){
140507         assert( p==p->pParent->pRight || p==p->pParent->pLeft );
140508         p = (p->pLeft ? p->pLeft : p->pRight);
140509       }
140510     }else{
140511       p = pParent;
140512     }
140513   }
140514 }
140515 
140516 /****************************************************************************
140517 *****************************************************************************
140518 ** Everything after this point is just test code.
140519 */
140520 
140521 #ifdef SQLITE_TEST
140522 
140523 /* #include <stdio.h> */
140524 
140525 /*
140526 ** Function to query the hash-table of tokenizers (see README.tokenizers).
140527 */
140528 static int queryTestTokenizer(
140529   sqlite3 *db,
140530   const char *zName,
140531   const sqlite3_tokenizer_module **pp
140532 ){
140533   int rc;
140534   sqlite3_stmt *pStmt;
140535   const char zSql[] = "SELECT fts3_tokenizer(?)";
140536 
140537   *pp = 0;
140538   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
140539   if( rc!=SQLITE_OK ){
140540     return rc;
140541   }
140542 
140543   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
140544   if( SQLITE_ROW==sqlite3_step(pStmt) ){
140545     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
140546       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
140547     }
140548   }
140549 
140550   return sqlite3_finalize(pStmt);
140551 }
140552 
140553 /*
140554 ** Return a pointer to a buffer containing a text representation of the
140555 ** expression passed as the first argument. The buffer is obtained from
140556 ** sqlite3_malloc(). It is the responsibility of the caller to use
140557 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
140558 ** NULL is returned.
140559 **
140560 ** If the second argument is not NULL, then its contents are prepended to
140561 ** the returned expression text and then freed using sqlite3_free().
140562 */
140563 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
140564   if( pExpr==0 ){
140565     return sqlite3_mprintf("");
140566   }
140567   switch( pExpr->eType ){
140568     case FTSQUERY_PHRASE: {
140569       Fts3Phrase *pPhrase = pExpr->pPhrase;
140570       int i;
140571       zBuf = sqlite3_mprintf(
140572           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
140573       for(i=0; zBuf && i<pPhrase->nToken; i++){
140574         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
140575             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
140576             (pPhrase->aToken[i].isPrefix?"+":"")
140577         );
140578       }
140579       return zBuf;
140580     }
140581 
140582     case FTSQUERY_NEAR:
140583       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
140584       break;
140585     case FTSQUERY_NOT:
140586       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
140587       break;
140588     case FTSQUERY_AND:
140589       zBuf = sqlite3_mprintf("%zAND ", zBuf);
140590       break;
140591     case FTSQUERY_OR:
140592       zBuf = sqlite3_mprintf("%zOR ", zBuf);
140593       break;
140594   }
140595 
140596   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
140597   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
140598   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
140599 
140600   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
140601   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
140602 
140603   return zBuf;
140604 }
140605 
140606 /*
140607 ** This is the implementation of a scalar SQL function used to test the
140608 ** expression parser. It should be called as follows:
140609 **
140610 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
140611 **
140612 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
140613 ** to parse the query expression (see README.tokenizers). The second argument
140614 ** is the query expression to parse. Each subsequent argument is the name
140615 ** of a column of the fts3 table that the query expression may refer to.
140616 ** For example:
140617 **
140618 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
140619 */
140620 static void fts3ExprTest(
140621   sqlite3_context *context,
140622   int argc,
140623   sqlite3_value **argv
140624 ){
140625   sqlite3_tokenizer_module const *pModule = 0;
140626   sqlite3_tokenizer *pTokenizer = 0;
140627   int rc;
140628   char **azCol = 0;
140629   const char *zExpr;
140630   int nExpr;
140631   int nCol;
140632   int ii;
140633   Fts3Expr *pExpr;
140634   char *zBuf = 0;
140635   sqlite3 *db = sqlite3_context_db_handle(context);
140636 
140637   if( argc<3 ){
140638     sqlite3_result_error(context,
140639         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
140640     );
140641     return;
140642   }
140643 
140644   rc = queryTestTokenizer(db,
140645                           (const char *)sqlite3_value_text(argv[0]), &pModule);
140646   if( rc==SQLITE_NOMEM ){
140647     sqlite3_result_error_nomem(context);
140648     goto exprtest_out;
140649   }else if( !pModule ){
140650     sqlite3_result_error(context, "No such tokenizer module", -1);
140651     goto exprtest_out;
140652   }
140653 
140654   rc = pModule->xCreate(0, 0, &pTokenizer);
140655   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
140656   if( rc==SQLITE_NOMEM ){
140657     sqlite3_result_error_nomem(context);
140658     goto exprtest_out;
140659   }
140660   pTokenizer->pModule = pModule;
140661 
140662   zExpr = (const char *)sqlite3_value_text(argv[1]);
140663   nExpr = sqlite3_value_bytes(argv[1]);
140664   nCol = argc-2;
140665   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
140666   if( !azCol ){
140667     sqlite3_result_error_nomem(context);
140668     goto exprtest_out;
140669   }
140670   for(ii=0; ii<nCol; ii++){
140671     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
140672   }
140673 
140674   if( sqlite3_user_data(context) ){
140675     char *zDummy = 0;
140676     rc = sqlite3Fts3ExprParse(
140677         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
140678     );
140679     assert( rc==SQLITE_OK || pExpr==0 );
140680     sqlite3_free(zDummy);
140681   }else{
140682     rc = fts3ExprParseUnbalanced(
140683         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
140684     );
140685   }
140686 
140687   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
140688     sqlite3Fts3ExprFree(pExpr);
140689     sqlite3_result_error(context, "Error parsing expression", -1);
140690   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
140691     sqlite3_result_error_nomem(context);
140692   }else{
140693     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
140694     sqlite3_free(zBuf);
140695   }
140696 
140697   sqlite3Fts3ExprFree(pExpr);
140698 
140699 exprtest_out:
140700   if( pModule && pTokenizer ){
140701     rc = pModule->xDestroy(pTokenizer);
140702   }
140703   sqlite3_free(azCol);
140704 }
140705 
140706 /*
140707 ** Register the query expression parser test function fts3_exprtest()
140708 ** with database connection db.
140709 */
140710 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
140711   int rc = sqlite3_create_function(
140712       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
140713   );
140714   if( rc==SQLITE_OK ){
140715     rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
140716         -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
140717     );
140718   }
140719   return rc;
140720 }
140721 
140722 #endif
140723 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
140724 
140725 /************** End of fts3_expr.c *******************************************/
140726 /************** Begin file fts3_hash.c ***************************************/
140727 /*
140728 ** 2001 September 22
140729 **
140730 ** The author disclaims copyright to this source code.  In place of
140731 ** a legal notice, here is a blessing:
140732 **
140733 **    May you do good and not evil.
140734 **    May you find forgiveness for yourself and forgive others.
140735 **    May you share freely, never taking more than you give.
140736 **
140737 *************************************************************************
140738 ** This is the implementation of generic hash-tables used in SQLite.
140739 ** We've modified it slightly to serve as a standalone hash table
140740 ** implementation for the full-text indexing module.
140741 */
140742 
140743 /*
140744 ** The code in this file is only compiled if:
140745 **
140746 **     * The FTS3 module is being built as an extension
140747 **       (in which case SQLITE_CORE is not defined), or
140748 **
140749 **     * The FTS3 module is being built into the core of
140750 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
140751 */
140752 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
140753 
140754 /* #include <assert.h> */
140755 /* #include <stdlib.h> */
140756 /* #include <string.h> */
140757 
140758 
140759 /*
140760 ** Malloc and Free functions
140761 */
140762 static void *fts3HashMalloc(int n){
140763   void *p = sqlite3_malloc(n);
140764   if( p ){
140765     memset(p, 0, n);
140766   }
140767   return p;
140768 }
140769 static void fts3HashFree(void *p){
140770   sqlite3_free(p);
140771 }
140772 
140773 /* Turn bulk memory into a hash table object by initializing the
140774 ** fields of the Hash structure.
140775 **
140776 ** "pNew" is a pointer to the hash table that is to be initialized.
140777 ** keyClass is one of the constants
140778 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
140779 ** determines what kind of key the hash table will use.  "copyKey" is
140780 ** true if the hash table should make its own private copy of keys and
140781 ** false if it should just use the supplied pointer.
140782 */
140783 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
140784   assert( pNew!=0 );
140785   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
140786   pNew->keyClass = keyClass;
140787   pNew->copyKey = copyKey;
140788   pNew->first = 0;
140789   pNew->count = 0;
140790   pNew->htsize = 0;
140791   pNew->ht = 0;
140792 }
140793 
140794 /* Remove all entries from a hash table.  Reclaim all memory.
140795 ** Call this routine to delete a hash table or to reset a hash table
140796 ** to the empty state.
140797 */
140798 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
140799   Fts3HashElem *elem;         /* For looping over all elements of the table */
140800 
140801   assert( pH!=0 );
140802   elem = pH->first;
140803   pH->first = 0;
140804   fts3HashFree(pH->ht);
140805   pH->ht = 0;
140806   pH->htsize = 0;
140807   while( elem ){
140808     Fts3HashElem *next_elem = elem->next;
140809     if( pH->copyKey && elem->pKey ){
140810       fts3HashFree(elem->pKey);
140811     }
140812     fts3HashFree(elem);
140813     elem = next_elem;
140814   }
140815   pH->count = 0;
140816 }
140817 
140818 /*
140819 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
140820 */
140821 static int fts3StrHash(const void *pKey, int nKey){
140822   const char *z = (const char *)pKey;
140823   unsigned h = 0;
140824   if( nKey<=0 ) nKey = (int) strlen(z);
140825   while( nKey > 0  ){
140826     h = (h<<3) ^ h ^ *z++;
140827     nKey--;
140828   }
140829   return (int)(h & 0x7fffffff);
140830 }
140831 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
140832   if( n1!=n2 ) return 1;
140833   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
140834 }
140835 
140836 /*
140837 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
140838 */
140839 static int fts3BinHash(const void *pKey, int nKey){
140840   int h = 0;
140841   const char *z = (const char *)pKey;
140842   while( nKey-- > 0 ){
140843     h = (h<<3) ^ h ^ *(z++);
140844   }
140845   return h & 0x7fffffff;
140846 }
140847 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
140848   if( n1!=n2 ) return 1;
140849   return memcmp(pKey1,pKey2,n1);
140850 }
140851 
140852 /*
140853 ** Return a pointer to the appropriate hash function given the key class.
140854 **
140855 ** The C syntax in this function definition may be unfamilar to some
140856 ** programmers, so we provide the following additional explanation:
140857 **
140858 ** The name of the function is "ftsHashFunction".  The function takes a
140859 ** single parameter "keyClass".  The return value of ftsHashFunction()
140860 ** is a pointer to another function.  Specifically, the return value
140861 ** of ftsHashFunction() is a pointer to a function that takes two parameters
140862 ** with types "const void*" and "int" and returns an "int".
140863 */
140864 static int (*ftsHashFunction(int keyClass))(const void*,int){
140865   if( keyClass==FTS3_HASH_STRING ){
140866     return &fts3StrHash;
140867   }else{
140868     assert( keyClass==FTS3_HASH_BINARY );
140869     return &fts3BinHash;
140870   }
140871 }
140872 
140873 /*
140874 ** Return a pointer to the appropriate hash function given the key class.
140875 **
140876 ** For help in interpreted the obscure C code in the function definition,
140877 ** see the header comment on the previous function.
140878 */
140879 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
140880   if( keyClass==FTS3_HASH_STRING ){
140881     return &fts3StrCompare;
140882   }else{
140883     assert( keyClass==FTS3_HASH_BINARY );
140884     return &fts3BinCompare;
140885   }
140886 }
140887 
140888 /* Link an element into the hash table
140889 */
140890 static void fts3HashInsertElement(
140891   Fts3Hash *pH,            /* The complete hash table */
140892   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
140893   Fts3HashElem *pNew       /* The element to be inserted */
140894 ){
140895   Fts3HashElem *pHead;     /* First element already in pEntry */
140896   pHead = pEntry->chain;
140897   if( pHead ){
140898     pNew->next = pHead;
140899     pNew->prev = pHead->prev;
140900     if( pHead->prev ){ pHead->prev->next = pNew; }
140901     else             { pH->first = pNew; }
140902     pHead->prev = pNew;
140903   }else{
140904     pNew->next = pH->first;
140905     if( pH->first ){ pH->first->prev = pNew; }
140906     pNew->prev = 0;
140907     pH->first = pNew;
140908   }
140909   pEntry->count++;
140910   pEntry->chain = pNew;
140911 }
140912 
140913 
140914 /* Resize the hash table so that it cantains "new_size" buckets.
140915 ** "new_size" must be a power of 2.  The hash table might fail
140916 ** to resize if sqliteMalloc() fails.
140917 **
140918 ** Return non-zero if a memory allocation error occurs.
140919 */
140920 static int fts3Rehash(Fts3Hash *pH, int new_size){
140921   struct _fts3ht *new_ht;          /* The new hash table */
140922   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
140923   int (*xHash)(const void*,int);   /* The hash function */
140924 
140925   assert( (new_size & (new_size-1))==0 );
140926   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
140927   if( new_ht==0 ) return 1;
140928   fts3HashFree(pH->ht);
140929   pH->ht = new_ht;
140930   pH->htsize = new_size;
140931   xHash = ftsHashFunction(pH->keyClass);
140932   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
140933     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
140934     next_elem = elem->next;
140935     fts3HashInsertElement(pH, &new_ht[h], elem);
140936   }
140937   return 0;
140938 }
140939 
140940 /* This function (for internal use only) locates an element in an
140941 ** hash table that matches the given key.  The hash for this key has
140942 ** already been computed and is passed as the 4th parameter.
140943 */
140944 static Fts3HashElem *fts3FindElementByHash(
140945   const Fts3Hash *pH, /* The pH to be searched */
140946   const void *pKey,   /* The key we are searching for */
140947   int nKey,
140948   int h               /* The hash for this key. */
140949 ){
140950   Fts3HashElem *elem;            /* Used to loop thru the element list */
140951   int count;                     /* Number of elements left to test */
140952   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
140953 
140954   if( pH->ht ){
140955     struct _fts3ht *pEntry = &pH->ht[h];
140956     elem = pEntry->chain;
140957     count = pEntry->count;
140958     xCompare = ftsCompareFunction(pH->keyClass);
140959     while( count-- && elem ){
140960       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
140961         return elem;
140962       }
140963       elem = elem->next;
140964     }
140965   }
140966   return 0;
140967 }
140968 
140969 /* Remove a single entry from the hash table given a pointer to that
140970 ** element and a hash on the element's key.
140971 */
140972 static void fts3RemoveElementByHash(
140973   Fts3Hash *pH,         /* The pH containing "elem" */
140974   Fts3HashElem* elem,   /* The element to be removed from the pH */
140975   int h                 /* Hash value for the element */
140976 ){
140977   struct _fts3ht *pEntry;
140978   if( elem->prev ){
140979     elem->prev->next = elem->next;
140980   }else{
140981     pH->first = elem->next;
140982   }
140983   if( elem->next ){
140984     elem->next->prev = elem->prev;
140985   }
140986   pEntry = &pH->ht[h];
140987   if( pEntry->chain==elem ){
140988     pEntry->chain = elem->next;
140989   }
140990   pEntry->count--;
140991   if( pEntry->count<=0 ){
140992     pEntry->chain = 0;
140993   }
140994   if( pH->copyKey && elem->pKey ){
140995     fts3HashFree(elem->pKey);
140996   }
140997   fts3HashFree( elem );
140998   pH->count--;
140999   if( pH->count<=0 ){
141000     assert( pH->first==0 );
141001     assert( pH->count==0 );
141002     fts3HashClear(pH);
141003   }
141004 }
141005 
141006 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
141007   const Fts3Hash *pH,
141008   const void *pKey,
141009   int nKey
141010 ){
141011   int h;                          /* A hash on key */
141012   int (*xHash)(const void*,int);  /* The hash function */
141013 
141014   if( pH==0 || pH->ht==0 ) return 0;
141015   xHash = ftsHashFunction(pH->keyClass);
141016   assert( xHash!=0 );
141017   h = (*xHash)(pKey,nKey);
141018   assert( (pH->htsize & (pH->htsize-1))==0 );
141019   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
141020 }
141021 
141022 /*
141023 ** Attempt to locate an element of the hash table pH with a key
141024 ** that matches pKey,nKey.  Return the data for this element if it is
141025 ** found, or NULL if there is no match.
141026 */
141027 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
141028   Fts3HashElem *pElem;            /* The element that matches key (if any) */
141029 
141030   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
141031   return pElem ? pElem->data : 0;
141032 }
141033 
141034 /* Insert an element into the hash table pH.  The key is pKey,nKey
141035 ** and the data is "data".
141036 **
141037 ** If no element exists with a matching key, then a new
141038 ** element is created.  A copy of the key is made if the copyKey
141039 ** flag is set.  NULL is returned.
141040 **
141041 ** If another element already exists with the same key, then the
141042 ** new data replaces the old data and the old data is returned.
141043 ** The key is not copied in this instance.  If a malloc fails, then
141044 ** the new data is returned and the hash table is unchanged.
141045 **
141046 ** If the "data" parameter to this function is NULL, then the
141047 ** element corresponding to "key" is removed from the hash table.
141048 */
141049 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
141050   Fts3Hash *pH,        /* The hash table to insert into */
141051   const void *pKey,    /* The key */
141052   int nKey,            /* Number of bytes in the key */
141053   void *data           /* The data */
141054 ){
141055   int hraw;                 /* Raw hash value of the key */
141056   int h;                    /* the hash of the key modulo hash table size */
141057   Fts3HashElem *elem;       /* Used to loop thru the element list */
141058   Fts3HashElem *new_elem;   /* New element added to the pH */
141059   int (*xHash)(const void*,int);  /* The hash function */
141060 
141061   assert( pH!=0 );
141062   xHash = ftsHashFunction(pH->keyClass);
141063   assert( xHash!=0 );
141064   hraw = (*xHash)(pKey, nKey);
141065   assert( (pH->htsize & (pH->htsize-1))==0 );
141066   h = hraw & (pH->htsize-1);
141067   elem = fts3FindElementByHash(pH,pKey,nKey,h);
141068   if( elem ){
141069     void *old_data = elem->data;
141070     if( data==0 ){
141071       fts3RemoveElementByHash(pH,elem,h);
141072     }else{
141073       elem->data = data;
141074     }
141075     return old_data;
141076   }
141077   if( data==0 ) return 0;
141078   if( (pH->htsize==0 && fts3Rehash(pH,8))
141079    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
141080   ){
141081     pH->count = 0;
141082     return data;
141083   }
141084   assert( pH->htsize>0 );
141085   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
141086   if( new_elem==0 ) return data;
141087   if( pH->copyKey && pKey!=0 ){
141088     new_elem->pKey = fts3HashMalloc( nKey );
141089     if( new_elem->pKey==0 ){
141090       fts3HashFree(new_elem);
141091       return data;
141092     }
141093     memcpy((void*)new_elem->pKey, pKey, nKey);
141094   }else{
141095     new_elem->pKey = (void*)pKey;
141096   }
141097   new_elem->nKey = nKey;
141098   pH->count++;
141099   assert( pH->htsize>0 );
141100   assert( (pH->htsize & (pH->htsize-1))==0 );
141101   h = hraw & (pH->htsize-1);
141102   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
141103   new_elem->data = data;
141104   return 0;
141105 }
141106 
141107 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
141108 
141109 /************** End of fts3_hash.c *******************************************/
141110 /************** Begin file fts3_porter.c *************************************/
141111 /*
141112 ** 2006 September 30
141113 **
141114 ** The author disclaims copyright to this source code.  In place of
141115 ** a legal notice, here is a blessing:
141116 **
141117 **    May you do good and not evil.
141118 **    May you find forgiveness for yourself and forgive others.
141119 **    May you share freely, never taking more than you give.
141120 **
141121 *************************************************************************
141122 ** Implementation of the full-text-search tokenizer that implements
141123 ** a Porter stemmer.
141124 */
141125 
141126 /*
141127 ** The code in this file is only compiled if:
141128 **
141129 **     * The FTS3 module is being built as an extension
141130 **       (in which case SQLITE_CORE is not defined), or
141131 **
141132 **     * The FTS3 module is being built into the core of
141133 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
141134 */
141135 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141136 
141137 /* #include <assert.h> */
141138 /* #include <stdlib.h> */
141139 /* #include <stdio.h> */
141140 /* #include <string.h> */
141141 
141142 
141143 /*
141144 ** Class derived from sqlite3_tokenizer
141145 */
141146 typedef struct porter_tokenizer {
141147   sqlite3_tokenizer base;      /* Base class */
141148 } porter_tokenizer;
141149 
141150 /*
141151 ** Class derived from sqlite3_tokenizer_cursor
141152 */
141153 typedef struct porter_tokenizer_cursor {
141154   sqlite3_tokenizer_cursor base;
141155   const char *zInput;          /* input we are tokenizing */
141156   int nInput;                  /* size of the input */
141157   int iOffset;                 /* current position in zInput */
141158   int iToken;                  /* index of next token to be returned */
141159   char *zToken;                /* storage for current token */
141160   int nAllocated;              /* space allocated to zToken buffer */
141161 } porter_tokenizer_cursor;
141162 
141163 
141164 /*
141165 ** Create a new tokenizer instance.
141166 */
141167 static int porterCreate(
141168   int argc, const char * const *argv,
141169   sqlite3_tokenizer **ppTokenizer
141170 ){
141171   porter_tokenizer *t;
141172 
141173   UNUSED_PARAMETER(argc);
141174   UNUSED_PARAMETER(argv);
141175 
141176   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
141177   if( t==NULL ) return SQLITE_NOMEM;
141178   memset(t, 0, sizeof(*t));
141179   *ppTokenizer = &t->base;
141180   return SQLITE_OK;
141181 }
141182 
141183 /*
141184 ** Destroy a tokenizer
141185 */
141186 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
141187   sqlite3_free(pTokenizer);
141188   return SQLITE_OK;
141189 }
141190 
141191 /*
141192 ** Prepare to begin tokenizing a particular string.  The input
141193 ** string to be tokenized is zInput[0..nInput-1].  A cursor
141194 ** used to incrementally tokenize this string is returned in
141195 ** *ppCursor.
141196 */
141197 static int porterOpen(
141198   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
141199   const char *zInput, int nInput,        /* String to be tokenized */
141200   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
141201 ){
141202   porter_tokenizer_cursor *c;
141203 
141204   UNUSED_PARAMETER(pTokenizer);
141205 
141206   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
141207   if( c==NULL ) return SQLITE_NOMEM;
141208 
141209   c->zInput = zInput;
141210   if( zInput==0 ){
141211     c->nInput = 0;
141212   }else if( nInput<0 ){
141213     c->nInput = (int)strlen(zInput);
141214   }else{
141215     c->nInput = nInput;
141216   }
141217   c->iOffset = 0;                 /* start tokenizing at the beginning */
141218   c->iToken = 0;
141219   c->zToken = NULL;               /* no space allocated, yet. */
141220   c->nAllocated = 0;
141221 
141222   *ppCursor = &c->base;
141223   return SQLITE_OK;
141224 }
141225 
141226 /*
141227 ** Close a tokenization cursor previously opened by a call to
141228 ** porterOpen() above.
141229 */
141230 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
141231   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
141232   sqlite3_free(c->zToken);
141233   sqlite3_free(c);
141234   return SQLITE_OK;
141235 }
141236 /*
141237 ** Vowel or consonant
141238 */
141239 static const char cType[] = {
141240    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
141241    1, 1, 1, 2, 1
141242 };
141243 
141244 /*
141245 ** isConsonant() and isVowel() determine if their first character in
141246 ** the string they point to is a consonant or a vowel, according
141247 ** to Porter ruls.
141248 **
141249 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
141250 ** 'Y' is a consonant unless it follows another consonant,
141251 ** in which case it is a vowel.
141252 **
141253 ** In these routine, the letters are in reverse order.  So the 'y' rule
141254 ** is that 'y' is a consonant unless it is followed by another
141255 ** consonent.
141256 */
141257 static int isVowel(const char*);
141258 static int isConsonant(const char *z){
141259   int j;
141260   char x = *z;
141261   if( x==0 ) return 0;
141262   assert( x>='a' && x<='z' );
141263   j = cType[x-'a'];
141264   if( j<2 ) return j;
141265   return z[1]==0 || isVowel(z + 1);
141266 }
141267 static int isVowel(const char *z){
141268   int j;
141269   char x = *z;
141270   if( x==0 ) return 0;
141271   assert( x>='a' && x<='z' );
141272   j = cType[x-'a'];
141273   if( j<2 ) return 1-j;
141274   return isConsonant(z + 1);
141275 }
141276 
141277 /*
141278 ** Let any sequence of one or more vowels be represented by V and let
141279 ** C be sequence of one or more consonants.  Then every word can be
141280 ** represented as:
141281 **
141282 **           [C] (VC){m} [V]
141283 **
141284 ** In prose:  A word is an optional consonant followed by zero or
141285 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
141286 ** number of vowel consonant pairs.  This routine computes the value
141287 ** of m for the first i bytes of a word.
141288 **
141289 ** Return true if the m-value for z is 1 or more.  In other words,
141290 ** return true if z contains at least one vowel that is followed
141291 ** by a consonant.
141292 **
141293 ** In this routine z[] is in reverse order.  So we are really looking
141294 ** for an instance of a consonant followed by a vowel.
141295 */
141296 static int m_gt_0(const char *z){
141297   while( isVowel(z) ){ z++; }
141298   if( *z==0 ) return 0;
141299   while( isConsonant(z) ){ z++; }
141300   return *z!=0;
141301 }
141302 
141303 /* Like mgt0 above except we are looking for a value of m which is
141304 ** exactly 1
141305 */
141306 static int m_eq_1(const char *z){
141307   while( isVowel(z) ){ z++; }
141308   if( *z==0 ) return 0;
141309   while( isConsonant(z) ){ z++; }
141310   if( *z==0 ) return 0;
141311   while( isVowel(z) ){ z++; }
141312   if( *z==0 ) return 1;
141313   while( isConsonant(z) ){ z++; }
141314   return *z==0;
141315 }
141316 
141317 /* Like mgt0 above except we are looking for a value of m>1 instead
141318 ** or m>0
141319 */
141320 static int m_gt_1(const char *z){
141321   while( isVowel(z) ){ z++; }
141322   if( *z==0 ) return 0;
141323   while( isConsonant(z) ){ z++; }
141324   if( *z==0 ) return 0;
141325   while( isVowel(z) ){ z++; }
141326   if( *z==0 ) return 0;
141327   while( isConsonant(z) ){ z++; }
141328   return *z!=0;
141329 }
141330 
141331 /*
141332 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
141333 */
141334 static int hasVowel(const char *z){
141335   while( isConsonant(z) ){ z++; }
141336   return *z!=0;
141337 }
141338 
141339 /*
141340 ** Return TRUE if the word ends in a double consonant.
141341 **
141342 ** The text is reversed here. So we are really looking at
141343 ** the first two characters of z[].
141344 */
141345 static int doubleConsonant(const char *z){
141346   return isConsonant(z) && z[0]==z[1];
141347 }
141348 
141349 /*
141350 ** Return TRUE if the word ends with three letters which
141351 ** are consonant-vowel-consonent and where the final consonant
141352 ** is not 'w', 'x', or 'y'.
141353 **
141354 ** The word is reversed here.  So we are really checking the
141355 ** first three letters and the first one cannot be in [wxy].
141356 */
141357 static int star_oh(const char *z){
141358   return
141359     isConsonant(z) &&
141360     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
141361     isVowel(z+1) &&
141362     isConsonant(z+2);
141363 }
141364 
141365 /*
141366 ** If the word ends with zFrom and xCond() is true for the stem
141367 ** of the word that preceeds the zFrom ending, then change the
141368 ** ending to zTo.
141369 **
141370 ** The input word *pz and zFrom are both in reverse order.  zTo
141371 ** is in normal order.
141372 **
141373 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
141374 ** match.  Not that TRUE is returned even if xCond() fails and
141375 ** no substitution occurs.
141376 */
141377 static int stem(
141378   char **pz,             /* The word being stemmed (Reversed) */
141379   const char *zFrom,     /* If the ending matches this... (Reversed) */
141380   const char *zTo,       /* ... change the ending to this (not reversed) */
141381   int (*xCond)(const char*)   /* Condition that must be true */
141382 ){
141383   char *z = *pz;
141384   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
141385   if( *zFrom!=0 ) return 0;
141386   if( xCond && !xCond(z) ) return 1;
141387   while( *zTo ){
141388     *(--z) = *(zTo++);
141389   }
141390   *pz = z;
141391   return 1;
141392 }
141393 
141394 /*
141395 ** This is the fallback stemmer used when the porter stemmer is
141396 ** inappropriate.  The input word is copied into the output with
141397 ** US-ASCII case folding.  If the input word is too long (more
141398 ** than 20 bytes if it contains no digits or more than 6 bytes if
141399 ** it contains digits) then word is truncated to 20 or 6 bytes
141400 ** by taking 10 or 3 bytes from the beginning and end.
141401 */
141402 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
141403   int i, mx, j;
141404   int hasDigit = 0;
141405   for(i=0; i<nIn; i++){
141406     char c = zIn[i];
141407     if( c>='A' && c<='Z' ){
141408       zOut[i] = c - 'A' + 'a';
141409     }else{
141410       if( c>='0' && c<='9' ) hasDigit = 1;
141411       zOut[i] = c;
141412     }
141413   }
141414   mx = hasDigit ? 3 : 10;
141415   if( nIn>mx*2 ){
141416     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
141417       zOut[j] = zOut[i];
141418     }
141419     i = j;
141420   }
141421   zOut[i] = 0;
141422   *pnOut = i;
141423 }
141424 
141425 
141426 /*
141427 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
141428 ** zOut is at least big enough to hold nIn bytes.  Write the actual
141429 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
141430 **
141431 ** Any upper-case characters in the US-ASCII character set ([A-Z])
141432 ** are converted to lower case.  Upper-case UTF characters are
141433 ** unchanged.
141434 **
141435 ** Words that are longer than about 20 bytes are stemmed by retaining
141436 ** a few bytes from the beginning and the end of the word.  If the
141437 ** word contains digits, 3 bytes are taken from the beginning and
141438 ** 3 bytes from the end.  For long words without digits, 10 bytes
141439 ** are taken from each end.  US-ASCII case folding still applies.
141440 **
141441 ** If the input word contains not digits but does characters not
141442 ** in [a-zA-Z] then no stemming is attempted and this routine just
141443 ** copies the input into the input into the output with US-ASCII
141444 ** case folding.
141445 **
141446 ** Stemming never increases the length of the word.  So there is
141447 ** no chance of overflowing the zOut buffer.
141448 */
141449 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
141450   int i, j;
141451   char zReverse[28];
141452   char *z, *z2;
141453   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
141454     /* The word is too big or too small for the porter stemmer.
141455     ** Fallback to the copy stemmer */
141456     copy_stemmer(zIn, nIn, zOut, pnOut);
141457     return;
141458   }
141459   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
141460     char c = zIn[i];
141461     if( c>='A' && c<='Z' ){
141462       zReverse[j] = c + 'a' - 'A';
141463     }else if( c>='a' && c<='z' ){
141464       zReverse[j] = c;
141465     }else{
141466       /* The use of a character not in [a-zA-Z] means that we fallback
141467       ** to the copy stemmer */
141468       copy_stemmer(zIn, nIn, zOut, pnOut);
141469       return;
141470     }
141471   }
141472   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
141473   z = &zReverse[j+1];
141474 
141475 
141476   /* Step 1a */
141477   if( z[0]=='s' ){
141478     if(
141479      !stem(&z, "sess", "ss", 0) &&
141480      !stem(&z, "sei", "i", 0)  &&
141481      !stem(&z, "ss", "ss", 0)
141482     ){
141483       z++;
141484     }
141485   }
141486 
141487   /* Step 1b */
141488   z2 = z;
141489   if( stem(&z, "dee", "ee", m_gt_0) ){
141490     /* Do nothing.  The work was all in the test */
141491   }else if(
141492      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
141493       && z!=z2
141494   ){
141495      if( stem(&z, "ta", "ate", 0) ||
141496          stem(&z, "lb", "ble", 0) ||
141497          stem(&z, "zi", "ize", 0) ){
141498        /* Do nothing.  The work was all in the test */
141499      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
141500        z++;
141501      }else if( m_eq_1(z) && star_oh(z) ){
141502        *(--z) = 'e';
141503      }
141504   }
141505 
141506   /* Step 1c */
141507   if( z[0]=='y' && hasVowel(z+1) ){
141508     z[0] = 'i';
141509   }
141510 
141511   /* Step 2 */
141512   switch( z[1] ){
141513    case 'a':
141514      if( !stem(&z, "lanoita", "ate", m_gt_0) ){
141515        stem(&z, "lanoit", "tion", m_gt_0);
141516      }
141517      break;
141518    case 'c':
141519      if( !stem(&z, "icne", "ence", m_gt_0) ){
141520        stem(&z, "icna", "ance", m_gt_0);
141521      }
141522      break;
141523    case 'e':
141524      stem(&z, "rezi", "ize", m_gt_0);
141525      break;
141526    case 'g':
141527      stem(&z, "igol", "log", m_gt_0);
141528      break;
141529    case 'l':
141530      if( !stem(&z, "ilb", "ble", m_gt_0)
141531       && !stem(&z, "illa", "al", m_gt_0)
141532       && !stem(&z, "iltne", "ent", m_gt_0)
141533       && !stem(&z, "ile", "e", m_gt_0)
141534      ){
141535        stem(&z, "ilsuo", "ous", m_gt_0);
141536      }
141537      break;
141538    case 'o':
141539      if( !stem(&z, "noitazi", "ize", m_gt_0)
141540       && !stem(&z, "noita", "ate", m_gt_0)
141541      ){
141542        stem(&z, "rota", "ate", m_gt_0);
141543      }
141544      break;
141545    case 's':
141546      if( !stem(&z, "msila", "al", m_gt_0)
141547       && !stem(&z, "ssenevi", "ive", m_gt_0)
141548       && !stem(&z, "ssenluf", "ful", m_gt_0)
141549      ){
141550        stem(&z, "ssensuo", "ous", m_gt_0);
141551      }
141552      break;
141553    case 't':
141554      if( !stem(&z, "itila", "al", m_gt_0)
141555       && !stem(&z, "itivi", "ive", m_gt_0)
141556      ){
141557        stem(&z, "itilib", "ble", m_gt_0);
141558      }
141559      break;
141560   }
141561 
141562   /* Step 3 */
141563   switch( z[0] ){
141564    case 'e':
141565      if( !stem(&z, "etaci", "ic", m_gt_0)
141566       && !stem(&z, "evita", "", m_gt_0)
141567      ){
141568        stem(&z, "ezila", "al", m_gt_0);
141569      }
141570      break;
141571    case 'i':
141572      stem(&z, "itici", "ic", m_gt_0);
141573      break;
141574    case 'l':
141575      if( !stem(&z, "laci", "ic", m_gt_0) ){
141576        stem(&z, "luf", "", m_gt_0);
141577      }
141578      break;
141579    case 's':
141580      stem(&z, "ssen", "", m_gt_0);
141581      break;
141582   }
141583 
141584   /* Step 4 */
141585   switch( z[1] ){
141586    case 'a':
141587      if( z[0]=='l' && m_gt_1(z+2) ){
141588        z += 2;
141589      }
141590      break;
141591    case 'c':
141592      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
141593        z += 4;
141594      }
141595      break;
141596    case 'e':
141597      if( z[0]=='r' && m_gt_1(z+2) ){
141598        z += 2;
141599      }
141600      break;
141601    case 'i':
141602      if( z[0]=='c' && m_gt_1(z+2) ){
141603        z += 2;
141604      }
141605      break;
141606    case 'l':
141607      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
141608        z += 4;
141609      }
141610      break;
141611    case 'n':
141612      if( z[0]=='t' ){
141613        if( z[2]=='a' ){
141614          if( m_gt_1(z+3) ){
141615            z += 3;
141616          }
141617        }else if( z[2]=='e' ){
141618          if( !stem(&z, "tneme", "", m_gt_1)
141619           && !stem(&z, "tnem", "", m_gt_1)
141620          ){
141621            stem(&z, "tne", "", m_gt_1);
141622          }
141623        }
141624      }
141625      break;
141626    case 'o':
141627      if( z[0]=='u' ){
141628        if( m_gt_1(z+2) ){
141629          z += 2;
141630        }
141631      }else if( z[3]=='s' || z[3]=='t' ){
141632        stem(&z, "noi", "", m_gt_1);
141633      }
141634      break;
141635    case 's':
141636      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
141637        z += 3;
141638      }
141639      break;
141640    case 't':
141641      if( !stem(&z, "eta", "", m_gt_1) ){
141642        stem(&z, "iti", "", m_gt_1);
141643      }
141644      break;
141645    case 'u':
141646      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
141647        z += 3;
141648      }
141649      break;
141650    case 'v':
141651    case 'z':
141652      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
141653        z += 3;
141654      }
141655      break;
141656   }
141657 
141658   /* Step 5a */
141659   if( z[0]=='e' ){
141660     if( m_gt_1(z+1) ){
141661       z++;
141662     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
141663       z++;
141664     }
141665   }
141666 
141667   /* Step 5b */
141668   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
141669     z++;
141670   }
141671 
141672   /* z[] is now the stemmed word in reverse order.  Flip it back
141673   ** around into forward order and return.
141674   */
141675   *pnOut = i = (int)strlen(z);
141676   zOut[i] = 0;
141677   while( *z ){
141678     zOut[--i] = *(z++);
141679   }
141680 }
141681 
141682 /*
141683 ** Characters that can be part of a token.  We assume any character
141684 ** whose value is greater than 0x80 (any UTF character) can be
141685 ** part of a token.  In other words, delimiters all must have
141686 ** values of 0x7f or lower.
141687 */
141688 static const char porterIdChar[] = {
141689 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
141690     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
141691     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
141692     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
141693     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
141694     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
141695 };
141696 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
141697 
141698 /*
141699 ** Extract the next token from a tokenization cursor.  The cursor must
141700 ** have been opened by a prior call to porterOpen().
141701 */
141702 static int porterNext(
141703   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
141704   const char **pzToken,               /* OUT: *pzToken is the token text */
141705   int *pnBytes,                       /* OUT: Number of bytes in token */
141706   int *piStartOffset,                 /* OUT: Starting offset of token */
141707   int *piEndOffset,                   /* OUT: Ending offset of token */
141708   int *piPosition                     /* OUT: Position integer of token */
141709 ){
141710   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
141711   const char *z = c->zInput;
141712 
141713   while( c->iOffset<c->nInput ){
141714     int iStartOffset, ch;
141715 
141716     /* Scan past delimiter characters */
141717     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
141718       c->iOffset++;
141719     }
141720 
141721     /* Count non-delimiter characters. */
141722     iStartOffset = c->iOffset;
141723     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
141724       c->iOffset++;
141725     }
141726 
141727     if( c->iOffset>iStartOffset ){
141728       int n = c->iOffset-iStartOffset;
141729       if( n>c->nAllocated ){
141730         char *pNew;
141731         c->nAllocated = n+20;
141732         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
141733         if( !pNew ) return SQLITE_NOMEM;
141734         c->zToken = pNew;
141735       }
141736       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
141737       *pzToken = c->zToken;
141738       *piStartOffset = iStartOffset;
141739       *piEndOffset = c->iOffset;
141740       *piPosition = c->iToken++;
141741       return SQLITE_OK;
141742     }
141743   }
141744   return SQLITE_DONE;
141745 }
141746 
141747 /*
141748 ** The set of routines that implement the porter-stemmer tokenizer
141749 */
141750 static const sqlite3_tokenizer_module porterTokenizerModule = {
141751   0,
141752   porterCreate,
141753   porterDestroy,
141754   porterOpen,
141755   porterClose,
141756   porterNext,
141757   0
141758 };
141759 
141760 /*
141761 ** Allocate a new porter tokenizer.  Return a pointer to the new
141762 ** tokenizer in *ppModule
141763 */
141764 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
141765   sqlite3_tokenizer_module const**ppModule
141766 ){
141767   *ppModule = &porterTokenizerModule;
141768 }
141769 
141770 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
141771 
141772 /************** End of fts3_porter.c *****************************************/
141773 /************** Begin file fts3_tokenizer.c **********************************/
141774 /*
141775 ** 2007 June 22
141776 **
141777 ** The author disclaims copyright to this source code.  In place of
141778 ** a legal notice, here is a blessing:
141779 **
141780 **    May you do good and not evil.
141781 **    May you find forgiveness for yourself and forgive others.
141782 **    May you share freely, never taking more than you give.
141783 **
141784 ******************************************************************************
141785 **
141786 ** This is part of an SQLite module implementing full-text search.
141787 ** This particular file implements the generic tokenizer interface.
141788 */
141789 
141790 /*
141791 ** The code in this file is only compiled if:
141792 **
141793 **     * The FTS3 module is being built as an extension
141794 **       (in which case SQLITE_CORE is not defined), or
141795 **
141796 **     * The FTS3 module is being built into the core of
141797 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
141798 */
141799 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141800 
141801 /* #include <assert.h> */
141802 /* #include <string.h> */
141803 
141804 /*
141805 ** Implementation of the SQL scalar function for accessing the underlying
141806 ** hash table. This function may be called as follows:
141807 **
141808 **   SELECT <function-name>(<key-name>);
141809 **   SELECT <function-name>(<key-name>, <pointer>);
141810 **
141811 ** where <function-name> is the name passed as the second argument
141812 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
141813 **
141814 ** If the <pointer> argument is specified, it must be a blob value
141815 ** containing a pointer to be stored as the hash data corresponding
141816 ** to the string <key-name>. If <pointer> is not specified, then
141817 ** the string <key-name> must already exist in the has table. Otherwise,
141818 ** an error is returned.
141819 **
141820 ** Whether or not the <pointer> argument is specified, the value returned
141821 ** is a blob containing the pointer stored as the hash data corresponding
141822 ** to string <key-name> (after the hash-table is updated, if applicable).
141823 */
141824 static void scalarFunc(
141825   sqlite3_context *context,
141826   int argc,
141827   sqlite3_value **argv
141828 ){
141829   Fts3Hash *pHash;
141830   void *pPtr = 0;
141831   const unsigned char *zName;
141832   int nName;
141833 
141834   assert( argc==1 || argc==2 );
141835 
141836   pHash = (Fts3Hash *)sqlite3_user_data(context);
141837 
141838   zName = sqlite3_value_text(argv[0]);
141839   nName = sqlite3_value_bytes(argv[0])+1;
141840 
141841   if( argc==2 ){
141842     void *pOld;
141843     int n = sqlite3_value_bytes(argv[1]);
141844     if( zName==0 || n!=sizeof(pPtr) ){
141845       sqlite3_result_error(context, "argument type mismatch", -1);
141846       return;
141847     }
141848     pPtr = *(void **)sqlite3_value_blob(argv[1]);
141849     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
141850     if( pOld==pPtr ){
141851       sqlite3_result_error(context, "out of memory", -1);
141852       return;
141853     }
141854   }else{
141855     if( zName ){
141856       pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
141857     }
141858     if( !pPtr ){
141859       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
141860       sqlite3_result_error(context, zErr, -1);
141861       sqlite3_free(zErr);
141862       return;
141863     }
141864   }
141865 
141866   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
141867 }
141868 
141869 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
141870   static const char isFtsIdChar[] = {
141871       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
141872       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
141873       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
141874       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
141875       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
141876       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
141877       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
141878       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
141879   };
141880   return (c&0x80 || isFtsIdChar[(int)(c)]);
141881 }
141882 
141883 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
141884   const char *z1;
141885   const char *z2 = 0;
141886 
141887   /* Find the start of the next token. */
141888   z1 = zStr;
141889   while( z2==0 ){
141890     char c = *z1;
141891     switch( c ){
141892       case '\0': return 0;        /* No more tokens here */
141893       case '\'':
141894       case '"':
141895       case '`': {
141896         z2 = z1;
141897         while( *++z2 && (*z2!=c || *++z2==c) );
141898         break;
141899       }
141900       case '[':
141901         z2 = &z1[1];
141902         while( *z2 && z2[0]!=']' ) z2++;
141903         if( *z2 ) z2++;
141904         break;
141905 
141906       default:
141907         if( sqlite3Fts3IsIdChar(*z1) ){
141908           z2 = &z1[1];
141909           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
141910         }else{
141911           z1++;
141912         }
141913     }
141914   }
141915 
141916   *pn = (int)(z2-z1);
141917   return z1;
141918 }
141919 
141920 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
141921   Fts3Hash *pHash,                /* Tokenizer hash table */
141922   const char *zArg,               /* Tokenizer name */
141923   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
141924   char **pzErr                    /* OUT: Set to malloced error message */
141925 ){
141926   int rc;
141927   char *z = (char *)zArg;
141928   int n = 0;
141929   char *zCopy;
141930   char *zEnd;                     /* Pointer to nul-term of zCopy */
141931   sqlite3_tokenizer_module *m;
141932 
141933   zCopy = sqlite3_mprintf("%s", zArg);
141934   if( !zCopy ) return SQLITE_NOMEM;
141935   zEnd = &zCopy[strlen(zCopy)];
141936 
141937   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
141938   if( z==0 ){
141939     assert( n==0 );
141940     z = zCopy;
141941   }
141942   z[n] = '\0';
141943   sqlite3Fts3Dequote(z);
141944 
141945   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
141946   if( !m ){
141947     sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
141948     rc = SQLITE_ERROR;
141949   }else{
141950     char const **aArg = 0;
141951     int iArg = 0;
141952     z = &z[n+1];
141953     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
141954       int nNew = sizeof(char *)*(iArg+1);
141955       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
141956       if( !aNew ){
141957         sqlite3_free(zCopy);
141958         sqlite3_free((void *)aArg);
141959         return SQLITE_NOMEM;
141960       }
141961       aArg = aNew;
141962       aArg[iArg++] = z;
141963       z[n] = '\0';
141964       sqlite3Fts3Dequote(z);
141965       z = &z[n+1];
141966     }
141967     rc = m->xCreate(iArg, aArg, ppTok);
141968     assert( rc!=SQLITE_OK || *ppTok );
141969     if( rc!=SQLITE_OK ){
141970       sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
141971     }else{
141972       (*ppTok)->pModule = m;
141973     }
141974     sqlite3_free((void *)aArg);
141975   }
141976 
141977   sqlite3_free(zCopy);
141978   return rc;
141979 }
141980 
141981 
141982 #ifdef SQLITE_TEST
141983 
141984 #include <tcl.h>
141985 /* #include <string.h> */
141986 
141987 /*
141988 ** Implementation of a special SQL scalar function for testing tokenizers
141989 ** designed to be used in concert with the Tcl testing framework. This
141990 ** function must be called with two or more arguments:
141991 **
141992 **   SELECT <function-name>(<key-name>, ..., <input-string>);
141993 **
141994 ** where <function-name> is the name passed as the second argument
141995 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
141996 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
141997 **
141998 ** The return value is a string that may be interpreted as a Tcl
141999 ** list. For each token in the <input-string>, three elements are
142000 ** added to the returned list. The first is the token position, the
142001 ** second is the token text (folded, stemmed, etc.) and the third is the
142002 ** substring of <input-string> associated with the token. For example,
142003 ** using the built-in "simple" tokenizer:
142004 **
142005 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
142006 **
142007 ** will return the string:
142008 **
142009 **   "{0 i I 1 dont don't 2 see see 3 how how}"
142010 **
142011 */
142012 static void testFunc(
142013   sqlite3_context *context,
142014   int argc,
142015   sqlite3_value **argv
142016 ){
142017   Fts3Hash *pHash;
142018   sqlite3_tokenizer_module *p;
142019   sqlite3_tokenizer *pTokenizer = 0;
142020   sqlite3_tokenizer_cursor *pCsr = 0;
142021 
142022   const char *zErr = 0;
142023 
142024   const char *zName;
142025   int nName;
142026   const char *zInput;
142027   int nInput;
142028 
142029   const char *azArg[64];
142030 
142031   const char *zToken;
142032   int nToken = 0;
142033   int iStart = 0;
142034   int iEnd = 0;
142035   int iPos = 0;
142036   int i;
142037 
142038   Tcl_Obj *pRet;
142039 
142040   if( argc<2 ){
142041     sqlite3_result_error(context, "insufficient arguments", -1);
142042     return;
142043   }
142044 
142045   nName = sqlite3_value_bytes(argv[0]);
142046   zName = (const char *)sqlite3_value_text(argv[0]);
142047   nInput = sqlite3_value_bytes(argv[argc-1]);
142048   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
142049 
142050   pHash = (Fts3Hash *)sqlite3_user_data(context);
142051   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
142052 
142053   if( !p ){
142054     char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
142055     sqlite3_result_error(context, zErr2, -1);
142056     sqlite3_free(zErr2);
142057     return;
142058   }
142059 
142060   pRet = Tcl_NewObj();
142061   Tcl_IncrRefCount(pRet);
142062 
142063   for(i=1; i<argc-1; i++){
142064     azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
142065   }
142066 
142067   if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
142068     zErr = "error in xCreate()";
142069     goto finish;
142070   }
142071   pTokenizer->pModule = p;
142072   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
142073     zErr = "error in xOpen()";
142074     goto finish;
142075   }
142076 
142077   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
142078     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
142079     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
142080     zToken = &zInput[iStart];
142081     nToken = iEnd-iStart;
142082     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
142083   }
142084 
142085   if( SQLITE_OK!=p->xClose(pCsr) ){
142086     zErr = "error in xClose()";
142087     goto finish;
142088   }
142089   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
142090     zErr = "error in xDestroy()";
142091     goto finish;
142092   }
142093 
142094 finish:
142095   if( zErr ){
142096     sqlite3_result_error(context, zErr, -1);
142097   }else{
142098     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
142099   }
142100   Tcl_DecrRefCount(pRet);
142101 }
142102 
142103 static
142104 int registerTokenizer(
142105   sqlite3 *db,
142106   char *zName,
142107   const sqlite3_tokenizer_module *p
142108 ){
142109   int rc;
142110   sqlite3_stmt *pStmt;
142111   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
142112 
142113   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
142114   if( rc!=SQLITE_OK ){
142115     return rc;
142116   }
142117 
142118   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
142119   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
142120   sqlite3_step(pStmt);
142121 
142122   return sqlite3_finalize(pStmt);
142123 }
142124 
142125 static
142126 int queryTokenizer(
142127   sqlite3 *db,
142128   char *zName,
142129   const sqlite3_tokenizer_module **pp
142130 ){
142131   int rc;
142132   sqlite3_stmt *pStmt;
142133   const char zSql[] = "SELECT fts3_tokenizer(?)";
142134 
142135   *pp = 0;
142136   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
142137   if( rc!=SQLITE_OK ){
142138     return rc;
142139   }
142140 
142141   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
142142   if( SQLITE_ROW==sqlite3_step(pStmt) ){
142143     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
142144       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
142145     }
142146   }
142147 
142148   return sqlite3_finalize(pStmt);
142149 }
142150 
142151 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
142152 
142153 /*
142154 ** Implementation of the scalar function fts3_tokenizer_internal_test().
142155 ** This function is used for testing only, it is not included in the
142156 ** build unless SQLITE_TEST is defined.
142157 **
142158 ** The purpose of this is to test that the fts3_tokenizer() function
142159 ** can be used as designed by the C-code in the queryTokenizer and
142160 ** registerTokenizer() functions above. These two functions are repeated
142161 ** in the README.tokenizer file as an example, so it is important to
142162 ** test them.
142163 **
142164 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
142165 ** function with no arguments. An assert() will fail if a problem is
142166 ** detected. i.e.:
142167 **
142168 **     SELECT fts3_tokenizer_internal_test();
142169 **
142170 */
142171 static void intTestFunc(
142172   sqlite3_context *context,
142173   int argc,
142174   sqlite3_value **argv
142175 ){
142176   int rc;
142177   const sqlite3_tokenizer_module *p1;
142178   const sqlite3_tokenizer_module *p2;
142179   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
142180 
142181   UNUSED_PARAMETER(argc);
142182   UNUSED_PARAMETER(argv);
142183 
142184   /* Test the query function */
142185   sqlite3Fts3SimpleTokenizerModule(&p1);
142186   rc = queryTokenizer(db, "simple", &p2);
142187   assert( rc==SQLITE_OK );
142188   assert( p1==p2 );
142189   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
142190   assert( rc==SQLITE_ERROR );
142191   assert( p2==0 );
142192   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
142193 
142194   /* Test the storage function */
142195   rc = registerTokenizer(db, "nosuchtokenizer", p1);
142196   assert( rc==SQLITE_OK );
142197   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
142198   assert( rc==SQLITE_OK );
142199   assert( p2==p1 );
142200 
142201   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
142202 }
142203 
142204 #endif
142205 
142206 /*
142207 ** Set up SQL objects in database db used to access the contents of
142208 ** the hash table pointed to by argument pHash. The hash table must
142209 ** been initialized to use string keys, and to take a private copy
142210 ** of the key when a value is inserted. i.e. by a call similar to:
142211 **
142212 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
142213 **
142214 ** This function adds a scalar function (see header comment above
142215 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
142216 ** defined at compilation time, a temporary virtual table (see header
142217 ** comment above struct HashTableVtab) to the database schema. Both
142218 ** provide read/write access to the contents of *pHash.
142219 **
142220 ** The third argument to this function, zName, is used as the name
142221 ** of both the scalar and, if created, the virtual table.
142222 */
142223 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
142224   sqlite3 *db,
142225   Fts3Hash *pHash,
142226   const char *zName
142227 ){
142228   int rc = SQLITE_OK;
142229   void *p = (void *)pHash;
142230   const int any = SQLITE_ANY;
142231 
142232 #ifdef SQLITE_TEST
142233   char *zTest = 0;
142234   char *zTest2 = 0;
142235   void *pdb = (void *)db;
142236   zTest = sqlite3_mprintf("%s_test", zName);
142237   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
142238   if( !zTest || !zTest2 ){
142239     rc = SQLITE_NOMEM;
142240   }
142241 #endif
142242 
142243   if( SQLITE_OK==rc ){
142244     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
142245   }
142246   if( SQLITE_OK==rc ){
142247     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
142248   }
142249 #ifdef SQLITE_TEST
142250   if( SQLITE_OK==rc ){
142251     rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
142252   }
142253   if( SQLITE_OK==rc ){
142254     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
142255   }
142256 #endif
142257 
142258 #ifdef SQLITE_TEST
142259   sqlite3_free(zTest);
142260   sqlite3_free(zTest2);
142261 #endif
142262 
142263   return rc;
142264 }
142265 
142266 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
142267 
142268 /************** End of fts3_tokenizer.c **************************************/
142269 /************** Begin file fts3_tokenizer1.c *********************************/
142270 /*
142271 ** 2006 Oct 10
142272 **
142273 ** The author disclaims copyright to this source code.  In place of
142274 ** a legal notice, here is a blessing:
142275 **
142276 **    May you do good and not evil.
142277 **    May you find forgiveness for yourself and forgive others.
142278 **    May you share freely, never taking more than you give.
142279 **
142280 ******************************************************************************
142281 **
142282 ** Implementation of the "simple" full-text-search tokenizer.
142283 */
142284 
142285 /*
142286 ** The code in this file is only compiled if:
142287 **
142288 **     * The FTS3 module is being built as an extension
142289 **       (in which case SQLITE_CORE is not defined), or
142290 **
142291 **     * The FTS3 module is being built into the core of
142292 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
142293 */
142294 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
142295 
142296 /* #include <assert.h> */
142297 /* #include <stdlib.h> */
142298 /* #include <stdio.h> */
142299 /* #include <string.h> */
142300 
142301 
142302 typedef struct simple_tokenizer {
142303   sqlite3_tokenizer base;
142304   char delim[128];             /* flag ASCII delimiters */
142305 } simple_tokenizer;
142306 
142307 typedef struct simple_tokenizer_cursor {
142308   sqlite3_tokenizer_cursor base;
142309   const char *pInput;          /* input we are tokenizing */
142310   int nBytes;                  /* size of the input */
142311   int iOffset;                 /* current position in pInput */
142312   int iToken;                  /* index of next token to be returned */
142313   char *pToken;                /* storage for current token */
142314   int nTokenAllocated;         /* space allocated to zToken buffer */
142315 } simple_tokenizer_cursor;
142316 
142317 
142318 static int simpleDelim(simple_tokenizer *t, unsigned char c){
142319   return c<0x80 && t->delim[c];
142320 }
142321 static int fts3_isalnum(int x){
142322   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
142323 }
142324 
142325 /*
142326 ** Create a new tokenizer instance.
142327 */
142328 static int simpleCreate(
142329   int argc, const char * const *argv,
142330   sqlite3_tokenizer **ppTokenizer
142331 ){
142332   simple_tokenizer *t;
142333 
142334   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
142335   if( t==NULL ) return SQLITE_NOMEM;
142336   memset(t, 0, sizeof(*t));
142337 
142338   /* TODO(shess) Delimiters need to remain the same from run to run,
142339   ** else we need to reindex.  One solution would be a meta-table to
142340   ** track such information in the database, then we'd only want this
142341   ** information on the initial create.
142342   */
142343   if( argc>1 ){
142344     int i, n = (int)strlen(argv[1]);
142345     for(i=0; i<n; i++){
142346       unsigned char ch = argv[1][i];
142347       /* We explicitly don't support UTF-8 delimiters for now. */
142348       if( ch>=0x80 ){
142349         sqlite3_free(t);
142350         return SQLITE_ERROR;
142351       }
142352       t->delim[ch] = 1;
142353     }
142354   } else {
142355     /* Mark non-alphanumeric ASCII characters as delimiters */
142356     int i;
142357     for(i=1; i<0x80; i++){
142358       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
142359     }
142360   }
142361 
142362   *ppTokenizer = &t->base;
142363   return SQLITE_OK;
142364 }
142365 
142366 /*
142367 ** Destroy a tokenizer
142368 */
142369 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
142370   sqlite3_free(pTokenizer);
142371   return SQLITE_OK;
142372 }
142373 
142374 /*
142375 ** Prepare to begin tokenizing a particular string.  The input
142376 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
142377 ** used to incrementally tokenize this string is returned in
142378 ** *ppCursor.
142379 */
142380 static int simpleOpen(
142381   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
142382   const char *pInput, int nBytes,        /* String to be tokenized */
142383   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
142384 ){
142385   simple_tokenizer_cursor *c;
142386 
142387   UNUSED_PARAMETER(pTokenizer);
142388 
142389   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
142390   if( c==NULL ) return SQLITE_NOMEM;
142391 
142392   c->pInput = pInput;
142393   if( pInput==0 ){
142394     c->nBytes = 0;
142395   }else if( nBytes<0 ){
142396     c->nBytes = (int)strlen(pInput);
142397   }else{
142398     c->nBytes = nBytes;
142399   }
142400   c->iOffset = 0;                 /* start tokenizing at the beginning */
142401   c->iToken = 0;
142402   c->pToken = NULL;               /* no space allocated, yet. */
142403   c->nTokenAllocated = 0;
142404 
142405   *ppCursor = &c->base;
142406   return SQLITE_OK;
142407 }
142408 
142409 /*
142410 ** Close a tokenization cursor previously opened by a call to
142411 ** simpleOpen() above.
142412 */
142413 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
142414   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
142415   sqlite3_free(c->pToken);
142416   sqlite3_free(c);
142417   return SQLITE_OK;
142418 }
142419 
142420 /*
142421 ** Extract the next token from a tokenization cursor.  The cursor must
142422 ** have been opened by a prior call to simpleOpen().
142423 */
142424 static int simpleNext(
142425   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
142426   const char **ppToken,               /* OUT: *ppToken is the token text */
142427   int *pnBytes,                       /* OUT: Number of bytes in token */
142428   int *piStartOffset,                 /* OUT: Starting offset of token */
142429   int *piEndOffset,                   /* OUT: Ending offset of token */
142430   int *piPosition                     /* OUT: Position integer of token */
142431 ){
142432   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
142433   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
142434   unsigned char *p = (unsigned char *)c->pInput;
142435 
142436   while( c->iOffset<c->nBytes ){
142437     int iStartOffset;
142438 
142439     /* Scan past delimiter characters */
142440     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
142441       c->iOffset++;
142442     }
142443 
142444     /* Count non-delimiter characters. */
142445     iStartOffset = c->iOffset;
142446     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
142447       c->iOffset++;
142448     }
142449 
142450     if( c->iOffset>iStartOffset ){
142451       int i, n = c->iOffset-iStartOffset;
142452       if( n>c->nTokenAllocated ){
142453         char *pNew;
142454         c->nTokenAllocated = n+20;
142455         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
142456         if( !pNew ) return SQLITE_NOMEM;
142457         c->pToken = pNew;
142458       }
142459       for(i=0; i<n; i++){
142460         /* TODO(shess) This needs expansion to handle UTF-8
142461         ** case-insensitivity.
142462         */
142463         unsigned char ch = p[iStartOffset+i];
142464         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
142465       }
142466       *ppToken = c->pToken;
142467       *pnBytes = n;
142468       *piStartOffset = iStartOffset;
142469       *piEndOffset = c->iOffset;
142470       *piPosition = c->iToken++;
142471 
142472       return SQLITE_OK;
142473     }
142474   }
142475   return SQLITE_DONE;
142476 }
142477 
142478 /*
142479 ** The set of routines that implement the simple tokenizer
142480 */
142481 static const sqlite3_tokenizer_module simpleTokenizerModule = {
142482   0,
142483   simpleCreate,
142484   simpleDestroy,
142485   simpleOpen,
142486   simpleClose,
142487   simpleNext,
142488   0,
142489 };
142490 
142491 /*
142492 ** Allocate a new simple tokenizer.  Return a pointer to the new
142493 ** tokenizer in *ppModule
142494 */
142495 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
142496   sqlite3_tokenizer_module const**ppModule
142497 ){
142498   *ppModule = &simpleTokenizerModule;
142499 }
142500 
142501 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
142502 
142503 /************** End of fts3_tokenizer1.c *************************************/
142504 /************** Begin file fts3_tokenize_vtab.c ******************************/
142505 /*
142506 ** 2013 Apr 22
142507 **
142508 ** The author disclaims copyright to this source code.  In place of
142509 ** a legal notice, here is a blessing:
142510 **
142511 **    May you do good and not evil.
142512 **    May you find forgiveness for yourself and forgive others.
142513 **    May you share freely, never taking more than you give.
142514 **
142515 ******************************************************************************
142516 **
142517 ** This file contains code for the "fts3tokenize" virtual table module.
142518 ** An fts3tokenize virtual table is created as follows:
142519 **
142520 **   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
142521 **       <tokenizer-name>, <arg-1>, ...
142522 **   );
142523 **
142524 ** The table created has the following schema:
142525 **
142526 **   CREATE TABLE <tbl>(input, token, start, end, position)
142527 **
142528 ** When queried, the query must include a WHERE clause of type:
142529 **
142530 **   input = <string>
142531 **
142532 ** The virtual table module tokenizes this <string>, using the FTS3
142533 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
142534 ** statement and returns one row for each token in the result. With
142535 ** fields set as follows:
142536 **
142537 **   input:   Always set to a copy of <string>
142538 **   token:   A token from the input.
142539 **   start:   Byte offset of the token within the input <string>.
142540 **   end:     Byte offset of the byte immediately following the end of the
142541 **            token within the input string.
142542 **   pos:     Token offset of token within input.
142543 **
142544 */
142545 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
142546 
142547 /* #include <string.h> */
142548 /* #include <assert.h> */
142549 
142550 typedef struct Fts3tokTable Fts3tokTable;
142551 typedef struct Fts3tokCursor Fts3tokCursor;
142552 
142553 /*
142554 ** Virtual table structure.
142555 */
142556 struct Fts3tokTable {
142557   sqlite3_vtab base;              /* Base class used by SQLite core */
142558   const sqlite3_tokenizer_module *pMod;
142559   sqlite3_tokenizer *pTok;
142560 };
142561 
142562 /*
142563 ** Virtual table cursor structure.
142564 */
142565 struct Fts3tokCursor {
142566   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
142567   char *zInput;                   /* Input string */
142568   sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
142569   int iRowid;                     /* Current 'rowid' value */
142570   const char *zToken;             /* Current 'token' value */
142571   int nToken;                     /* Size of zToken in bytes */
142572   int iStart;                     /* Current 'start' value */
142573   int iEnd;                       /* Current 'end' value */
142574   int iPos;                       /* Current 'pos' value */
142575 };
142576 
142577 /*
142578 ** Query FTS for the tokenizer implementation named zName.
142579 */
142580 static int fts3tokQueryTokenizer(
142581   Fts3Hash *pHash,
142582   const char *zName,
142583   const sqlite3_tokenizer_module **pp,
142584   char **pzErr
142585 ){
142586   sqlite3_tokenizer_module *p;
142587   int nName = (int)strlen(zName);
142588 
142589   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
142590   if( !p ){
142591     sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
142592     return SQLITE_ERROR;
142593   }
142594 
142595   *pp = p;
142596   return SQLITE_OK;
142597 }
142598 
142599 /*
142600 ** The second argument, argv[], is an array of pointers to nul-terminated
142601 ** strings. This function makes a copy of the array and strings into a
142602 ** single block of memory. It then dequotes any of the strings that appear
142603 ** to be quoted.
142604 **
142605 ** If successful, output parameter *pazDequote is set to point at the
142606 ** array of dequoted strings and SQLITE_OK is returned. The caller is
142607 ** responsible for eventually calling sqlite3_free() to free the array
142608 ** in this case. Or, if an error occurs, an SQLite error code is returned.
142609 ** The final value of *pazDequote is undefined in this case.
142610 */
142611 static int fts3tokDequoteArray(
142612   int argc,                       /* Number of elements in argv[] */
142613   const char * const *argv,       /* Input array */
142614   char ***pazDequote              /* Output array */
142615 ){
142616   int rc = SQLITE_OK;             /* Return code */
142617   if( argc==0 ){
142618     *pazDequote = 0;
142619   }else{
142620     int i;
142621     int nByte = 0;
142622     char **azDequote;
142623 
142624     for(i=0; i<argc; i++){
142625       nByte += (int)(strlen(argv[i]) + 1);
142626     }
142627 
142628     *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
142629     if( azDequote==0 ){
142630       rc = SQLITE_NOMEM;
142631     }else{
142632       char *pSpace = (char *)&azDequote[argc];
142633       for(i=0; i<argc; i++){
142634         int n = (int)strlen(argv[i]);
142635         azDequote[i] = pSpace;
142636         memcpy(pSpace, argv[i], n+1);
142637         sqlite3Fts3Dequote(pSpace);
142638         pSpace += (n+1);
142639       }
142640     }
142641   }
142642 
142643   return rc;
142644 }
142645 
142646 /*
142647 ** Schema of the tokenizer table.
142648 */
142649 #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
142650 
142651 /*
142652 ** This function does all the work for both the xConnect and xCreate methods.
142653 ** These tables have no persistent representation of their own, so xConnect
142654 ** and xCreate are identical operations.
142655 **
142656 **   argv[0]: module name
142657 **   argv[1]: database name
142658 **   argv[2]: table name
142659 **   argv[3]: first argument (tokenizer name)
142660 */
142661 static int fts3tokConnectMethod(
142662   sqlite3 *db,                    /* Database connection */
142663   void *pHash,                    /* Hash table of tokenizers */
142664   int argc,                       /* Number of elements in argv array */
142665   const char * const *argv,       /* xCreate/xConnect argument array */
142666   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
142667   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
142668 ){
142669   Fts3tokTable *pTab = 0;
142670   const sqlite3_tokenizer_module *pMod = 0;
142671   sqlite3_tokenizer *pTok = 0;
142672   int rc;
142673   char **azDequote = 0;
142674   int nDequote;
142675 
142676   rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
142677   if( rc!=SQLITE_OK ) return rc;
142678 
142679   nDequote = argc-3;
142680   rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
142681 
142682   if( rc==SQLITE_OK ){
142683     const char *zModule;
142684     if( nDequote<1 ){
142685       zModule = "simple";
142686     }else{
142687       zModule = azDequote[0];
142688     }
142689     rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
142690   }
142691 
142692   assert( (rc==SQLITE_OK)==(pMod!=0) );
142693   if( rc==SQLITE_OK ){
142694     const char * const *azArg = (const char * const *)&azDequote[1];
142695     rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
142696   }
142697 
142698   if( rc==SQLITE_OK ){
142699     pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
142700     if( pTab==0 ){
142701       rc = SQLITE_NOMEM;
142702     }
142703   }
142704 
142705   if( rc==SQLITE_OK ){
142706     memset(pTab, 0, sizeof(Fts3tokTable));
142707     pTab->pMod = pMod;
142708     pTab->pTok = pTok;
142709     *ppVtab = &pTab->base;
142710   }else{
142711     if( pTok ){
142712       pMod->xDestroy(pTok);
142713     }
142714   }
142715 
142716   sqlite3_free(azDequote);
142717   return rc;
142718 }
142719 
142720 /*
142721 ** This function does the work for both the xDisconnect and xDestroy methods.
142722 ** These tables have no persistent representation of their own, so xDisconnect
142723 ** and xDestroy are identical operations.
142724 */
142725 static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
142726   Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
142727 
142728   pTab->pMod->xDestroy(pTab->pTok);
142729   sqlite3_free(pTab);
142730   return SQLITE_OK;
142731 }
142732 
142733 /*
142734 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
142735 */
142736 static int fts3tokBestIndexMethod(
142737   sqlite3_vtab *pVTab,
142738   sqlite3_index_info *pInfo
142739 ){
142740   int i;
142741   UNUSED_PARAMETER(pVTab);
142742 
142743   for(i=0; i<pInfo->nConstraint; i++){
142744     if( pInfo->aConstraint[i].usable
142745      && pInfo->aConstraint[i].iColumn==0
142746      && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
142747     ){
142748       pInfo->idxNum = 1;
142749       pInfo->aConstraintUsage[i].argvIndex = 1;
142750       pInfo->aConstraintUsage[i].omit = 1;
142751       pInfo->estimatedCost = 1;
142752       return SQLITE_OK;
142753     }
142754   }
142755 
142756   pInfo->idxNum = 0;
142757   assert( pInfo->estimatedCost>1000000.0 );
142758 
142759   return SQLITE_OK;
142760 }
142761 
142762 /*
142763 ** xOpen - Open a cursor.
142764 */
142765 static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
142766   Fts3tokCursor *pCsr;
142767   UNUSED_PARAMETER(pVTab);
142768 
142769   pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
142770   if( pCsr==0 ){
142771     return SQLITE_NOMEM;
142772   }
142773   memset(pCsr, 0, sizeof(Fts3tokCursor));
142774 
142775   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
142776   return SQLITE_OK;
142777 }
142778 
142779 /*
142780 ** Reset the tokenizer cursor passed as the only argument. As if it had
142781 ** just been returned by fts3tokOpenMethod().
142782 */
142783 static void fts3tokResetCursor(Fts3tokCursor *pCsr){
142784   if( pCsr->pCsr ){
142785     Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
142786     pTab->pMod->xClose(pCsr->pCsr);
142787     pCsr->pCsr = 0;
142788   }
142789   sqlite3_free(pCsr->zInput);
142790   pCsr->zInput = 0;
142791   pCsr->zToken = 0;
142792   pCsr->nToken = 0;
142793   pCsr->iStart = 0;
142794   pCsr->iEnd = 0;
142795   pCsr->iPos = 0;
142796   pCsr->iRowid = 0;
142797 }
142798 
142799 /*
142800 ** xClose - Close a cursor.
142801 */
142802 static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
142803   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
142804 
142805   fts3tokResetCursor(pCsr);
142806   sqlite3_free(pCsr);
142807   return SQLITE_OK;
142808 }
142809 
142810 /*
142811 ** xNext - Advance the cursor to the next row, if any.
142812 */
142813 static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
142814   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
142815   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
142816   int rc;                         /* Return code */
142817 
142818   pCsr->iRowid++;
142819   rc = pTab->pMod->xNext(pCsr->pCsr,
142820       &pCsr->zToken, &pCsr->nToken,
142821       &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
142822   );
142823 
142824   if( rc!=SQLITE_OK ){
142825     fts3tokResetCursor(pCsr);
142826     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
142827   }
142828 
142829   return rc;
142830 }
142831 
142832 /*
142833 ** xFilter - Initialize a cursor to point at the start of its data.
142834 */
142835 static int fts3tokFilterMethod(
142836   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
142837   int idxNum,                     /* Strategy index */
142838   const char *idxStr,             /* Unused */
142839   int nVal,                       /* Number of elements in apVal */
142840   sqlite3_value **apVal           /* Arguments for the indexing scheme */
142841 ){
142842   int rc = SQLITE_ERROR;
142843   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
142844   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
142845   UNUSED_PARAMETER(idxStr);
142846   UNUSED_PARAMETER(nVal);
142847 
142848   fts3tokResetCursor(pCsr);
142849   if( idxNum==1 ){
142850     const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
142851     int nByte = sqlite3_value_bytes(apVal[0]);
142852     pCsr->zInput = sqlite3_malloc(nByte+1);
142853     if( pCsr->zInput==0 ){
142854       rc = SQLITE_NOMEM;
142855     }else{
142856       memcpy(pCsr->zInput, zByte, nByte);
142857       pCsr->zInput[nByte] = 0;
142858       rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
142859       if( rc==SQLITE_OK ){
142860         pCsr->pCsr->pTokenizer = pTab->pTok;
142861       }
142862     }
142863   }
142864 
142865   if( rc!=SQLITE_OK ) return rc;
142866   return fts3tokNextMethod(pCursor);
142867 }
142868 
142869 /*
142870 ** xEof - Return true if the cursor is at EOF, or false otherwise.
142871 */
142872 static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
142873   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
142874   return (pCsr->zToken==0);
142875 }
142876 
142877 /*
142878 ** xColumn - Return a column value.
142879 */
142880 static int fts3tokColumnMethod(
142881   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
142882   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
142883   int iCol                        /* Index of column to read value from */
142884 ){
142885   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
142886 
142887   /* CREATE TABLE x(input, token, start, end, position) */
142888   switch( iCol ){
142889     case 0:
142890       sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
142891       break;
142892     case 1:
142893       sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
142894       break;
142895     case 2:
142896       sqlite3_result_int(pCtx, pCsr->iStart);
142897       break;
142898     case 3:
142899       sqlite3_result_int(pCtx, pCsr->iEnd);
142900       break;
142901     default:
142902       assert( iCol==4 );
142903       sqlite3_result_int(pCtx, pCsr->iPos);
142904       break;
142905   }
142906   return SQLITE_OK;
142907 }
142908 
142909 /*
142910 ** xRowid - Return the current rowid for the cursor.
142911 */
142912 static int fts3tokRowidMethod(
142913   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
142914   sqlite_int64 *pRowid            /* OUT: Rowid value */
142915 ){
142916   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
142917   *pRowid = (sqlite3_int64)pCsr->iRowid;
142918   return SQLITE_OK;
142919 }
142920 
142921 /*
142922 ** Register the fts3tok module with database connection db. Return SQLITE_OK
142923 ** if successful or an error code if sqlite3_create_module() fails.
142924 */
142925 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
142926   static const sqlite3_module fts3tok_module = {
142927      0,                           /* iVersion      */
142928      fts3tokConnectMethod,        /* xCreate       */
142929      fts3tokConnectMethod,        /* xConnect      */
142930      fts3tokBestIndexMethod,      /* xBestIndex    */
142931      fts3tokDisconnectMethod,     /* xDisconnect   */
142932      fts3tokDisconnectMethod,     /* xDestroy      */
142933      fts3tokOpenMethod,           /* xOpen         */
142934      fts3tokCloseMethod,          /* xClose        */
142935      fts3tokFilterMethod,         /* xFilter       */
142936      fts3tokNextMethod,           /* xNext         */
142937      fts3tokEofMethod,            /* xEof          */
142938      fts3tokColumnMethod,         /* xColumn       */
142939      fts3tokRowidMethod,          /* xRowid        */
142940      0,                           /* xUpdate       */
142941      0,                           /* xBegin        */
142942      0,                           /* xSync         */
142943      0,                           /* xCommit       */
142944      0,                           /* xRollback     */
142945      0,                           /* xFindFunction */
142946      0,                           /* xRename       */
142947      0,                           /* xSavepoint    */
142948      0,                           /* xRelease      */
142949      0                            /* xRollbackTo   */
142950   };
142951   int rc;                         /* Return code */
142952 
142953   rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
142954   return rc;
142955 }
142956 
142957 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
142958 
142959 /************** End of fts3_tokenize_vtab.c **********************************/
142960 /************** Begin file fts3_write.c **************************************/
142961 /*
142962 ** 2009 Oct 23
142963 **
142964 ** The author disclaims copyright to this source code.  In place of
142965 ** a legal notice, here is a blessing:
142966 **
142967 **    May you do good and not evil.
142968 **    May you find forgiveness for yourself and forgive others.
142969 **    May you share freely, never taking more than you give.
142970 **
142971 ******************************************************************************
142972 **
142973 ** This file is part of the SQLite FTS3 extension module. Specifically,
142974 ** this file contains code to insert, update and delete rows from FTS3
142975 ** tables. It also contains code to merge FTS3 b-tree segments. Some
142976 ** of the sub-routines used to merge segments are also used by the query
142977 ** code in fts3.c.
142978 */
142979 
142980 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
142981 
142982 /* #include <string.h> */
142983 /* #include <assert.h> */
142984 /* #include <stdlib.h> */
142985 
142986 
142987 #define FTS_MAX_APPENDABLE_HEIGHT 16
142988 
142989 /*
142990 ** When full-text index nodes are loaded from disk, the buffer that they
142991 ** are loaded into has the following number of bytes of padding at the end
142992 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
142993 ** of 920 bytes is allocated for it.
142994 **
142995 ** This means that if we have a pointer into a buffer containing node data,
142996 ** it is always safe to read up to two varints from it without risking an
142997 ** overread, even if the node data is corrupted.
142998 */
142999 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
143000 
143001 /*
143002 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
143003 ** memory incrementally instead of all at once. This can be a big performance
143004 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
143005 ** method before retrieving all query results (as may happen, for example,
143006 ** if a query has a LIMIT clause).
143007 **
143008 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
143009 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
143010 ** The code is written so that the hard lower-limit for each of these values
143011 ** is 1. Clearly such small values would be inefficient, but can be useful
143012 ** for testing purposes.
143013 **
143014 ** If this module is built with SQLITE_TEST defined, these constants may
143015 ** be overridden at runtime for testing purposes. File fts3_test.c contains
143016 ** a Tcl interface to read and write the values.
143017 */
143018 #ifdef SQLITE_TEST
143019 int test_fts3_node_chunksize = (4*1024);
143020 int test_fts3_node_chunk_threshold = (4*1024)*4;
143021 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
143022 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
143023 #else
143024 # define FTS3_NODE_CHUNKSIZE (4*1024)
143025 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
143026 #endif
143027 
143028 /*
143029 ** The two values that may be meaningfully bound to the :1 parameter in
143030 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
143031 */
143032 #define FTS_STAT_DOCTOTAL      0
143033 #define FTS_STAT_INCRMERGEHINT 1
143034 #define FTS_STAT_AUTOINCRMERGE 2
143035 
143036 /*
143037 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
143038 ** and incremental merge operation that takes place. This is used for
143039 ** debugging FTS only, it should not usually be turned on in production
143040 ** systems.
143041 */
143042 #ifdef FTS3_LOG_MERGES
143043 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
143044   sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
143045 }
143046 #else
143047 #define fts3LogMerge(x, y)
143048 #endif
143049 
143050 
143051 typedef struct PendingList PendingList;
143052 typedef struct SegmentNode SegmentNode;
143053 typedef struct SegmentWriter SegmentWriter;
143054 
143055 /*
143056 ** An instance of the following data structure is used to build doclists
143057 ** incrementally. See function fts3PendingListAppend() for details.
143058 */
143059 struct PendingList {
143060   int nData;
143061   char *aData;
143062   int nSpace;
143063   sqlite3_int64 iLastDocid;
143064   sqlite3_int64 iLastCol;
143065   sqlite3_int64 iLastPos;
143066 };
143067 
143068 
143069 /*
143070 ** Each cursor has a (possibly empty) linked list of the following objects.
143071 */
143072 struct Fts3DeferredToken {
143073   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
143074   int iCol;                       /* Column token must occur in */
143075   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
143076   PendingList *pList;             /* Doclist is assembled here */
143077 };
143078 
143079 /*
143080 ** An instance of this structure is used to iterate through the terms on
143081 ** a contiguous set of segment b-tree leaf nodes. Although the details of
143082 ** this structure are only manipulated by code in this file, opaque handles
143083 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
143084 ** terms when querying the full-text index. See functions:
143085 **
143086 **   sqlite3Fts3SegReaderNew()
143087 **   sqlite3Fts3SegReaderFree()
143088 **   sqlite3Fts3SegReaderIterate()
143089 **
143090 ** Methods used to manipulate Fts3SegReader structures:
143091 **
143092 **   fts3SegReaderNext()
143093 **   fts3SegReaderFirstDocid()
143094 **   fts3SegReaderNextDocid()
143095 */
143096 struct Fts3SegReader {
143097   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
143098   u8 bLookup;                     /* True for a lookup only */
143099   u8 rootOnly;                    /* True for a root-only reader */
143100 
143101   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
143102   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
143103   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
143104   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
143105 
143106   char *aNode;                    /* Pointer to node data (or NULL) */
143107   int nNode;                      /* Size of buffer at aNode (or 0) */
143108   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
143109   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
143110 
143111   Fts3HashElem **ppNextElem;
143112 
143113   /* Variables set by fts3SegReaderNext(). These may be read directly
143114   ** by the caller. They are valid from the time SegmentReaderNew() returns
143115   ** until SegmentReaderNext() returns something other than SQLITE_OK
143116   ** (i.e. SQLITE_DONE).
143117   */
143118   int nTerm;                      /* Number of bytes in current term */
143119   char *zTerm;                    /* Pointer to current term */
143120   int nTermAlloc;                 /* Allocated size of zTerm buffer */
143121   char *aDoclist;                 /* Pointer to doclist of current entry */
143122   int nDoclist;                   /* Size of doclist in current entry */
143123 
143124   /* The following variables are used by fts3SegReaderNextDocid() to iterate
143125   ** through the current doclist (aDoclist/nDoclist).
143126   */
143127   char *pOffsetList;
143128   int nOffsetList;                /* For descending pending seg-readers only */
143129   sqlite3_int64 iDocid;
143130 };
143131 
143132 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
143133 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
143134 
143135 /*
143136 ** An instance of this structure is used to create a segment b-tree in the
143137 ** database. The internal details of this type are only accessed by the
143138 ** following functions:
143139 **
143140 **   fts3SegWriterAdd()
143141 **   fts3SegWriterFlush()
143142 **   fts3SegWriterFree()
143143 */
143144 struct SegmentWriter {
143145   SegmentNode *pTree;             /* Pointer to interior tree structure */
143146   sqlite3_int64 iFirst;           /* First slot in %_segments written */
143147   sqlite3_int64 iFree;            /* Next free slot in %_segments */
143148   char *zTerm;                    /* Pointer to previous term buffer */
143149   int nTerm;                      /* Number of bytes in zTerm */
143150   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
143151   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
143152   int nSize;                      /* Size of allocation at aData */
143153   int nData;                      /* Bytes of data in aData */
143154   char *aData;                    /* Pointer to block from malloc() */
143155   i64 nLeafData;                  /* Number of bytes of leaf data written */
143156 };
143157 
143158 /*
143159 ** Type SegmentNode is used by the following three functions to create
143160 ** the interior part of the segment b+-tree structures (everything except
143161 ** the leaf nodes). These functions and type are only ever used by code
143162 ** within the fts3SegWriterXXX() family of functions described above.
143163 **
143164 **   fts3NodeAddTerm()
143165 **   fts3NodeWrite()
143166 **   fts3NodeFree()
143167 **
143168 ** When a b+tree is written to the database (either as a result of a merge
143169 ** or the pending-terms table being flushed), leaves are written into the
143170 ** database file as soon as they are completely populated. The interior of
143171 ** the tree is assembled in memory and written out only once all leaves have
143172 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
143173 ** very large, meaning that the interior of the tree consumes relatively
143174 ** little memory.
143175 */
143176 struct SegmentNode {
143177   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
143178   SegmentNode *pRight;            /* Pointer to right-sibling */
143179   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
143180   int nEntry;                     /* Number of terms written to node so far */
143181   char *zTerm;                    /* Pointer to previous term buffer */
143182   int nTerm;                      /* Number of bytes in zTerm */
143183   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
143184   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
143185   int nData;                      /* Bytes of valid data so far */
143186   char *aData;                    /* Node data */
143187 };
143188 
143189 /*
143190 ** Valid values for the second argument to fts3SqlStmt().
143191 */
143192 #define SQL_DELETE_CONTENT             0
143193 #define SQL_IS_EMPTY                   1
143194 #define SQL_DELETE_ALL_CONTENT         2
143195 #define SQL_DELETE_ALL_SEGMENTS        3
143196 #define SQL_DELETE_ALL_SEGDIR          4
143197 #define SQL_DELETE_ALL_DOCSIZE         5
143198 #define SQL_DELETE_ALL_STAT            6
143199 #define SQL_SELECT_CONTENT_BY_ROWID    7
143200 #define SQL_NEXT_SEGMENT_INDEX         8
143201 #define SQL_INSERT_SEGMENTS            9
143202 #define SQL_NEXT_SEGMENTS_ID          10
143203 #define SQL_INSERT_SEGDIR             11
143204 #define SQL_SELECT_LEVEL              12
143205 #define SQL_SELECT_LEVEL_RANGE        13
143206 #define SQL_SELECT_LEVEL_COUNT        14
143207 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
143208 #define SQL_DELETE_SEGDIR_LEVEL       16
143209 #define SQL_DELETE_SEGMENTS_RANGE     17
143210 #define SQL_CONTENT_INSERT            18
143211 #define SQL_DELETE_DOCSIZE            19
143212 #define SQL_REPLACE_DOCSIZE           20
143213 #define SQL_SELECT_DOCSIZE            21
143214 #define SQL_SELECT_STAT               22
143215 #define SQL_REPLACE_STAT              23
143216 
143217 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
143218 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
143219 #define SQL_DELETE_SEGDIR_RANGE       26
143220 #define SQL_SELECT_ALL_LANGID         27
143221 #define SQL_FIND_MERGE_LEVEL          28
143222 #define SQL_MAX_LEAF_NODE_ESTIMATE    29
143223 #define SQL_DELETE_SEGDIR_ENTRY       30
143224 #define SQL_SHIFT_SEGDIR_ENTRY        31
143225 #define SQL_SELECT_SEGDIR             32
143226 #define SQL_CHOMP_SEGDIR              33
143227 #define SQL_SEGMENT_IS_APPENDABLE     34
143228 #define SQL_SELECT_INDEXES            35
143229 #define SQL_SELECT_MXLEVEL            36
143230 
143231 #define SQL_SELECT_LEVEL_RANGE2       37
143232 #define SQL_UPDATE_LEVEL_IDX          38
143233 #define SQL_UPDATE_LEVEL              39
143234 
143235 /*
143236 ** This function is used to obtain an SQLite prepared statement handle
143237 ** for the statement identified by the second argument. If successful,
143238 ** *pp is set to the requested statement handle and SQLITE_OK returned.
143239 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
143240 **
143241 ** If argument apVal is not NULL, then it must point to an array with
143242 ** at least as many entries as the requested statement has bound
143243 ** parameters. The values are bound to the statements parameters before
143244 ** returning.
143245 */
143246 static int fts3SqlStmt(
143247   Fts3Table *p,                   /* Virtual table handle */
143248   int eStmt,                      /* One of the SQL_XXX constants above */
143249   sqlite3_stmt **pp,              /* OUT: Statement handle */
143250   sqlite3_value **apVal           /* Values to bind to statement */
143251 ){
143252   const char *azSql[] = {
143253 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
143254 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
143255 /* 2  */  "DELETE FROM %Q.'%q_content'",
143256 /* 3  */  "DELETE FROM %Q.'%q_segments'",
143257 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
143258 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
143259 /* 6  */  "DELETE FROM %Q.'%q_stat'",
143260 /* 7  */  "SELECT %s WHERE rowid=?",
143261 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
143262 /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
143263 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
143264 /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
143265 
143266           /* Return segments in order from oldest to newest.*/
143267 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
143268             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
143269 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
143270             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
143271             "ORDER BY level DESC, idx ASC",
143272 
143273 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
143274 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
143275 
143276 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
143277 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
143278 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
143279 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
143280 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
143281 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
143282 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
143283 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
143284 /* 24 */  "",
143285 /* 25 */  "",
143286 
143287 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
143288 /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
143289 
143290 /* This statement is used to determine which level to read the input from
143291 ** when performing an incremental merge. It returns the absolute level number
143292 ** of the oldest level in the db that contains at least ? segments. Or,
143293 ** if no level in the FTS index contains more than ? segments, the statement
143294 ** returns zero rows.  */
143295 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
143296          "  ORDER BY (level %% 1024) ASC LIMIT 1",
143297 
143298 /* Estimate the upper limit on the number of leaf nodes in a new segment
143299 ** created by merging the oldest :2 segments from absolute level :1. See
143300 ** function sqlite3Fts3Incrmerge() for details.  */
143301 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
143302          "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
143303 
143304 /* SQL_DELETE_SEGDIR_ENTRY
143305 **   Delete the %_segdir entry on absolute level :1 with index :2.  */
143306 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
143307 
143308 /* SQL_SHIFT_SEGDIR_ENTRY
143309 **   Modify the idx value for the segment with idx=:3 on absolute level :2
143310 **   to :1.  */
143311 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
143312 
143313 /* SQL_SELECT_SEGDIR
143314 **   Read a single entry from the %_segdir table. The entry from absolute
143315 **   level :1 with index value :2.  */
143316 /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
143317             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
143318 
143319 /* SQL_CHOMP_SEGDIR
143320 **   Update the start_block (:1) and root (:2) fields of the %_segdir
143321 **   entry located on absolute level :3 with index :4.  */
143322 /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
143323             "WHERE level = ? AND idx = ?",
143324 
143325 /* SQL_SEGMENT_IS_APPENDABLE
143326 **   Return a single row if the segment with end_block=? is appendable. Or
143327 **   no rows otherwise.  */
143328 /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
143329 
143330 /* SQL_SELECT_INDEXES
143331 **   Return the list of valid segment indexes for absolute level ?  */
143332 /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
143333 
143334 /* SQL_SELECT_MXLEVEL
143335 **   Return the largest relative level in the FTS index or indexes.  */
143336 /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
143337 
143338           /* Return segments in order from oldest to newest.*/
143339 /* 37 */  "SELECT level, idx, end_block "
143340             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
143341             "ORDER BY level DESC, idx ASC",
143342 
143343           /* Update statements used while promoting segments */
143344 /* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
143345             "WHERE level=? AND idx=?",
143346 /* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
143347 
143348   };
143349   int rc = SQLITE_OK;
143350   sqlite3_stmt *pStmt;
143351 
143352   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
143353   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
143354 
143355   pStmt = p->aStmt[eStmt];
143356   if( !pStmt ){
143357     char *zSql;
143358     if( eStmt==SQL_CONTENT_INSERT ){
143359       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
143360     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
143361       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
143362     }else{
143363       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
143364     }
143365     if( !zSql ){
143366       rc = SQLITE_NOMEM;
143367     }else{
143368       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
143369       sqlite3_free(zSql);
143370       assert( rc==SQLITE_OK || pStmt==0 );
143371       p->aStmt[eStmt] = pStmt;
143372     }
143373   }
143374   if( apVal ){
143375     int i;
143376     int nParam = sqlite3_bind_parameter_count(pStmt);
143377     for(i=0; rc==SQLITE_OK && i<nParam; i++){
143378       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
143379     }
143380   }
143381   *pp = pStmt;
143382   return rc;
143383 }
143384 
143385 
143386 static int fts3SelectDocsize(
143387   Fts3Table *pTab,                /* FTS3 table handle */
143388   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
143389   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
143390 ){
143391   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
143392   int rc;                         /* Return code */
143393 
143394   rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
143395   if( rc==SQLITE_OK ){
143396     sqlite3_bind_int64(pStmt, 1, iDocid);
143397     rc = sqlite3_step(pStmt);
143398     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
143399       rc = sqlite3_reset(pStmt);
143400       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
143401       pStmt = 0;
143402     }else{
143403       rc = SQLITE_OK;
143404     }
143405   }
143406 
143407   *ppStmt = pStmt;
143408   return rc;
143409 }
143410 
143411 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
143412   Fts3Table *pTab,                /* Fts3 table handle */
143413   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
143414 ){
143415   sqlite3_stmt *pStmt = 0;
143416   int rc;
143417   rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
143418   if( rc==SQLITE_OK ){
143419     sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
143420     if( sqlite3_step(pStmt)!=SQLITE_ROW
143421      || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
143422     ){
143423       rc = sqlite3_reset(pStmt);
143424       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
143425       pStmt = 0;
143426     }
143427   }
143428   *ppStmt = pStmt;
143429   return rc;
143430 }
143431 
143432 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
143433   Fts3Table *pTab,                /* Fts3 table handle */
143434   sqlite3_int64 iDocid,           /* Docid to read size data for */
143435   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
143436 ){
143437   return fts3SelectDocsize(pTab, iDocid, ppStmt);
143438 }
143439 
143440 /*
143441 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
143442 ** array apVal[] to the SQL statement identified by eStmt, the statement
143443 ** is executed.
143444 **
143445 ** Returns SQLITE_OK if the statement is successfully executed, or an
143446 ** SQLite error code otherwise.
143447 */
143448 static void fts3SqlExec(
143449   int *pRC,                /* Result code */
143450   Fts3Table *p,            /* The FTS3 table */
143451   int eStmt,               /* Index of statement to evaluate */
143452   sqlite3_value **apVal    /* Parameters to bind */
143453 ){
143454   sqlite3_stmt *pStmt;
143455   int rc;
143456   if( *pRC ) return;
143457   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
143458   if( rc==SQLITE_OK ){
143459     sqlite3_step(pStmt);
143460     rc = sqlite3_reset(pStmt);
143461   }
143462   *pRC = rc;
143463 }
143464 
143465 
143466 /*
143467 ** This function ensures that the caller has obtained an exclusive
143468 ** shared-cache table-lock on the %_segdir table. This is required before
143469 ** writing data to the fts3 table. If this lock is not acquired first, then
143470 ** the caller may end up attempting to take this lock as part of committing
143471 ** a transaction, causing SQLite to return SQLITE_LOCKED or
143472 ** LOCKED_SHAREDCACHEto a COMMIT command.
143473 **
143474 ** It is best to avoid this because if FTS3 returns any error when
143475 ** committing a transaction, the whole transaction will be rolled back.
143476 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
143477 ** It can still happen if the user locks the underlying tables directly
143478 ** instead of accessing them via FTS.
143479 */
143480 static int fts3Writelock(Fts3Table *p){
143481   int rc = SQLITE_OK;
143482 
143483   if( p->nPendingData==0 ){
143484     sqlite3_stmt *pStmt;
143485     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
143486     if( rc==SQLITE_OK ){
143487       sqlite3_bind_null(pStmt, 1);
143488       sqlite3_step(pStmt);
143489       rc = sqlite3_reset(pStmt);
143490     }
143491   }
143492 
143493   return rc;
143494 }
143495 
143496 /*
143497 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
143498 ** Within each language id, a separate index is maintained to store the
143499 ** document terms, and each configured prefix size (configured the FTS
143500 ** "prefix=" option). And each index consists of multiple levels ("relative
143501 ** levels").
143502 **
143503 ** All three of these values (the language id, the specific index and the
143504 ** level within the index) are encoded in 64-bit integer values stored
143505 ** in the %_segdir table on disk. This function is used to convert three
143506 ** separate component values into the single 64-bit integer value that
143507 ** can be used to query the %_segdir table.
143508 **
143509 ** Specifically, each language-id/index combination is allocated 1024
143510 ** 64-bit integer level values ("absolute levels"). The main terms index
143511 ** for language-id 0 is allocate values 0-1023. The first prefix index
143512 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
143513 ** Language 1 indexes are allocated immediately following language 0.
143514 **
143515 ** So, for a system with nPrefix prefix indexes configured, the block of
143516 ** absolute levels that corresponds to language-id iLangid and index
143517 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
143518 */
143519 static sqlite3_int64 getAbsoluteLevel(
143520   Fts3Table *p,                   /* FTS3 table handle */
143521   int iLangid,                    /* Language id */
143522   int iIndex,                     /* Index in p->aIndex[] */
143523   int iLevel                      /* Level of segments */
143524 ){
143525   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
143526   assert( iLangid>=0 );
143527   assert( p->nIndex>0 );
143528   assert( iIndex>=0 && iIndex<p->nIndex );
143529 
143530   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
143531   return iBase + iLevel;
143532 }
143533 
143534 /*
143535 ** Set *ppStmt to a statement handle that may be used to iterate through
143536 ** all rows in the %_segdir table, from oldest to newest. If successful,
143537 ** return SQLITE_OK. If an error occurs while preparing the statement,
143538 ** return an SQLite error code.
143539 **
143540 ** There is only ever one instance of this SQL statement compiled for
143541 ** each FTS3 table.
143542 **
143543 ** The statement returns the following columns from the %_segdir table:
143544 **
143545 **   0: idx
143546 **   1: start_block
143547 **   2: leaves_end_block
143548 **   3: end_block
143549 **   4: root
143550 */
143551 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
143552   Fts3Table *p,                   /* FTS3 table */
143553   int iLangid,                    /* Language being queried */
143554   int iIndex,                     /* Index for p->aIndex[] */
143555   int iLevel,                     /* Level to select (relative level) */
143556   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
143557 ){
143558   int rc;
143559   sqlite3_stmt *pStmt = 0;
143560 
143561   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
143562   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
143563   assert( iIndex>=0 && iIndex<p->nIndex );
143564 
143565   if( iLevel<0 ){
143566     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
143567     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
143568     if( rc==SQLITE_OK ){
143569       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
143570       sqlite3_bind_int64(pStmt, 2,
143571           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
143572       );
143573     }
143574   }else{
143575     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
143576     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
143577     if( rc==SQLITE_OK ){
143578       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
143579     }
143580   }
143581   *ppStmt = pStmt;
143582   return rc;
143583 }
143584 
143585 
143586 /*
143587 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
143588 ** if successful, or an SQLite error code otherwise.
143589 **
143590 ** This function also serves to allocate the PendingList structure itself.
143591 ** For example, to create a new PendingList structure containing two
143592 ** varints:
143593 **
143594 **   PendingList *p = 0;
143595 **   fts3PendingListAppendVarint(&p, 1);
143596 **   fts3PendingListAppendVarint(&p, 2);
143597 */
143598 static int fts3PendingListAppendVarint(
143599   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
143600   sqlite3_int64 i                 /* Value to append to data */
143601 ){
143602   PendingList *p = *pp;
143603 
143604   /* Allocate or grow the PendingList as required. */
143605   if( !p ){
143606     p = sqlite3_malloc(sizeof(*p) + 100);
143607     if( !p ){
143608       return SQLITE_NOMEM;
143609     }
143610     p->nSpace = 100;
143611     p->aData = (char *)&p[1];
143612     p->nData = 0;
143613   }
143614   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
143615     int nNew = p->nSpace * 2;
143616     p = sqlite3_realloc(p, sizeof(*p) + nNew);
143617     if( !p ){
143618       sqlite3_free(*pp);
143619       *pp = 0;
143620       return SQLITE_NOMEM;
143621     }
143622     p->nSpace = nNew;
143623     p->aData = (char *)&p[1];
143624   }
143625 
143626   /* Append the new serialized varint to the end of the list. */
143627   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
143628   p->aData[p->nData] = '\0';
143629   *pp = p;
143630   return SQLITE_OK;
143631 }
143632 
143633 /*
143634 ** Add a docid/column/position entry to a PendingList structure. Non-zero
143635 ** is returned if the structure is sqlite3_realloced as part of adding
143636 ** the entry. Otherwise, zero.
143637 **
143638 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
143639 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
143640 ** it is set to SQLITE_OK.
143641 */
143642 static int fts3PendingListAppend(
143643   PendingList **pp,               /* IN/OUT: PendingList structure */
143644   sqlite3_int64 iDocid,           /* Docid for entry to add */
143645   sqlite3_int64 iCol,             /* Column for entry to add */
143646   sqlite3_int64 iPos,             /* Position of term for entry to add */
143647   int *pRc                        /* OUT: Return code */
143648 ){
143649   PendingList *p = *pp;
143650   int rc = SQLITE_OK;
143651 
143652   assert( !p || p->iLastDocid<=iDocid );
143653 
143654   if( !p || p->iLastDocid!=iDocid ){
143655     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
143656     if( p ){
143657       assert( p->nData<p->nSpace );
143658       assert( p->aData[p->nData]==0 );
143659       p->nData++;
143660     }
143661     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
143662       goto pendinglistappend_out;
143663     }
143664     p->iLastCol = -1;
143665     p->iLastPos = 0;
143666     p->iLastDocid = iDocid;
143667   }
143668   if( iCol>0 && p->iLastCol!=iCol ){
143669     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
143670      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
143671     ){
143672       goto pendinglistappend_out;
143673     }
143674     p->iLastCol = iCol;
143675     p->iLastPos = 0;
143676   }
143677   if( iCol>=0 ){
143678     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
143679     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
143680     if( rc==SQLITE_OK ){
143681       p->iLastPos = iPos;
143682     }
143683   }
143684 
143685  pendinglistappend_out:
143686   *pRc = rc;
143687   if( p!=*pp ){
143688     *pp = p;
143689     return 1;
143690   }
143691   return 0;
143692 }
143693 
143694 /*
143695 ** Free a PendingList object allocated by fts3PendingListAppend().
143696 */
143697 static void fts3PendingListDelete(PendingList *pList){
143698   sqlite3_free(pList);
143699 }
143700 
143701 /*
143702 ** Add an entry to one of the pending-terms hash tables.
143703 */
143704 static int fts3PendingTermsAddOne(
143705   Fts3Table *p,
143706   int iCol,
143707   int iPos,
143708   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
143709   const char *zToken,
143710   int nToken
143711 ){
143712   PendingList *pList;
143713   int rc = SQLITE_OK;
143714 
143715   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
143716   if( pList ){
143717     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
143718   }
143719   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
143720     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
143721       /* Malloc failed while inserting the new entry. This can only
143722       ** happen if there was no previous entry for this token.
143723       */
143724       assert( 0==fts3HashFind(pHash, zToken, nToken) );
143725       sqlite3_free(pList);
143726       rc = SQLITE_NOMEM;
143727     }
143728   }
143729   if( rc==SQLITE_OK ){
143730     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
143731   }
143732   return rc;
143733 }
143734 
143735 /*
143736 ** Tokenize the nul-terminated string zText and add all tokens to the
143737 ** pending-terms hash-table. The docid used is that currently stored in
143738 ** p->iPrevDocid, and the column is specified by argument iCol.
143739 **
143740 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
143741 */
143742 static int fts3PendingTermsAdd(
143743   Fts3Table *p,                   /* Table into which text will be inserted */
143744   int iLangid,                    /* Language id to use */
143745   const char *zText,              /* Text of document to be inserted */
143746   int iCol,                       /* Column into which text is being inserted */
143747   u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
143748 ){
143749   int rc;
143750   int iStart = 0;
143751   int iEnd = 0;
143752   int iPos = 0;
143753   int nWord = 0;
143754 
143755   char const *zToken;
143756   int nToken = 0;
143757 
143758   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
143759   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
143760   sqlite3_tokenizer_cursor *pCsr;
143761   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
143762       const char**,int*,int*,int*,int*);
143763 
143764   assert( pTokenizer && pModule );
143765 
143766   /* If the user has inserted a NULL value, this function may be called with
143767   ** zText==0. In this case, add zero token entries to the hash table and
143768   ** return early. */
143769   if( zText==0 ){
143770     *pnWord = 0;
143771     return SQLITE_OK;
143772   }
143773 
143774   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
143775   if( rc!=SQLITE_OK ){
143776     return rc;
143777   }
143778 
143779   xNext = pModule->xNext;
143780   while( SQLITE_OK==rc
143781       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
143782   ){
143783     int i;
143784     if( iPos>=nWord ) nWord = iPos+1;
143785 
143786     /* Positions cannot be negative; we use -1 as a terminator internally.
143787     ** Tokens must have a non-zero length.
143788     */
143789     if( iPos<0 || !zToken || nToken<=0 ){
143790       rc = SQLITE_ERROR;
143791       break;
143792     }
143793 
143794     /* Add the term to the terms index */
143795     rc = fts3PendingTermsAddOne(
143796         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
143797     );
143798 
143799     /* Add the term to each of the prefix indexes that it is not too
143800     ** short for. */
143801     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
143802       struct Fts3Index *pIndex = &p->aIndex[i];
143803       if( nToken<pIndex->nPrefix ) continue;
143804       rc = fts3PendingTermsAddOne(
143805           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
143806       );
143807     }
143808   }
143809 
143810   pModule->xClose(pCsr);
143811   *pnWord += nWord;
143812   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
143813 }
143814 
143815 /*
143816 ** Calling this function indicates that subsequent calls to
143817 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
143818 ** contents of the document with docid iDocid.
143819 */
143820 static int fts3PendingTermsDocid(
143821   Fts3Table *p,                   /* Full-text table handle */
143822   int iLangid,                    /* Language id of row being written */
143823   sqlite_int64 iDocid             /* Docid of row being written */
143824 ){
143825   assert( iLangid>=0 );
143826 
143827   /* TODO(shess) Explore whether partially flushing the buffer on
143828   ** forced-flush would provide better performance.  I suspect that if
143829   ** we ordered the doclists by size and flushed the largest until the
143830   ** buffer was half empty, that would let the less frequent terms
143831   ** generate longer doclists.
143832   */
143833   if( iDocid<=p->iPrevDocid
143834    || p->iPrevLangid!=iLangid
143835    || p->nPendingData>p->nMaxPendingData
143836   ){
143837     int rc = sqlite3Fts3PendingTermsFlush(p);
143838     if( rc!=SQLITE_OK ) return rc;
143839   }
143840   p->iPrevDocid = iDocid;
143841   p->iPrevLangid = iLangid;
143842   return SQLITE_OK;
143843 }
143844 
143845 /*
143846 ** Discard the contents of the pending-terms hash tables.
143847 */
143848 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
143849   int i;
143850   for(i=0; i<p->nIndex; i++){
143851     Fts3HashElem *pElem;
143852     Fts3Hash *pHash = &p->aIndex[i].hPending;
143853     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
143854       PendingList *pList = (PendingList *)fts3HashData(pElem);
143855       fts3PendingListDelete(pList);
143856     }
143857     fts3HashClear(pHash);
143858   }
143859   p->nPendingData = 0;
143860 }
143861 
143862 /*
143863 ** This function is called by the xUpdate() method as part of an INSERT
143864 ** operation. It adds entries for each term in the new record to the
143865 ** pendingTerms hash table.
143866 **
143867 ** Argument apVal is the same as the similarly named argument passed to
143868 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
143869 */
143870 static int fts3InsertTerms(
143871   Fts3Table *p,
143872   int iLangid,
143873   sqlite3_value **apVal,
143874   u32 *aSz
143875 ){
143876   int i;                          /* Iterator variable */
143877   for(i=2; i<p->nColumn+2; i++){
143878     int iCol = i-2;
143879     if( p->abNotindexed[iCol]==0 ){
143880       const char *zText = (const char *)sqlite3_value_text(apVal[i]);
143881       int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
143882       if( rc!=SQLITE_OK ){
143883         return rc;
143884       }
143885       aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
143886     }
143887   }
143888   return SQLITE_OK;
143889 }
143890 
143891 /*
143892 ** This function is called by the xUpdate() method for an INSERT operation.
143893 ** The apVal parameter is passed a copy of the apVal argument passed by
143894 ** SQLite to the xUpdate() method. i.e:
143895 **
143896 **   apVal[0]                Not used for INSERT.
143897 **   apVal[1]                rowid
143898 **   apVal[2]                Left-most user-defined column
143899 **   ...
143900 **   apVal[p->nColumn+1]     Right-most user-defined column
143901 **   apVal[p->nColumn+2]     Hidden column with same name as table
143902 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
143903 **   apVal[p->nColumn+4]     Hidden languageid column
143904 */
143905 static int fts3InsertData(
143906   Fts3Table *p,                   /* Full-text table */
143907   sqlite3_value **apVal,          /* Array of values to insert */
143908   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
143909 ){
143910   int rc;                         /* Return code */
143911   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
143912 
143913   if( p->zContentTbl ){
143914     sqlite3_value *pRowid = apVal[p->nColumn+3];
143915     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
143916       pRowid = apVal[1];
143917     }
143918     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
143919       return SQLITE_CONSTRAINT;
143920     }
143921     *piDocid = sqlite3_value_int64(pRowid);
143922     return SQLITE_OK;
143923   }
143924 
143925   /* Locate the statement handle used to insert data into the %_content
143926   ** table. The SQL for this statement is:
143927   **
143928   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
143929   **
143930   ** The statement features N '?' variables, where N is the number of user
143931   ** defined columns in the FTS3 table, plus one for the docid field.
143932   */
143933   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
143934   if( rc==SQLITE_OK && p->zLanguageid ){
143935     rc = sqlite3_bind_int(
143936         pContentInsert, p->nColumn+2,
143937         sqlite3_value_int(apVal[p->nColumn+4])
143938     );
143939   }
143940   if( rc!=SQLITE_OK ) return rc;
143941 
143942   /* There is a quirk here. The users INSERT statement may have specified
143943   ** a value for the "rowid" field, for the "docid" field, or for both.
143944   ** Which is a problem, since "rowid" and "docid" are aliases for the
143945   ** same value. For example:
143946   **
143947   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
143948   **
143949   ** In FTS3, this is an error. It is an error to specify non-NULL values
143950   ** for both docid and some other rowid alias.
143951   */
143952   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
143953     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
143954      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
143955     ){
143956       /* A rowid/docid conflict. */
143957       return SQLITE_ERROR;
143958     }
143959     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
143960     if( rc!=SQLITE_OK ) return rc;
143961   }
143962 
143963   /* Execute the statement to insert the record. Set *piDocid to the
143964   ** new docid value.
143965   */
143966   sqlite3_step(pContentInsert);
143967   rc = sqlite3_reset(pContentInsert);
143968 
143969   *piDocid = sqlite3_last_insert_rowid(p->db);
143970   return rc;
143971 }
143972 
143973 
143974 
143975 /*
143976 ** Remove all data from the FTS3 table. Clear the hash table containing
143977 ** pending terms.
143978 */
143979 static int fts3DeleteAll(Fts3Table *p, int bContent){
143980   int rc = SQLITE_OK;             /* Return code */
143981 
143982   /* Discard the contents of the pending-terms hash table. */
143983   sqlite3Fts3PendingTermsClear(p);
143984 
143985   /* Delete everything from the shadow tables. Except, leave %_content as
143986   ** is if bContent is false.  */
143987   assert( p->zContentTbl==0 || bContent==0 );
143988   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
143989   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
143990   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
143991   if( p->bHasDocsize ){
143992     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
143993   }
143994   if( p->bHasStat ){
143995     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
143996   }
143997   return rc;
143998 }
143999 
144000 /*
144001 **
144002 */
144003 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
144004   int iLangid = 0;
144005   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
144006   return iLangid;
144007 }
144008 
144009 /*
144010 ** The first element in the apVal[] array is assumed to contain the docid
144011 ** (an integer) of a row about to be deleted. Remove all terms from the
144012 ** full-text index.
144013 */
144014 static void fts3DeleteTerms(
144015   int *pRC,               /* Result code */
144016   Fts3Table *p,           /* The FTS table to delete from */
144017   sqlite3_value *pRowid,  /* The docid to be deleted */
144018   u32 *aSz,               /* Sizes of deleted document written here */
144019   int *pbFound            /* OUT: Set to true if row really does exist */
144020 ){
144021   int rc;
144022   sqlite3_stmt *pSelect;
144023 
144024   assert( *pbFound==0 );
144025   if( *pRC ) return;
144026   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
144027   if( rc==SQLITE_OK ){
144028     if( SQLITE_ROW==sqlite3_step(pSelect) ){
144029       int i;
144030       int iLangid = langidFromSelect(p, pSelect);
144031       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
144032       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
144033         int iCol = i-1;
144034         if( p->abNotindexed[iCol]==0 ){
144035           const char *zText = (const char *)sqlite3_column_text(pSelect, i);
144036           rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
144037           aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
144038         }
144039       }
144040       if( rc!=SQLITE_OK ){
144041         sqlite3_reset(pSelect);
144042         *pRC = rc;
144043         return;
144044       }
144045       *pbFound = 1;
144046     }
144047     rc = sqlite3_reset(pSelect);
144048   }else{
144049     sqlite3_reset(pSelect);
144050   }
144051   *pRC = rc;
144052 }
144053 
144054 /*
144055 ** Forward declaration to account for the circular dependency between
144056 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
144057 */
144058 static int fts3SegmentMerge(Fts3Table *, int, int, int);
144059 
144060 /*
144061 ** This function allocates a new level iLevel index in the segdir table.
144062 ** Usually, indexes are allocated within a level sequentially starting
144063 ** with 0, so the allocated index is one greater than the value returned
144064 ** by:
144065 **
144066 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
144067 **
144068 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
144069 ** level, they are merged into a single level (iLevel+1) segment and the
144070 ** allocated index is 0.
144071 **
144072 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
144073 ** returned. Otherwise, an SQLite error code is returned.
144074 */
144075 static int fts3AllocateSegdirIdx(
144076   Fts3Table *p,
144077   int iLangid,                    /* Language id */
144078   int iIndex,                     /* Index for p->aIndex */
144079   int iLevel,
144080   int *piIdx
144081 ){
144082   int rc;                         /* Return Code */
144083   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
144084   int iNext = 0;                  /* Result of query pNextIdx */
144085 
144086   assert( iLangid>=0 );
144087   assert( p->nIndex>=1 );
144088 
144089   /* Set variable iNext to the next available segdir index at level iLevel. */
144090   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
144091   if( rc==SQLITE_OK ){
144092     sqlite3_bind_int64(
144093         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
144094     );
144095     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
144096       iNext = sqlite3_column_int(pNextIdx, 0);
144097     }
144098     rc = sqlite3_reset(pNextIdx);
144099   }
144100 
144101   if( rc==SQLITE_OK ){
144102     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
144103     ** full, merge all segments in level iLevel into a single iLevel+1
144104     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
144105     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
144106     */
144107     if( iNext>=FTS3_MERGE_COUNT ){
144108       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
144109       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
144110       *piIdx = 0;
144111     }else{
144112       *piIdx = iNext;
144113     }
144114   }
144115 
144116   return rc;
144117 }
144118 
144119 /*
144120 ** The %_segments table is declared as follows:
144121 **
144122 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
144123 **
144124 ** This function reads data from a single row of the %_segments table. The
144125 ** specific row is identified by the iBlockid parameter. If paBlob is not
144126 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
144127 ** with the contents of the blob stored in the "block" column of the
144128 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
144129 ** to the size of the blob in bytes before returning.
144130 **
144131 ** If an error occurs, or the table does not contain the specified row,
144132 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
144133 ** paBlob is non-NULL, then it is the responsibility of the caller to
144134 ** eventually free the returned buffer.
144135 **
144136 ** This function may leave an open sqlite3_blob* handle in the
144137 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
144138 ** to this function. The handle may be closed by calling the
144139 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
144140 ** performance improvement, but the blob handle should always be closed
144141 ** before control is returned to the user (to prevent a lock being held
144142 ** on the database file for longer than necessary). Thus, any virtual table
144143 ** method (xFilter etc.) that may directly or indirectly call this function
144144 ** must call sqlite3Fts3SegmentsClose() before returning.
144145 */
144146 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
144147   Fts3Table *p,                   /* FTS3 table handle */
144148   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
144149   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
144150   int *pnBlob,                    /* OUT: Size of blob data */
144151   int *pnLoad                     /* OUT: Bytes actually loaded */
144152 ){
144153   int rc;                         /* Return code */
144154 
144155   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
144156   assert( pnBlob );
144157 
144158   if( p->pSegments ){
144159     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
144160   }else{
144161     if( 0==p->zSegmentsTbl ){
144162       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
144163       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
144164     }
144165     rc = sqlite3_blob_open(
144166        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
144167     );
144168   }
144169 
144170   if( rc==SQLITE_OK ){
144171     int nByte = sqlite3_blob_bytes(p->pSegments);
144172     *pnBlob = nByte;
144173     if( paBlob ){
144174       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
144175       if( !aByte ){
144176         rc = SQLITE_NOMEM;
144177       }else{
144178         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
144179           nByte = FTS3_NODE_CHUNKSIZE;
144180           *pnLoad = nByte;
144181         }
144182         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
144183         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
144184         if( rc!=SQLITE_OK ){
144185           sqlite3_free(aByte);
144186           aByte = 0;
144187         }
144188       }
144189       *paBlob = aByte;
144190     }
144191   }
144192 
144193   return rc;
144194 }
144195 
144196 /*
144197 ** Close the blob handle at p->pSegments, if it is open. See comments above
144198 ** the sqlite3Fts3ReadBlock() function for details.
144199 */
144200 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
144201   sqlite3_blob_close(p->pSegments);
144202   p->pSegments = 0;
144203 }
144204 
144205 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
144206   int nRead;                      /* Number of bytes to read */
144207   int rc;                         /* Return code */
144208 
144209   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
144210   rc = sqlite3_blob_read(
144211       pReader->pBlob,
144212       &pReader->aNode[pReader->nPopulate],
144213       nRead,
144214       pReader->nPopulate
144215   );
144216 
144217   if( rc==SQLITE_OK ){
144218     pReader->nPopulate += nRead;
144219     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
144220     if( pReader->nPopulate==pReader->nNode ){
144221       sqlite3_blob_close(pReader->pBlob);
144222       pReader->pBlob = 0;
144223       pReader->nPopulate = 0;
144224     }
144225   }
144226   return rc;
144227 }
144228 
144229 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
144230   int rc = SQLITE_OK;
144231   assert( !pReader->pBlob
144232        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
144233   );
144234   while( pReader->pBlob && rc==SQLITE_OK
144235      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
144236   ){
144237     rc = fts3SegReaderIncrRead(pReader);
144238   }
144239   return rc;
144240 }
144241 
144242 /*
144243 ** Set an Fts3SegReader cursor to point at EOF.
144244 */
144245 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
144246   if( !fts3SegReaderIsRootOnly(pSeg) ){
144247     sqlite3_free(pSeg->aNode);
144248     sqlite3_blob_close(pSeg->pBlob);
144249     pSeg->pBlob = 0;
144250   }
144251   pSeg->aNode = 0;
144252 }
144253 
144254 /*
144255 ** Move the iterator passed as the first argument to the next term in the
144256 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
144257 ** SQLITE_DONE. Otherwise, an SQLite error code.
144258 */
144259 static int fts3SegReaderNext(
144260   Fts3Table *p,
144261   Fts3SegReader *pReader,
144262   int bIncr
144263 ){
144264   int rc;                         /* Return code of various sub-routines */
144265   char *pNext;                    /* Cursor variable */
144266   int nPrefix;                    /* Number of bytes in term prefix */
144267   int nSuffix;                    /* Number of bytes in term suffix */
144268 
144269   if( !pReader->aDoclist ){
144270     pNext = pReader->aNode;
144271   }else{
144272     pNext = &pReader->aDoclist[pReader->nDoclist];
144273   }
144274 
144275   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
144276 
144277     if( fts3SegReaderIsPending(pReader) ){
144278       Fts3HashElem *pElem = *(pReader->ppNextElem);
144279       if( pElem==0 ){
144280         pReader->aNode = 0;
144281       }else{
144282         PendingList *pList = (PendingList *)fts3HashData(pElem);
144283         pReader->zTerm = (char *)fts3HashKey(pElem);
144284         pReader->nTerm = fts3HashKeysize(pElem);
144285         pReader->nNode = pReader->nDoclist = pList->nData + 1;
144286         pReader->aNode = pReader->aDoclist = pList->aData;
144287         pReader->ppNextElem++;
144288         assert( pReader->aNode );
144289       }
144290       return SQLITE_OK;
144291     }
144292 
144293     fts3SegReaderSetEof(pReader);
144294 
144295     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
144296     ** blocks have already been traversed.  */
144297     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
144298     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
144299       return SQLITE_OK;
144300     }
144301 
144302     rc = sqlite3Fts3ReadBlock(
144303         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
144304         (bIncr ? &pReader->nPopulate : 0)
144305     );
144306     if( rc!=SQLITE_OK ) return rc;
144307     assert( pReader->pBlob==0 );
144308     if( bIncr && pReader->nPopulate<pReader->nNode ){
144309       pReader->pBlob = p->pSegments;
144310       p->pSegments = 0;
144311     }
144312     pNext = pReader->aNode;
144313   }
144314 
144315   assert( !fts3SegReaderIsPending(pReader) );
144316 
144317   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
144318   if( rc!=SQLITE_OK ) return rc;
144319 
144320   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
144321   ** safe (no risk of overread) even if the node data is corrupted. */
144322   pNext += fts3GetVarint32(pNext, &nPrefix);
144323   pNext += fts3GetVarint32(pNext, &nSuffix);
144324   if( nPrefix<0 || nSuffix<=0
144325    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
144326   ){
144327     return FTS_CORRUPT_VTAB;
144328   }
144329 
144330   if( nPrefix+nSuffix>pReader->nTermAlloc ){
144331     int nNew = (nPrefix+nSuffix)*2;
144332     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
144333     if( !zNew ){
144334       return SQLITE_NOMEM;
144335     }
144336     pReader->zTerm = zNew;
144337     pReader->nTermAlloc = nNew;
144338   }
144339 
144340   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
144341   if( rc!=SQLITE_OK ) return rc;
144342 
144343   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
144344   pReader->nTerm = nPrefix+nSuffix;
144345   pNext += nSuffix;
144346   pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
144347   pReader->aDoclist = pNext;
144348   pReader->pOffsetList = 0;
144349 
144350   /* Check that the doclist does not appear to extend past the end of the
144351   ** b-tree node. And that the final byte of the doclist is 0x00. If either
144352   ** of these statements is untrue, then the data structure is corrupt.
144353   */
144354   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
144355    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
144356   ){
144357     return FTS_CORRUPT_VTAB;
144358   }
144359   return SQLITE_OK;
144360 }
144361 
144362 /*
144363 ** Set the SegReader to point to the first docid in the doclist associated
144364 ** with the current term.
144365 */
144366 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
144367   int rc = SQLITE_OK;
144368   assert( pReader->aDoclist );
144369   assert( !pReader->pOffsetList );
144370   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
144371     u8 bEof = 0;
144372     pReader->iDocid = 0;
144373     pReader->nOffsetList = 0;
144374     sqlite3Fts3DoclistPrev(0,
144375         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
144376         &pReader->iDocid, &pReader->nOffsetList, &bEof
144377     );
144378   }else{
144379     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
144380     if( rc==SQLITE_OK ){
144381       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
144382       pReader->pOffsetList = &pReader->aDoclist[n];
144383     }
144384   }
144385   return rc;
144386 }
144387 
144388 /*
144389 ** Advance the SegReader to point to the next docid in the doclist
144390 ** associated with the current term.
144391 **
144392 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
144393 ** *ppOffsetList is set to point to the first column-offset list
144394 ** in the doclist entry (i.e. immediately past the docid varint).
144395 ** *pnOffsetList is set to the length of the set of column-offset
144396 ** lists, not including the nul-terminator byte. For example:
144397 */
144398 static int fts3SegReaderNextDocid(
144399   Fts3Table *pTab,
144400   Fts3SegReader *pReader,         /* Reader to advance to next docid */
144401   char **ppOffsetList,            /* OUT: Pointer to current position-list */
144402   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
144403 ){
144404   int rc = SQLITE_OK;
144405   char *p = pReader->pOffsetList;
144406   char c = 0;
144407 
144408   assert( p );
144409 
144410   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
144411     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
144412     ** Pending-terms doclists are always built up in ascending order, so
144413     ** we have to iterate through them backwards here. */
144414     u8 bEof = 0;
144415     if( ppOffsetList ){
144416       *ppOffsetList = pReader->pOffsetList;
144417       *pnOffsetList = pReader->nOffsetList - 1;
144418     }
144419     sqlite3Fts3DoclistPrev(0,
144420         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
144421         &pReader->nOffsetList, &bEof
144422     );
144423     if( bEof ){
144424       pReader->pOffsetList = 0;
144425     }else{
144426       pReader->pOffsetList = p;
144427     }
144428   }else{
144429     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
144430 
144431     /* Pointer p currently points at the first byte of an offset list. The
144432     ** following block advances it to point one byte past the end of
144433     ** the same offset list. */
144434     while( 1 ){
144435 
144436       /* The following line of code (and the "p++" below the while() loop) is
144437       ** normally all that is required to move pointer p to the desired
144438       ** position. The exception is if this node is being loaded from disk
144439       ** incrementally and pointer "p" now points to the first byte past
144440       ** the populated part of pReader->aNode[].
144441       */
144442       while( *p | c ) c = *p++ & 0x80;
144443       assert( *p==0 );
144444 
144445       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
144446       rc = fts3SegReaderIncrRead(pReader);
144447       if( rc!=SQLITE_OK ) return rc;
144448     }
144449     p++;
144450 
144451     /* If required, populate the output variables with a pointer to and the
144452     ** size of the previous offset-list.
144453     */
144454     if( ppOffsetList ){
144455       *ppOffsetList = pReader->pOffsetList;
144456       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
144457     }
144458 
144459     /* List may have been edited in place by fts3EvalNearTrim() */
144460     while( p<pEnd && *p==0 ) p++;
144461 
144462     /* If there are no more entries in the doclist, set pOffsetList to
144463     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
144464     ** Fts3SegReader.pOffsetList to point to the next offset list before
144465     ** returning.
144466     */
144467     if( p>=pEnd ){
144468       pReader->pOffsetList = 0;
144469     }else{
144470       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
144471       if( rc==SQLITE_OK ){
144472         sqlite3_int64 iDelta;
144473         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
144474         if( pTab->bDescIdx ){
144475           pReader->iDocid -= iDelta;
144476         }else{
144477           pReader->iDocid += iDelta;
144478         }
144479       }
144480     }
144481   }
144482 
144483   return SQLITE_OK;
144484 }
144485 
144486 
144487 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
144488   Fts3Cursor *pCsr,
144489   Fts3MultiSegReader *pMsr,
144490   int *pnOvfl
144491 ){
144492   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
144493   int nOvfl = 0;
144494   int ii;
144495   int rc = SQLITE_OK;
144496   int pgsz = p->nPgsz;
144497 
144498   assert( p->bFts4 );
144499   assert( pgsz>0 );
144500 
144501   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
144502     Fts3SegReader *pReader = pMsr->apSegment[ii];
144503     if( !fts3SegReaderIsPending(pReader)
144504      && !fts3SegReaderIsRootOnly(pReader)
144505     ){
144506       sqlite3_int64 jj;
144507       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
144508         int nBlob;
144509         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
144510         if( rc!=SQLITE_OK ) break;
144511         if( (nBlob+35)>pgsz ){
144512           nOvfl += (nBlob + 34)/pgsz;
144513         }
144514       }
144515     }
144516   }
144517   *pnOvfl = nOvfl;
144518   return rc;
144519 }
144520 
144521 /*
144522 ** Free all allocations associated with the iterator passed as the
144523 ** second argument.
144524 */
144525 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
144526   if( pReader && !fts3SegReaderIsPending(pReader) ){
144527     sqlite3_free(pReader->zTerm);
144528     if( !fts3SegReaderIsRootOnly(pReader) ){
144529       sqlite3_free(pReader->aNode);
144530       sqlite3_blob_close(pReader->pBlob);
144531     }
144532   }
144533   sqlite3_free(pReader);
144534 }
144535 
144536 /*
144537 ** Allocate a new SegReader object.
144538 */
144539 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
144540   int iAge,                       /* Segment "age". */
144541   int bLookup,                    /* True for a lookup only */
144542   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
144543   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
144544   sqlite3_int64 iEndBlock,        /* Final block of segment */
144545   const char *zRoot,              /* Buffer containing root node */
144546   int nRoot,                      /* Size of buffer containing root node */
144547   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
144548 ){
144549   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
144550   int nExtra = 0;                 /* Bytes to allocate segment root node */
144551 
144552   assert( iStartLeaf<=iEndLeaf );
144553   if( iStartLeaf==0 ){
144554     nExtra = nRoot + FTS3_NODE_PADDING;
144555   }
144556 
144557   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
144558   if( !pReader ){
144559     return SQLITE_NOMEM;
144560   }
144561   memset(pReader, 0, sizeof(Fts3SegReader));
144562   pReader->iIdx = iAge;
144563   pReader->bLookup = bLookup!=0;
144564   pReader->iStartBlock = iStartLeaf;
144565   pReader->iLeafEndBlock = iEndLeaf;
144566   pReader->iEndBlock = iEndBlock;
144567 
144568   if( nExtra ){
144569     /* The entire segment is stored in the root node. */
144570     pReader->aNode = (char *)&pReader[1];
144571     pReader->rootOnly = 1;
144572     pReader->nNode = nRoot;
144573     memcpy(pReader->aNode, zRoot, nRoot);
144574     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
144575   }else{
144576     pReader->iCurrentBlock = iStartLeaf-1;
144577   }
144578   *ppReader = pReader;
144579   return SQLITE_OK;
144580 }
144581 
144582 /*
144583 ** This is a comparison function used as a qsort() callback when sorting
144584 ** an array of pending terms by term. This occurs as part of flushing
144585 ** the contents of the pending-terms hash table to the database.
144586 */
144587 static int SQLITE_CDECL fts3CompareElemByTerm(
144588   const void *lhs,
144589   const void *rhs
144590 ){
144591   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
144592   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
144593   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
144594   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
144595 
144596   int n = (n1<n2 ? n1 : n2);
144597   int c = memcmp(z1, z2, n);
144598   if( c==0 ){
144599     c = n1 - n2;
144600   }
144601   return c;
144602 }
144603 
144604 /*
144605 ** This function is used to allocate an Fts3SegReader that iterates through
144606 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
144607 **
144608 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
144609 ** through each term in the pending-terms table. Or, if isPrefixIter is
144610 ** non-zero, it iterates through each term and its prefixes. For example, if
144611 ** the pending terms hash table contains the terms "sqlite", "mysql" and
144612 ** "firebird", then the iterator visits the following 'terms' (in the order
144613 ** shown):
144614 **
144615 **   f fi fir fire fireb firebi firebir firebird
144616 **   m my mys mysq mysql
144617 **   s sq sql sqli sqlit sqlite
144618 **
144619 ** Whereas if isPrefixIter is zero, the terms visited are:
144620 **
144621 **   firebird mysql sqlite
144622 */
144623 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
144624   Fts3Table *p,                   /* Virtual table handle */
144625   int iIndex,                     /* Index for p->aIndex */
144626   const char *zTerm,              /* Term to search for */
144627   int nTerm,                      /* Size of buffer zTerm */
144628   int bPrefix,                    /* True for a prefix iterator */
144629   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
144630 ){
144631   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
144632   Fts3HashElem *pE;               /* Iterator variable */
144633   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
144634   int nElem = 0;                  /* Size of array at aElem */
144635   int rc = SQLITE_OK;             /* Return Code */
144636   Fts3Hash *pHash;
144637 
144638   pHash = &p->aIndex[iIndex].hPending;
144639   if( bPrefix ){
144640     int nAlloc = 0;               /* Size of allocated array at aElem */
144641 
144642     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
144643       char *zKey = (char *)fts3HashKey(pE);
144644       int nKey = fts3HashKeysize(pE);
144645       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
144646         if( nElem==nAlloc ){
144647           Fts3HashElem **aElem2;
144648           nAlloc += 16;
144649           aElem2 = (Fts3HashElem **)sqlite3_realloc(
144650               aElem, nAlloc*sizeof(Fts3HashElem *)
144651           );
144652           if( !aElem2 ){
144653             rc = SQLITE_NOMEM;
144654             nElem = 0;
144655             break;
144656           }
144657           aElem = aElem2;
144658         }
144659 
144660         aElem[nElem++] = pE;
144661       }
144662     }
144663 
144664     /* If more than one term matches the prefix, sort the Fts3HashElem
144665     ** objects in term order using qsort(). This uses the same comparison
144666     ** callback as is used when flushing terms to disk.
144667     */
144668     if( nElem>1 ){
144669       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
144670     }
144671 
144672   }else{
144673     /* The query is a simple term lookup that matches at most one term in
144674     ** the index. All that is required is a straight hash-lookup.
144675     **
144676     ** Because the stack address of pE may be accessed via the aElem pointer
144677     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
144678     ** within this entire function, not just this "else{...}" block.
144679     */
144680     pE = fts3HashFindElem(pHash, zTerm, nTerm);
144681     if( pE ){
144682       aElem = &pE;
144683       nElem = 1;
144684     }
144685   }
144686 
144687   if( nElem>0 ){
144688     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
144689     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
144690     if( !pReader ){
144691       rc = SQLITE_NOMEM;
144692     }else{
144693       memset(pReader, 0, nByte);
144694       pReader->iIdx = 0x7FFFFFFF;
144695       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
144696       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
144697     }
144698   }
144699 
144700   if( bPrefix ){
144701     sqlite3_free(aElem);
144702   }
144703   *ppReader = pReader;
144704   return rc;
144705 }
144706 
144707 /*
144708 ** Compare the entries pointed to by two Fts3SegReader structures.
144709 ** Comparison is as follows:
144710 **
144711 **   1) EOF is greater than not EOF.
144712 **
144713 **   2) The current terms (if any) are compared using memcmp(). If one
144714 **      term is a prefix of another, the longer term is considered the
144715 **      larger.
144716 **
144717 **   3) By segment age. An older segment is considered larger.
144718 */
144719 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
144720   int rc;
144721   if( pLhs->aNode && pRhs->aNode ){
144722     int rc2 = pLhs->nTerm - pRhs->nTerm;
144723     if( rc2<0 ){
144724       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
144725     }else{
144726       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
144727     }
144728     if( rc==0 ){
144729       rc = rc2;
144730     }
144731   }else{
144732     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
144733   }
144734   if( rc==0 ){
144735     rc = pRhs->iIdx - pLhs->iIdx;
144736   }
144737   assert( rc!=0 );
144738   return rc;
144739 }
144740 
144741 /*
144742 ** A different comparison function for SegReader structures. In this
144743 ** version, it is assumed that each SegReader points to an entry in
144744 ** a doclist for identical terms. Comparison is made as follows:
144745 **
144746 **   1) EOF (end of doclist in this case) is greater than not EOF.
144747 **
144748 **   2) By current docid.
144749 **
144750 **   3) By segment age. An older segment is considered larger.
144751 */
144752 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
144753   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
144754   if( rc==0 ){
144755     if( pLhs->iDocid==pRhs->iDocid ){
144756       rc = pRhs->iIdx - pLhs->iIdx;
144757     }else{
144758       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
144759     }
144760   }
144761   assert( pLhs->aNode && pRhs->aNode );
144762   return rc;
144763 }
144764 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
144765   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
144766   if( rc==0 ){
144767     if( pLhs->iDocid==pRhs->iDocid ){
144768       rc = pRhs->iIdx - pLhs->iIdx;
144769     }else{
144770       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
144771     }
144772   }
144773   assert( pLhs->aNode && pRhs->aNode );
144774   return rc;
144775 }
144776 
144777 /*
144778 ** Compare the term that the Fts3SegReader object passed as the first argument
144779 ** points to with the term specified by arguments zTerm and nTerm.
144780 **
144781 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
144782 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
144783 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
144784 */
144785 static int fts3SegReaderTermCmp(
144786   Fts3SegReader *pSeg,            /* Segment reader object */
144787   const char *zTerm,              /* Term to compare to */
144788   int nTerm                       /* Size of term zTerm in bytes */
144789 ){
144790   int res = 0;
144791   if( pSeg->aNode ){
144792     if( pSeg->nTerm>nTerm ){
144793       res = memcmp(pSeg->zTerm, zTerm, nTerm);
144794     }else{
144795       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
144796     }
144797     if( res==0 ){
144798       res = pSeg->nTerm-nTerm;
144799     }
144800   }
144801   return res;
144802 }
144803 
144804 /*
144805 ** Argument apSegment is an array of nSegment elements. It is known that
144806 ** the final (nSegment-nSuspect) members are already in sorted order
144807 ** (according to the comparison function provided). This function shuffles
144808 ** the array around until all entries are in sorted order.
144809 */
144810 static void fts3SegReaderSort(
144811   Fts3SegReader **apSegment,                     /* Array to sort entries of */
144812   int nSegment,                                  /* Size of apSegment array */
144813   int nSuspect,                                  /* Unsorted entry count */
144814   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
144815 ){
144816   int i;                          /* Iterator variable */
144817 
144818   assert( nSuspect<=nSegment );
144819 
144820   if( nSuspect==nSegment ) nSuspect--;
144821   for(i=nSuspect-1; i>=0; i--){
144822     int j;
144823     for(j=i; j<(nSegment-1); j++){
144824       Fts3SegReader *pTmp;
144825       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
144826       pTmp = apSegment[j+1];
144827       apSegment[j+1] = apSegment[j];
144828       apSegment[j] = pTmp;
144829     }
144830   }
144831 
144832 #ifndef NDEBUG
144833   /* Check that the list really is sorted now. */
144834   for(i=0; i<(nSuspect-1); i++){
144835     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
144836   }
144837 #endif
144838 }
144839 
144840 /*
144841 ** Insert a record into the %_segments table.
144842 */
144843 static int fts3WriteSegment(
144844   Fts3Table *p,                   /* Virtual table handle */
144845   sqlite3_int64 iBlock,           /* Block id for new block */
144846   char *z,                        /* Pointer to buffer containing block data */
144847   int n                           /* Size of buffer z in bytes */
144848 ){
144849   sqlite3_stmt *pStmt;
144850   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
144851   if( rc==SQLITE_OK ){
144852     sqlite3_bind_int64(pStmt, 1, iBlock);
144853     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
144854     sqlite3_step(pStmt);
144855     rc = sqlite3_reset(pStmt);
144856   }
144857   return rc;
144858 }
144859 
144860 /*
144861 ** Find the largest relative level number in the table. If successful, set
144862 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
144863 ** set *pnMax to zero and return an SQLite error code.
144864 */
144865 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
144866   int rc;
144867   int mxLevel = 0;
144868   sqlite3_stmt *pStmt = 0;
144869 
144870   rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
144871   if( rc==SQLITE_OK ){
144872     if( SQLITE_ROW==sqlite3_step(pStmt) ){
144873       mxLevel = sqlite3_column_int(pStmt, 0);
144874     }
144875     rc = sqlite3_reset(pStmt);
144876   }
144877   *pnMax = mxLevel;
144878   return rc;
144879 }
144880 
144881 /*
144882 ** Insert a record into the %_segdir table.
144883 */
144884 static int fts3WriteSegdir(
144885   Fts3Table *p,                   /* Virtual table handle */
144886   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
144887   int iIdx,                       /* Value for "idx" field */
144888   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
144889   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
144890   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
144891   sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
144892   char *zRoot,                    /* Blob value for "root" field */
144893   int nRoot                       /* Number of bytes in buffer zRoot */
144894 ){
144895   sqlite3_stmt *pStmt;
144896   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
144897   if( rc==SQLITE_OK ){
144898     sqlite3_bind_int64(pStmt, 1, iLevel);
144899     sqlite3_bind_int(pStmt, 2, iIdx);
144900     sqlite3_bind_int64(pStmt, 3, iStartBlock);
144901     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
144902     if( nLeafData==0 ){
144903       sqlite3_bind_int64(pStmt, 5, iEndBlock);
144904     }else{
144905       char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
144906       if( !zEnd ) return SQLITE_NOMEM;
144907       sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
144908     }
144909     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
144910     sqlite3_step(pStmt);
144911     rc = sqlite3_reset(pStmt);
144912   }
144913   return rc;
144914 }
144915 
144916 /*
144917 ** Return the size of the common prefix (if any) shared by zPrev and
144918 ** zNext, in bytes. For example,
144919 **
144920 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
144921 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
144922 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
144923 */
144924 static int fts3PrefixCompress(
144925   const char *zPrev,              /* Buffer containing previous term */
144926   int nPrev,                      /* Size of buffer zPrev in bytes */
144927   const char *zNext,              /* Buffer containing next term */
144928   int nNext                       /* Size of buffer zNext in bytes */
144929 ){
144930   int n;
144931   UNUSED_PARAMETER(nNext);
144932   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
144933   return n;
144934 }
144935 
144936 /*
144937 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
144938 ** (according to memcmp) than the previous term.
144939 */
144940 static int fts3NodeAddTerm(
144941   Fts3Table *p,                   /* Virtual table handle */
144942   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
144943   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
144944   const char *zTerm,              /* Pointer to buffer containing term */
144945   int nTerm                       /* Size of term in bytes */
144946 ){
144947   SegmentNode *pTree = *ppTree;
144948   int rc;
144949   SegmentNode *pNew;
144950 
144951   /* First try to append the term to the current node. Return early if
144952   ** this is possible.
144953   */
144954   if( pTree ){
144955     int nData = pTree->nData;     /* Current size of node in bytes */
144956     int nReq = nData;             /* Required space after adding zTerm */
144957     int nPrefix;                  /* Number of bytes of prefix compression */
144958     int nSuffix;                  /* Suffix length */
144959 
144960     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
144961     nSuffix = nTerm-nPrefix;
144962 
144963     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
144964     if( nReq<=p->nNodeSize || !pTree->zTerm ){
144965 
144966       if( nReq>p->nNodeSize ){
144967         /* An unusual case: this is the first term to be added to the node
144968         ** and the static node buffer (p->nNodeSize bytes) is not large
144969         ** enough. Use a separately malloced buffer instead This wastes
144970         ** p->nNodeSize bytes, but since this scenario only comes about when
144971         ** the database contain two terms that share a prefix of almost 2KB,
144972         ** this is not expected to be a serious problem.
144973         */
144974         assert( pTree->aData==(char *)&pTree[1] );
144975         pTree->aData = (char *)sqlite3_malloc(nReq);
144976         if( !pTree->aData ){
144977           return SQLITE_NOMEM;
144978         }
144979       }
144980 
144981       if( pTree->zTerm ){
144982         /* There is no prefix-length field for first term in a node */
144983         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
144984       }
144985 
144986       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
144987       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
144988       pTree->nData = nData + nSuffix;
144989       pTree->nEntry++;
144990 
144991       if( isCopyTerm ){
144992         if( pTree->nMalloc<nTerm ){
144993           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
144994           if( !zNew ){
144995             return SQLITE_NOMEM;
144996           }
144997           pTree->nMalloc = nTerm*2;
144998           pTree->zMalloc = zNew;
144999         }
145000         pTree->zTerm = pTree->zMalloc;
145001         memcpy(pTree->zTerm, zTerm, nTerm);
145002         pTree->nTerm = nTerm;
145003       }else{
145004         pTree->zTerm = (char *)zTerm;
145005         pTree->nTerm = nTerm;
145006       }
145007       return SQLITE_OK;
145008     }
145009   }
145010 
145011   /* If control flows to here, it was not possible to append zTerm to the
145012   ** current node. Create a new node (a right-sibling of the current node).
145013   ** If this is the first node in the tree, the term is added to it.
145014   **
145015   ** Otherwise, the term is not added to the new node, it is left empty for
145016   ** now. Instead, the term is inserted into the parent of pTree. If pTree
145017   ** has no parent, one is created here.
145018   */
145019   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
145020   if( !pNew ){
145021     return SQLITE_NOMEM;
145022   }
145023   memset(pNew, 0, sizeof(SegmentNode));
145024   pNew->nData = 1 + FTS3_VARINT_MAX;
145025   pNew->aData = (char *)&pNew[1];
145026 
145027   if( pTree ){
145028     SegmentNode *pParent = pTree->pParent;
145029     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
145030     if( pTree->pParent==0 ){
145031       pTree->pParent = pParent;
145032     }
145033     pTree->pRight = pNew;
145034     pNew->pLeftmost = pTree->pLeftmost;
145035     pNew->pParent = pParent;
145036     pNew->zMalloc = pTree->zMalloc;
145037     pNew->nMalloc = pTree->nMalloc;
145038     pTree->zMalloc = 0;
145039   }else{
145040     pNew->pLeftmost = pNew;
145041     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
145042   }
145043 
145044   *ppTree = pNew;
145045   return rc;
145046 }
145047 
145048 /*
145049 ** Helper function for fts3NodeWrite().
145050 */
145051 static int fts3TreeFinishNode(
145052   SegmentNode *pTree,
145053   int iHeight,
145054   sqlite3_int64 iLeftChild
145055 ){
145056   int nStart;
145057   assert( iHeight>=1 && iHeight<128 );
145058   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
145059   pTree->aData[nStart] = (char)iHeight;
145060   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
145061   return nStart;
145062 }
145063 
145064 /*
145065 ** Write the buffer for the segment node pTree and all of its peers to the
145066 ** database. Then call this function recursively to write the parent of
145067 ** pTree and its peers to the database.
145068 **
145069 ** Except, if pTree is a root node, do not write it to the database. Instead,
145070 ** set output variables *paRoot and *pnRoot to contain the root node.
145071 **
145072 ** If successful, SQLITE_OK is returned and output variable *piLast is
145073 ** set to the largest blockid written to the database (or zero if no
145074 ** blocks were written to the db). Otherwise, an SQLite error code is
145075 ** returned.
145076 */
145077 static int fts3NodeWrite(
145078   Fts3Table *p,                   /* Virtual table handle */
145079   SegmentNode *pTree,             /* SegmentNode handle */
145080   int iHeight,                    /* Height of this node in tree */
145081   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
145082   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
145083   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
145084   char **paRoot,                  /* OUT: Data for root node */
145085   int *pnRoot                     /* OUT: Size of root node in bytes */
145086 ){
145087   int rc = SQLITE_OK;
145088 
145089   if( !pTree->pParent ){
145090     /* Root node of the tree. */
145091     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
145092     *piLast = iFree-1;
145093     *pnRoot = pTree->nData - nStart;
145094     *paRoot = &pTree->aData[nStart];
145095   }else{
145096     SegmentNode *pIter;
145097     sqlite3_int64 iNextFree = iFree;
145098     sqlite3_int64 iNextLeaf = iLeaf;
145099     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
145100       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
145101       int nWrite = pIter->nData - nStart;
145102 
145103       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
145104       iNextFree++;
145105       iNextLeaf += (pIter->nEntry+1);
145106     }
145107     if( rc==SQLITE_OK ){
145108       assert( iNextLeaf==iFree );
145109       rc = fts3NodeWrite(
145110           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
145111       );
145112     }
145113   }
145114 
145115   return rc;
145116 }
145117 
145118 /*
145119 ** Free all memory allocations associated with the tree pTree.
145120 */
145121 static void fts3NodeFree(SegmentNode *pTree){
145122   if( pTree ){
145123     SegmentNode *p = pTree->pLeftmost;
145124     fts3NodeFree(p->pParent);
145125     while( p ){
145126       SegmentNode *pRight = p->pRight;
145127       if( p->aData!=(char *)&p[1] ){
145128         sqlite3_free(p->aData);
145129       }
145130       assert( pRight==0 || p->zMalloc==0 );
145131       sqlite3_free(p->zMalloc);
145132       sqlite3_free(p);
145133       p = pRight;
145134     }
145135   }
145136 }
145137 
145138 /*
145139 ** Add a term to the segment being constructed by the SegmentWriter object
145140 ** *ppWriter. When adding the first term to a segment, *ppWriter should
145141 ** be passed NULL. This function will allocate a new SegmentWriter object
145142 ** and return it via the input/output variable *ppWriter in this case.
145143 **
145144 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
145145 */
145146 static int fts3SegWriterAdd(
145147   Fts3Table *p,                   /* Virtual table handle */
145148   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
145149   int isCopyTerm,                 /* True if buffer zTerm must be copied */
145150   const char *zTerm,              /* Pointer to buffer containing term */
145151   int nTerm,                      /* Size of term in bytes */
145152   const char *aDoclist,           /* Pointer to buffer containing doclist */
145153   int nDoclist                    /* Size of doclist in bytes */
145154 ){
145155   int nPrefix;                    /* Size of term prefix in bytes */
145156   int nSuffix;                    /* Size of term suffix in bytes */
145157   int nReq;                       /* Number of bytes required on leaf page */
145158   int nData;
145159   SegmentWriter *pWriter = *ppWriter;
145160 
145161   if( !pWriter ){
145162     int rc;
145163     sqlite3_stmt *pStmt;
145164 
145165     /* Allocate the SegmentWriter structure */
145166     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
145167     if( !pWriter ) return SQLITE_NOMEM;
145168     memset(pWriter, 0, sizeof(SegmentWriter));
145169     *ppWriter = pWriter;
145170 
145171     /* Allocate a buffer in which to accumulate data */
145172     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
145173     if( !pWriter->aData ) return SQLITE_NOMEM;
145174     pWriter->nSize = p->nNodeSize;
145175 
145176     /* Find the next free blockid in the %_segments table */
145177     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
145178     if( rc!=SQLITE_OK ) return rc;
145179     if( SQLITE_ROW==sqlite3_step(pStmt) ){
145180       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
145181       pWriter->iFirst = pWriter->iFree;
145182     }
145183     rc = sqlite3_reset(pStmt);
145184     if( rc!=SQLITE_OK ) return rc;
145185   }
145186   nData = pWriter->nData;
145187 
145188   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
145189   nSuffix = nTerm-nPrefix;
145190 
145191   /* Figure out how many bytes are required by this new entry */
145192   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
145193     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
145194     nSuffix +                               /* Term suffix */
145195     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
145196     nDoclist;                               /* Doclist data */
145197 
145198   if( nData>0 && nData+nReq>p->nNodeSize ){
145199     int rc;
145200 
145201     /* The current leaf node is full. Write it out to the database. */
145202     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
145203     if( rc!=SQLITE_OK ) return rc;
145204     p->nLeafAdd++;
145205 
145206     /* Add the current term to the interior node tree. The term added to
145207     ** the interior tree must:
145208     **
145209     **   a) be greater than the largest term on the leaf node just written
145210     **      to the database (still available in pWriter->zTerm), and
145211     **
145212     **   b) be less than or equal to the term about to be added to the new
145213     **      leaf node (zTerm/nTerm).
145214     **
145215     ** In other words, it must be the prefix of zTerm 1 byte longer than
145216     ** the common prefix (if any) of zTerm and pWriter->zTerm.
145217     */
145218     assert( nPrefix<nTerm );
145219     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
145220     if( rc!=SQLITE_OK ) return rc;
145221 
145222     nData = 0;
145223     pWriter->nTerm = 0;
145224 
145225     nPrefix = 0;
145226     nSuffix = nTerm;
145227     nReq = 1 +                              /* varint containing prefix size */
145228       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
145229       nTerm +                               /* Term suffix */
145230       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
145231       nDoclist;                             /* Doclist data */
145232   }
145233 
145234   /* Increase the total number of bytes written to account for the new entry. */
145235   pWriter->nLeafData += nReq;
145236 
145237   /* If the buffer currently allocated is too small for this entry, realloc
145238   ** the buffer to make it large enough.
145239   */
145240   if( nReq>pWriter->nSize ){
145241     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
145242     if( !aNew ) return SQLITE_NOMEM;
145243     pWriter->aData = aNew;
145244     pWriter->nSize = nReq;
145245   }
145246   assert( nData+nReq<=pWriter->nSize );
145247 
145248   /* Append the prefix-compressed term and doclist to the buffer. */
145249   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
145250   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
145251   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
145252   nData += nSuffix;
145253   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
145254   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
145255   pWriter->nData = nData + nDoclist;
145256 
145257   /* Save the current term so that it can be used to prefix-compress the next.
145258   ** If the isCopyTerm parameter is true, then the buffer pointed to by
145259   ** zTerm is transient, so take a copy of the term data. Otherwise, just
145260   ** store a copy of the pointer.
145261   */
145262   if( isCopyTerm ){
145263     if( nTerm>pWriter->nMalloc ){
145264       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
145265       if( !zNew ){
145266         return SQLITE_NOMEM;
145267       }
145268       pWriter->nMalloc = nTerm*2;
145269       pWriter->zMalloc = zNew;
145270       pWriter->zTerm = zNew;
145271     }
145272     assert( pWriter->zTerm==pWriter->zMalloc );
145273     memcpy(pWriter->zTerm, zTerm, nTerm);
145274   }else{
145275     pWriter->zTerm = (char *)zTerm;
145276   }
145277   pWriter->nTerm = nTerm;
145278 
145279   return SQLITE_OK;
145280 }
145281 
145282 /*
145283 ** Flush all data associated with the SegmentWriter object pWriter to the
145284 ** database. This function must be called after all terms have been added
145285 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
145286 ** returned. Otherwise, an SQLite error code.
145287 */
145288 static int fts3SegWriterFlush(
145289   Fts3Table *p,                   /* Virtual table handle */
145290   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
145291   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
145292   int iIdx                        /* Value for 'idx' column of %_segdir */
145293 ){
145294   int rc;                         /* Return code */
145295   if( pWriter->pTree ){
145296     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
145297     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
145298     char *zRoot = NULL;           /* Pointer to buffer containing root node */
145299     int nRoot = 0;                /* Size of buffer zRoot */
145300 
145301     iLastLeaf = pWriter->iFree;
145302     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
145303     if( rc==SQLITE_OK ){
145304       rc = fts3NodeWrite(p, pWriter->pTree, 1,
145305           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
145306     }
145307     if( rc==SQLITE_OK ){
145308       rc = fts3WriteSegdir(p, iLevel, iIdx,
145309           pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
145310     }
145311   }else{
145312     /* The entire tree fits on the root node. Write it to the segdir table. */
145313     rc = fts3WriteSegdir(p, iLevel, iIdx,
145314         0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
145315   }
145316   p->nLeafAdd++;
145317   return rc;
145318 }
145319 
145320 /*
145321 ** Release all memory held by the SegmentWriter object passed as the
145322 ** first argument.
145323 */
145324 static void fts3SegWriterFree(SegmentWriter *pWriter){
145325   if( pWriter ){
145326     sqlite3_free(pWriter->aData);
145327     sqlite3_free(pWriter->zMalloc);
145328     fts3NodeFree(pWriter->pTree);
145329     sqlite3_free(pWriter);
145330   }
145331 }
145332 
145333 /*
145334 ** The first value in the apVal[] array is assumed to contain an integer.
145335 ** This function tests if there exist any documents with docid values that
145336 ** are different from that integer. i.e. if deleting the document with docid
145337 ** pRowid would mean the FTS3 table were empty.
145338 **
145339 ** If successful, *pisEmpty is set to true if the table is empty except for
145340 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
145341 ** error occurs, an SQLite error code is returned.
145342 */
145343 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
145344   sqlite3_stmt *pStmt;
145345   int rc;
145346   if( p->zContentTbl ){
145347     /* If using the content=xxx option, assume the table is never empty */
145348     *pisEmpty = 0;
145349     rc = SQLITE_OK;
145350   }else{
145351     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
145352     if( rc==SQLITE_OK ){
145353       if( SQLITE_ROW==sqlite3_step(pStmt) ){
145354         *pisEmpty = sqlite3_column_int(pStmt, 0);
145355       }
145356       rc = sqlite3_reset(pStmt);
145357     }
145358   }
145359   return rc;
145360 }
145361 
145362 /*
145363 ** Set *pnMax to the largest segment level in the database for the index
145364 ** iIndex.
145365 **
145366 ** Segment levels are stored in the 'level' column of the %_segdir table.
145367 **
145368 ** Return SQLITE_OK if successful, or an SQLite error code if not.
145369 */
145370 static int fts3SegmentMaxLevel(
145371   Fts3Table *p,
145372   int iLangid,
145373   int iIndex,
145374   sqlite3_int64 *pnMax
145375 ){
145376   sqlite3_stmt *pStmt;
145377   int rc;
145378   assert( iIndex>=0 && iIndex<p->nIndex );
145379 
145380   /* Set pStmt to the compiled version of:
145381   **
145382   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
145383   **
145384   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
145385   */
145386   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
145387   if( rc!=SQLITE_OK ) return rc;
145388   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
145389   sqlite3_bind_int64(pStmt, 2,
145390       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
145391   );
145392   if( SQLITE_ROW==sqlite3_step(pStmt) ){
145393     *pnMax = sqlite3_column_int64(pStmt, 0);
145394   }
145395   return sqlite3_reset(pStmt);
145396 }
145397 
145398 /*
145399 ** iAbsLevel is an absolute level that may be assumed to exist within
145400 ** the database. This function checks if it is the largest level number
145401 ** within its index. Assuming no error occurs, *pbMax is set to 1 if
145402 ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
145403 ** is returned. If an error occurs, an error code is returned and the
145404 ** final value of *pbMax is undefined.
145405 */
145406 static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
145407 
145408   /* Set pStmt to the compiled version of:
145409   **
145410   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
145411   **
145412   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
145413   */
145414   sqlite3_stmt *pStmt;
145415   int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
145416   if( rc!=SQLITE_OK ) return rc;
145417   sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
145418   sqlite3_bind_int64(pStmt, 2,
145419       ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
145420   );
145421 
145422   *pbMax = 0;
145423   if( SQLITE_ROW==sqlite3_step(pStmt) ){
145424     *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
145425   }
145426   return sqlite3_reset(pStmt);
145427 }
145428 
145429 /*
145430 ** Delete all entries in the %_segments table associated with the segment
145431 ** opened with seg-reader pSeg. This function does not affect the contents
145432 ** of the %_segdir table.
145433 */
145434 static int fts3DeleteSegment(
145435   Fts3Table *p,                   /* FTS table handle */
145436   Fts3SegReader *pSeg             /* Segment to delete */
145437 ){
145438   int rc = SQLITE_OK;             /* Return code */
145439   if( pSeg->iStartBlock ){
145440     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
145441     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
145442     if( rc==SQLITE_OK ){
145443       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
145444       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
145445       sqlite3_step(pDelete);
145446       rc = sqlite3_reset(pDelete);
145447     }
145448   }
145449   return rc;
145450 }
145451 
145452 /*
145453 ** This function is used after merging multiple segments into a single large
145454 ** segment to delete the old, now redundant, segment b-trees. Specifically,
145455 ** it:
145456 **
145457 **   1) Deletes all %_segments entries for the segments associated with
145458 **      each of the SegReader objects in the array passed as the third
145459 **      argument, and
145460 **
145461 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
145462 **      entries regardless of level if (iLevel<0).
145463 **
145464 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
145465 */
145466 static int fts3DeleteSegdir(
145467   Fts3Table *p,                   /* Virtual table handle */
145468   int iLangid,                    /* Language id */
145469   int iIndex,                     /* Index for p->aIndex */
145470   int iLevel,                     /* Level of %_segdir entries to delete */
145471   Fts3SegReader **apSegment,      /* Array of SegReader objects */
145472   int nReader                     /* Size of array apSegment */
145473 ){
145474   int rc = SQLITE_OK;             /* Return Code */
145475   int i;                          /* Iterator variable */
145476   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
145477 
145478   for(i=0; rc==SQLITE_OK && i<nReader; i++){
145479     rc = fts3DeleteSegment(p, apSegment[i]);
145480   }
145481   if( rc!=SQLITE_OK ){
145482     return rc;
145483   }
145484 
145485   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
145486   if( iLevel==FTS3_SEGCURSOR_ALL ){
145487     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
145488     if( rc==SQLITE_OK ){
145489       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
145490       sqlite3_bind_int64(pDelete, 2,
145491           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
145492       );
145493     }
145494   }else{
145495     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
145496     if( rc==SQLITE_OK ){
145497       sqlite3_bind_int64(
145498           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
145499       );
145500     }
145501   }
145502 
145503   if( rc==SQLITE_OK ){
145504     sqlite3_step(pDelete);
145505     rc = sqlite3_reset(pDelete);
145506   }
145507 
145508   return rc;
145509 }
145510 
145511 /*
145512 ** When this function is called, buffer *ppList (size *pnList bytes) contains
145513 ** a position list that may (or may not) feature multiple columns. This
145514 ** function adjusts the pointer *ppList and the length *pnList so that they
145515 ** identify the subset of the position list that corresponds to column iCol.
145516 **
145517 ** If there are no entries in the input position list for column iCol, then
145518 ** *pnList is set to zero before returning.
145519 **
145520 ** If parameter bZero is non-zero, then any part of the input list following
145521 ** the end of the output list is zeroed before returning.
145522 */
145523 static void fts3ColumnFilter(
145524   int iCol,                       /* Column to filter on */
145525   int bZero,                      /* Zero out anything following *ppList */
145526   char **ppList,                  /* IN/OUT: Pointer to position list */
145527   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
145528 ){
145529   char *pList = *ppList;
145530   int nList = *pnList;
145531   char *pEnd = &pList[nList];
145532   int iCurrent = 0;
145533   char *p = pList;
145534 
145535   assert( iCol>=0 );
145536   while( 1 ){
145537     char c = 0;
145538     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
145539 
145540     if( iCol==iCurrent ){
145541       nList = (int)(p - pList);
145542       break;
145543     }
145544 
145545     nList -= (int)(p - pList);
145546     pList = p;
145547     if( nList==0 ){
145548       break;
145549     }
145550     p = &pList[1];
145551     p += fts3GetVarint32(p, &iCurrent);
145552   }
145553 
145554   if( bZero && &pList[nList]!=pEnd ){
145555     memset(&pList[nList], 0, pEnd - &pList[nList]);
145556   }
145557   *ppList = pList;
145558   *pnList = nList;
145559 }
145560 
145561 /*
145562 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
145563 ** existing data). Grow the buffer if required.
145564 **
145565 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
145566 ** trying to resize the buffer, return SQLITE_NOMEM.
145567 */
145568 static int fts3MsrBufferData(
145569   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
145570   char *pList,
145571   int nList
145572 ){
145573   if( nList>pMsr->nBuffer ){
145574     char *pNew;
145575     pMsr->nBuffer = nList*2;
145576     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
145577     if( !pNew ) return SQLITE_NOMEM;
145578     pMsr->aBuffer = pNew;
145579   }
145580 
145581   memcpy(pMsr->aBuffer, pList, nList);
145582   return SQLITE_OK;
145583 }
145584 
145585 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
145586   Fts3Table *p,                   /* Virtual table handle */
145587   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
145588   sqlite3_int64 *piDocid,         /* OUT: Docid value */
145589   char **paPoslist,               /* OUT: Pointer to position list */
145590   int *pnPoslist                  /* OUT: Size of position list in bytes */
145591 ){
145592   int nMerge = pMsr->nAdvance;
145593   Fts3SegReader **apSegment = pMsr->apSegment;
145594   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
145595     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
145596   );
145597 
145598   if( nMerge==0 ){
145599     *paPoslist = 0;
145600     return SQLITE_OK;
145601   }
145602 
145603   while( 1 ){
145604     Fts3SegReader *pSeg;
145605     pSeg = pMsr->apSegment[0];
145606 
145607     if( pSeg->pOffsetList==0 ){
145608       *paPoslist = 0;
145609       break;
145610     }else{
145611       int rc;
145612       char *pList;
145613       int nList;
145614       int j;
145615       sqlite3_int64 iDocid = apSegment[0]->iDocid;
145616 
145617       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
145618       j = 1;
145619       while( rc==SQLITE_OK
145620         && j<nMerge
145621         && apSegment[j]->pOffsetList
145622         && apSegment[j]->iDocid==iDocid
145623       ){
145624         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
145625         j++;
145626       }
145627       if( rc!=SQLITE_OK ) return rc;
145628       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
145629 
145630       if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
145631         rc = fts3MsrBufferData(pMsr, pList, nList+1);
145632         if( rc!=SQLITE_OK ) return rc;
145633         assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
145634         pList = pMsr->aBuffer;
145635       }
145636 
145637       if( pMsr->iColFilter>=0 ){
145638         fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
145639       }
145640 
145641       if( nList>0 ){
145642         *paPoslist = pList;
145643         *piDocid = iDocid;
145644         *pnPoslist = nList;
145645         break;
145646       }
145647     }
145648   }
145649 
145650   return SQLITE_OK;
145651 }
145652 
145653 static int fts3SegReaderStart(
145654   Fts3Table *p,                   /* Virtual table handle */
145655   Fts3MultiSegReader *pCsr,       /* Cursor object */
145656   const char *zTerm,              /* Term searched for (or NULL) */
145657   int nTerm                       /* Length of zTerm in bytes */
145658 ){
145659   int i;
145660   int nSeg = pCsr->nSegment;
145661 
145662   /* If the Fts3SegFilter defines a specific term (or term prefix) to search
145663   ** for, then advance each segment iterator until it points to a term of
145664   ** equal or greater value than the specified term. This prevents many
145665   ** unnecessary merge/sort operations for the case where single segment
145666   ** b-tree leaf nodes contain more than one term.
145667   */
145668   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
145669     int res = 0;
145670     Fts3SegReader *pSeg = pCsr->apSegment[i];
145671     do {
145672       int rc = fts3SegReaderNext(p, pSeg, 0);
145673       if( rc!=SQLITE_OK ) return rc;
145674     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
145675 
145676     if( pSeg->bLookup && res!=0 ){
145677       fts3SegReaderSetEof(pSeg);
145678     }
145679   }
145680   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
145681 
145682   return SQLITE_OK;
145683 }
145684 
145685 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
145686   Fts3Table *p,                   /* Virtual table handle */
145687   Fts3MultiSegReader *pCsr,       /* Cursor object */
145688   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
145689 ){
145690   pCsr->pFilter = pFilter;
145691   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
145692 }
145693 
145694 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
145695   Fts3Table *p,                   /* Virtual table handle */
145696   Fts3MultiSegReader *pCsr,       /* Cursor object */
145697   int iCol,                       /* Column to match on. */
145698   const char *zTerm,              /* Term to iterate through a doclist for */
145699   int nTerm                       /* Number of bytes in zTerm */
145700 ){
145701   int i;
145702   int rc;
145703   int nSegment = pCsr->nSegment;
145704   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
145705     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
145706   );
145707 
145708   assert( pCsr->pFilter==0 );
145709   assert( zTerm && nTerm>0 );
145710 
145711   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
145712   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
145713   if( rc!=SQLITE_OK ) return rc;
145714 
145715   /* Determine how many of the segments actually point to zTerm/nTerm. */
145716   for(i=0; i<nSegment; i++){
145717     Fts3SegReader *pSeg = pCsr->apSegment[i];
145718     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
145719       break;
145720     }
145721   }
145722   pCsr->nAdvance = i;
145723 
145724   /* Advance each of the segments to point to the first docid. */
145725   for(i=0; i<pCsr->nAdvance; i++){
145726     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
145727     if( rc!=SQLITE_OK ) return rc;
145728   }
145729   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
145730 
145731   assert( iCol<0 || iCol<p->nColumn );
145732   pCsr->iColFilter = iCol;
145733 
145734   return SQLITE_OK;
145735 }
145736 
145737 /*
145738 ** This function is called on a MultiSegReader that has been started using
145739 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
145740 ** have been made. Calling this function puts the MultiSegReader in such
145741 ** a state that if the next two calls are:
145742 **
145743 **   sqlite3Fts3SegReaderStart()
145744 **   sqlite3Fts3SegReaderStep()
145745 **
145746 ** then the entire doclist for the term is available in
145747 ** MultiSegReader.aDoclist/nDoclist.
145748 */
145749 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
145750   int i;                          /* Used to iterate through segment-readers */
145751 
145752   assert( pCsr->zTerm==0 );
145753   assert( pCsr->nTerm==0 );
145754   assert( pCsr->aDoclist==0 );
145755   assert( pCsr->nDoclist==0 );
145756 
145757   pCsr->nAdvance = 0;
145758   pCsr->bRestart = 1;
145759   for(i=0; i<pCsr->nSegment; i++){
145760     pCsr->apSegment[i]->pOffsetList = 0;
145761     pCsr->apSegment[i]->nOffsetList = 0;
145762     pCsr->apSegment[i]->iDocid = 0;
145763   }
145764 
145765   return SQLITE_OK;
145766 }
145767 
145768 
145769 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
145770   Fts3Table *p,                   /* Virtual table handle */
145771   Fts3MultiSegReader *pCsr        /* Cursor object */
145772 ){
145773   int rc = SQLITE_OK;
145774 
145775   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
145776   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
145777   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
145778   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
145779   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
145780   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
145781 
145782   Fts3SegReader **apSegment = pCsr->apSegment;
145783   int nSegment = pCsr->nSegment;
145784   Fts3SegFilter *pFilter = pCsr->pFilter;
145785   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
145786     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
145787   );
145788 
145789   if( pCsr->nSegment==0 ) return SQLITE_OK;
145790 
145791   do {
145792     int nMerge;
145793     int i;
145794 
145795     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
145796     ** forward. Then sort the list in order of current term again.
145797     */
145798     for(i=0; i<pCsr->nAdvance; i++){
145799       Fts3SegReader *pSeg = apSegment[i];
145800       if( pSeg->bLookup ){
145801         fts3SegReaderSetEof(pSeg);
145802       }else{
145803         rc = fts3SegReaderNext(p, pSeg, 0);
145804       }
145805       if( rc!=SQLITE_OK ) return rc;
145806     }
145807     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
145808     pCsr->nAdvance = 0;
145809 
145810     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
145811     assert( rc==SQLITE_OK );
145812     if( apSegment[0]->aNode==0 ) break;
145813 
145814     pCsr->nTerm = apSegment[0]->nTerm;
145815     pCsr->zTerm = apSegment[0]->zTerm;
145816 
145817     /* If this is a prefix-search, and if the term that apSegment[0] points
145818     ** to does not share a suffix with pFilter->zTerm/nTerm, then all
145819     ** required callbacks have been made. In this case exit early.
145820     **
145821     ** Similarly, if this is a search for an exact match, and the first term
145822     ** of segment apSegment[0] is not a match, exit early.
145823     */
145824     if( pFilter->zTerm && !isScan ){
145825       if( pCsr->nTerm<pFilter->nTerm
145826        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
145827        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
145828       ){
145829         break;
145830       }
145831     }
145832 
145833     nMerge = 1;
145834     while( nMerge<nSegment
145835         && apSegment[nMerge]->aNode
145836         && apSegment[nMerge]->nTerm==pCsr->nTerm
145837         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
145838     ){
145839       nMerge++;
145840     }
145841 
145842     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
145843     if( nMerge==1
145844      && !isIgnoreEmpty
145845      && !isFirst
145846      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
145847     ){
145848       pCsr->nDoclist = apSegment[0]->nDoclist;
145849       if( fts3SegReaderIsPending(apSegment[0]) ){
145850         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
145851         pCsr->aDoclist = pCsr->aBuffer;
145852       }else{
145853         pCsr->aDoclist = apSegment[0]->aDoclist;
145854       }
145855       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
145856     }else{
145857       int nDoclist = 0;           /* Size of doclist */
145858       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
145859 
145860       /* The current term of the first nMerge entries in the array
145861       ** of Fts3SegReader objects is the same. The doclists must be merged
145862       ** and a single term returned with the merged doclist.
145863       */
145864       for(i=0; i<nMerge; i++){
145865         fts3SegReaderFirstDocid(p, apSegment[i]);
145866       }
145867       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
145868       while( apSegment[0]->pOffsetList ){
145869         int j;                    /* Number of segments that share a docid */
145870         char *pList = 0;
145871         int nList = 0;
145872         int nByte;
145873         sqlite3_int64 iDocid = apSegment[0]->iDocid;
145874         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
145875         j = 1;
145876         while( j<nMerge
145877             && apSegment[j]->pOffsetList
145878             && apSegment[j]->iDocid==iDocid
145879         ){
145880           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
145881           j++;
145882         }
145883 
145884         if( isColFilter ){
145885           fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
145886         }
145887 
145888         if( !isIgnoreEmpty || nList>0 ){
145889 
145890           /* Calculate the 'docid' delta value to write into the merged
145891           ** doclist. */
145892           sqlite3_int64 iDelta;
145893           if( p->bDescIdx && nDoclist>0 ){
145894             iDelta = iPrev - iDocid;
145895           }else{
145896             iDelta = iDocid - iPrev;
145897           }
145898           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
145899           assert( nDoclist>0 || iDelta==iDocid );
145900 
145901           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
145902           if( nDoclist+nByte>pCsr->nBuffer ){
145903             char *aNew;
145904             pCsr->nBuffer = (nDoclist+nByte)*2;
145905             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
145906             if( !aNew ){
145907               return SQLITE_NOMEM;
145908             }
145909             pCsr->aBuffer = aNew;
145910           }
145911 
145912           if( isFirst ){
145913             char *a = &pCsr->aBuffer[nDoclist];
145914             int nWrite;
145915 
145916             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
145917             if( nWrite ){
145918               iPrev = iDocid;
145919               nDoclist += nWrite;
145920             }
145921           }else{
145922             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
145923             iPrev = iDocid;
145924             if( isRequirePos ){
145925               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
145926               nDoclist += nList;
145927               pCsr->aBuffer[nDoclist++] = '\0';
145928             }
145929           }
145930         }
145931 
145932         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
145933       }
145934       if( nDoclist>0 ){
145935         pCsr->aDoclist = pCsr->aBuffer;
145936         pCsr->nDoclist = nDoclist;
145937         rc = SQLITE_ROW;
145938       }
145939     }
145940     pCsr->nAdvance = nMerge;
145941   }while( rc==SQLITE_OK );
145942 
145943   return rc;
145944 }
145945 
145946 
145947 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
145948   Fts3MultiSegReader *pCsr       /* Cursor object */
145949 ){
145950   if( pCsr ){
145951     int i;
145952     for(i=0; i<pCsr->nSegment; i++){
145953       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
145954     }
145955     sqlite3_free(pCsr->apSegment);
145956     sqlite3_free(pCsr->aBuffer);
145957 
145958     pCsr->nSegment = 0;
145959     pCsr->apSegment = 0;
145960     pCsr->aBuffer = 0;
145961   }
145962 }
145963 
145964 /*
145965 ** Decode the "end_block" field, selected by column iCol of the SELECT
145966 ** statement passed as the first argument.
145967 **
145968 ** The "end_block" field may contain either an integer, or a text field
145969 ** containing the text representation of two non-negative integers separated
145970 ** by one or more space (0x20) characters. In the first case, set *piEndBlock
145971 ** to the integer value and *pnByte to zero before returning. In the second,
145972 ** set *piEndBlock to the first value and *pnByte to the second.
145973 */
145974 static void fts3ReadEndBlockField(
145975   sqlite3_stmt *pStmt,
145976   int iCol,
145977   i64 *piEndBlock,
145978   i64 *pnByte
145979 ){
145980   const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
145981   if( zText ){
145982     int i;
145983     int iMul = 1;
145984     i64 iVal = 0;
145985     for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
145986       iVal = iVal*10 + (zText[i] - '0');
145987     }
145988     *piEndBlock = iVal;
145989     while( zText[i]==' ' ) i++;
145990     iVal = 0;
145991     if( zText[i]=='-' ){
145992       i++;
145993       iMul = -1;
145994     }
145995     for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
145996       iVal = iVal*10 + (zText[i] - '0');
145997     }
145998     *pnByte = (iVal * (i64)iMul);
145999   }
146000 }
146001 
146002 
146003 /*
146004 ** A segment of size nByte bytes has just been written to absolute level
146005 ** iAbsLevel. Promote any segments that should be promoted as a result.
146006 */
146007 static int fts3PromoteSegments(
146008   Fts3Table *p,                   /* FTS table handle */
146009   sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
146010   sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
146011 ){
146012   int rc = SQLITE_OK;
146013   sqlite3_stmt *pRange;
146014 
146015   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
146016 
146017   if( rc==SQLITE_OK ){
146018     int bOk = 0;
146019     i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
146020     i64 nLimit = (nByte*3)/2;
146021 
146022     /* Loop through all entries in the %_segdir table corresponding to
146023     ** segments in this index on levels greater than iAbsLevel. If there is
146024     ** at least one such segment, and it is possible to determine that all
146025     ** such segments are smaller than nLimit bytes in size, they will be
146026     ** promoted to level iAbsLevel.  */
146027     sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
146028     sqlite3_bind_int64(pRange, 2, iLast);
146029     while( SQLITE_ROW==sqlite3_step(pRange) ){
146030       i64 nSize = 0, dummy;
146031       fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
146032       if( nSize<=0 || nSize>nLimit ){
146033         /* If nSize==0, then the %_segdir.end_block field does not not
146034         ** contain a size value. This happens if it was written by an
146035         ** old version of FTS. In this case it is not possible to determine
146036         ** the size of the segment, and so segment promotion does not
146037         ** take place.  */
146038         bOk = 0;
146039         break;
146040       }
146041       bOk = 1;
146042     }
146043     rc = sqlite3_reset(pRange);
146044 
146045     if( bOk ){
146046       int iIdx = 0;
146047       sqlite3_stmt *pUpdate1 = 0;
146048       sqlite3_stmt *pUpdate2 = 0;
146049 
146050       if( rc==SQLITE_OK ){
146051         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
146052       }
146053       if( rc==SQLITE_OK ){
146054         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
146055       }
146056 
146057       if( rc==SQLITE_OK ){
146058 
146059         /* Loop through all %_segdir entries for segments in this index with
146060         ** levels equal to or greater than iAbsLevel. As each entry is visited,
146061         ** updated it to set (level = -1) and (idx = N), where N is 0 for the
146062         ** oldest segment in the range, 1 for the next oldest, and so on.
146063         **
146064         ** In other words, move all segments being promoted to level -1,
146065         ** setting the "idx" fields as appropriate to keep them in the same
146066         ** order. The contents of level -1 (which is never used, except
146067         ** transiently here), will be moved back to level iAbsLevel below.  */
146068         sqlite3_bind_int64(pRange, 1, iAbsLevel);
146069         while( SQLITE_ROW==sqlite3_step(pRange) ){
146070           sqlite3_bind_int(pUpdate1, 1, iIdx++);
146071           sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
146072           sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
146073           sqlite3_step(pUpdate1);
146074           rc = sqlite3_reset(pUpdate1);
146075           if( rc!=SQLITE_OK ){
146076             sqlite3_reset(pRange);
146077             break;
146078           }
146079         }
146080       }
146081       if( rc==SQLITE_OK ){
146082         rc = sqlite3_reset(pRange);
146083       }
146084 
146085       /* Move level -1 to level iAbsLevel */
146086       if( rc==SQLITE_OK ){
146087         sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
146088         sqlite3_step(pUpdate2);
146089         rc = sqlite3_reset(pUpdate2);
146090       }
146091     }
146092   }
146093 
146094 
146095   return rc;
146096 }
146097 
146098 /*
146099 ** Merge all level iLevel segments in the database into a single
146100 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
146101 ** single segment with a level equal to the numerically largest level
146102 ** currently present in the database.
146103 **
146104 ** If this function is called with iLevel<0, but there is only one
146105 ** segment in the database, SQLITE_DONE is returned immediately.
146106 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
146107 ** an SQLite error code is returned.
146108 */
146109 static int fts3SegmentMerge(
146110   Fts3Table *p,
146111   int iLangid,                    /* Language id to merge */
146112   int iIndex,                     /* Index in p->aIndex[] to merge */
146113   int iLevel                      /* Level to merge */
146114 ){
146115   int rc;                         /* Return code */
146116   int iIdx = 0;                   /* Index of new segment */
146117   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
146118   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
146119   Fts3SegFilter filter;           /* Segment term filter condition */
146120   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
146121   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
146122   i64 iMaxLevel = 0;              /* Max level number for this index/langid */
146123 
146124   assert( iLevel==FTS3_SEGCURSOR_ALL
146125        || iLevel==FTS3_SEGCURSOR_PENDING
146126        || iLevel>=0
146127   );
146128   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
146129   assert( iIndex>=0 && iIndex<p->nIndex );
146130 
146131   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
146132   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
146133 
146134   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
146135     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
146136     if( rc!=SQLITE_OK ) goto finished;
146137   }
146138 
146139   if( iLevel==FTS3_SEGCURSOR_ALL ){
146140     /* This call is to merge all segments in the database to a single
146141     ** segment. The level of the new segment is equal to the numerically
146142     ** greatest segment level currently present in the database for this
146143     ** index. The idx of the new segment is always 0.  */
146144     if( csr.nSegment==1 ){
146145       rc = SQLITE_DONE;
146146       goto finished;
146147     }
146148     iNewLevel = iMaxLevel;
146149     bIgnoreEmpty = 1;
146150 
146151   }else{
146152     /* This call is to merge all segments at level iLevel. find the next
146153     ** available segment index at level iLevel+1. The call to
146154     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
146155     ** a single iLevel+2 segment if necessary.  */
146156     assert( FTS3_SEGCURSOR_PENDING==-1 );
146157     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
146158     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
146159     bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
146160   }
146161   if( rc!=SQLITE_OK ) goto finished;
146162 
146163   assert( csr.nSegment>0 );
146164   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
146165   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
146166 
146167   memset(&filter, 0, sizeof(Fts3SegFilter));
146168   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
146169   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
146170 
146171   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
146172   while( SQLITE_OK==rc ){
146173     rc = sqlite3Fts3SegReaderStep(p, &csr);
146174     if( rc!=SQLITE_ROW ) break;
146175     rc = fts3SegWriterAdd(p, &pWriter, 1,
146176         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
146177   }
146178   if( rc!=SQLITE_OK ) goto finished;
146179   assert( pWriter || bIgnoreEmpty );
146180 
146181   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
146182     rc = fts3DeleteSegdir(
146183         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
146184     );
146185     if( rc!=SQLITE_OK ) goto finished;
146186   }
146187   if( pWriter ){
146188     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
146189     if( rc==SQLITE_OK ){
146190       if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
146191         rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
146192       }
146193     }
146194   }
146195 
146196  finished:
146197   fts3SegWriterFree(pWriter);
146198   sqlite3Fts3SegReaderFinish(&csr);
146199   return rc;
146200 }
146201 
146202 
146203 /*
146204 ** Flush the contents of pendingTerms to level 0 segments.
146205 */
146206 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
146207   int rc = SQLITE_OK;
146208   int i;
146209 
146210   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
146211     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
146212     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
146213   }
146214   sqlite3Fts3PendingTermsClear(p);
146215 
146216   /* Determine the auto-incr-merge setting if unknown.  If enabled,
146217   ** estimate the number of leaf blocks of content to be written
146218   */
146219   if( rc==SQLITE_OK && p->bHasStat
146220    && p->nAutoincrmerge==0xff && p->nLeafAdd>0
146221   ){
146222     sqlite3_stmt *pStmt = 0;
146223     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
146224     if( rc==SQLITE_OK ){
146225       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
146226       rc = sqlite3_step(pStmt);
146227       if( rc==SQLITE_ROW ){
146228         p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
146229         if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
146230       }else if( rc==SQLITE_DONE ){
146231         p->nAutoincrmerge = 0;
146232       }
146233       rc = sqlite3_reset(pStmt);
146234     }
146235   }
146236   return rc;
146237 }
146238 
146239 /*
146240 ** Encode N integers as varints into a blob.
146241 */
146242 static void fts3EncodeIntArray(
146243   int N,             /* The number of integers to encode */
146244   u32 *a,            /* The integer values */
146245   char *zBuf,        /* Write the BLOB here */
146246   int *pNBuf         /* Write number of bytes if zBuf[] used here */
146247 ){
146248   int i, j;
146249   for(i=j=0; i<N; i++){
146250     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
146251   }
146252   *pNBuf = j;
146253 }
146254 
146255 /*
146256 ** Decode a blob of varints into N integers
146257 */
146258 static void fts3DecodeIntArray(
146259   int N,             /* The number of integers to decode */
146260   u32 *a,            /* Write the integer values */
146261   const char *zBuf,  /* The BLOB containing the varints */
146262   int nBuf           /* size of the BLOB */
146263 ){
146264   int i, j;
146265   UNUSED_PARAMETER(nBuf);
146266   for(i=j=0; i<N; i++){
146267     sqlite3_int64 x;
146268     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
146269     assert(j<=nBuf);
146270     a[i] = (u32)(x & 0xffffffff);
146271   }
146272 }
146273 
146274 /*
146275 ** Insert the sizes (in tokens) for each column of the document
146276 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
146277 ** a blob of varints.
146278 */
146279 static void fts3InsertDocsize(
146280   int *pRC,                       /* Result code */
146281   Fts3Table *p,                   /* Table into which to insert */
146282   u32 *aSz                        /* Sizes of each column, in tokens */
146283 ){
146284   char *pBlob;             /* The BLOB encoding of the document size */
146285   int nBlob;               /* Number of bytes in the BLOB */
146286   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
146287   int rc;                  /* Result code from subfunctions */
146288 
146289   if( *pRC ) return;
146290   pBlob = sqlite3_malloc( 10*p->nColumn );
146291   if( pBlob==0 ){
146292     *pRC = SQLITE_NOMEM;
146293     return;
146294   }
146295   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
146296   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
146297   if( rc ){
146298     sqlite3_free(pBlob);
146299     *pRC = rc;
146300     return;
146301   }
146302   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
146303   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
146304   sqlite3_step(pStmt);
146305   *pRC = sqlite3_reset(pStmt);
146306 }
146307 
146308 /*
146309 ** Record 0 of the %_stat table contains a blob consisting of N varints,
146310 ** where N is the number of user defined columns in the fts3 table plus
146311 ** two. If nCol is the number of user defined columns, then values of the
146312 ** varints are set as follows:
146313 **
146314 **   Varint 0:       Total number of rows in the table.
146315 **
146316 **   Varint 1..nCol: For each column, the total number of tokens stored in
146317 **                   the column for all rows of the table.
146318 **
146319 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
146320 **                   columns of all rows of the table.
146321 **
146322 */
146323 static void fts3UpdateDocTotals(
146324   int *pRC,                       /* The result code */
146325   Fts3Table *p,                   /* Table being updated */
146326   u32 *aSzIns,                    /* Size increases */
146327   u32 *aSzDel,                    /* Size decreases */
146328   int nChng                       /* Change in the number of documents */
146329 ){
146330   char *pBlob;             /* Storage for BLOB written into %_stat */
146331   int nBlob;               /* Size of BLOB written into %_stat */
146332   u32 *a;                  /* Array of integers that becomes the BLOB */
146333   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
146334   int i;                   /* Loop counter */
146335   int rc;                  /* Result code from subfunctions */
146336 
146337   const int nStat = p->nColumn+2;
146338 
146339   if( *pRC ) return;
146340   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
146341   if( a==0 ){
146342     *pRC = SQLITE_NOMEM;
146343     return;
146344   }
146345   pBlob = (char*)&a[nStat];
146346   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
146347   if( rc ){
146348     sqlite3_free(a);
146349     *pRC = rc;
146350     return;
146351   }
146352   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
146353   if( sqlite3_step(pStmt)==SQLITE_ROW ){
146354     fts3DecodeIntArray(nStat, a,
146355          sqlite3_column_blob(pStmt, 0),
146356          sqlite3_column_bytes(pStmt, 0));
146357   }else{
146358     memset(a, 0, sizeof(u32)*(nStat) );
146359   }
146360   rc = sqlite3_reset(pStmt);
146361   if( rc!=SQLITE_OK ){
146362     sqlite3_free(a);
146363     *pRC = rc;
146364     return;
146365   }
146366   if( nChng<0 && a[0]<(u32)(-nChng) ){
146367     a[0] = 0;
146368   }else{
146369     a[0] += nChng;
146370   }
146371   for(i=0; i<p->nColumn+1; i++){
146372     u32 x = a[i+1];
146373     if( x+aSzIns[i] < aSzDel[i] ){
146374       x = 0;
146375     }else{
146376       x = x + aSzIns[i] - aSzDel[i];
146377     }
146378     a[i+1] = x;
146379   }
146380   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
146381   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
146382   if( rc ){
146383     sqlite3_free(a);
146384     *pRC = rc;
146385     return;
146386   }
146387   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
146388   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
146389   sqlite3_step(pStmt);
146390   *pRC = sqlite3_reset(pStmt);
146391   sqlite3_free(a);
146392 }
146393 
146394 /*
146395 ** Merge the entire database so that there is one segment for each
146396 ** iIndex/iLangid combination.
146397 */
146398 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
146399   int bSeenDone = 0;
146400   int rc;
146401   sqlite3_stmt *pAllLangid = 0;
146402 
146403   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
146404   if( rc==SQLITE_OK ){
146405     int rc2;
146406     sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
146407     sqlite3_bind_int(pAllLangid, 2, p->nIndex);
146408     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
146409       int i;
146410       int iLangid = sqlite3_column_int(pAllLangid, 0);
146411       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
146412         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
146413         if( rc==SQLITE_DONE ){
146414           bSeenDone = 1;
146415           rc = SQLITE_OK;
146416         }
146417       }
146418     }
146419     rc2 = sqlite3_reset(pAllLangid);
146420     if( rc==SQLITE_OK ) rc = rc2;
146421   }
146422 
146423   sqlite3Fts3SegmentsClose(p);
146424   sqlite3Fts3PendingTermsClear(p);
146425 
146426   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
146427 }
146428 
146429 /*
146430 ** This function is called when the user executes the following statement:
146431 **
146432 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
146433 **
146434 ** The entire FTS index is discarded and rebuilt. If the table is one
146435 ** created using the content=xxx option, then the new index is based on
146436 ** the current contents of the xxx table. Otherwise, it is rebuilt based
146437 ** on the contents of the %_content table.
146438 */
146439 static int fts3DoRebuild(Fts3Table *p){
146440   int rc;                         /* Return Code */
146441 
146442   rc = fts3DeleteAll(p, 0);
146443   if( rc==SQLITE_OK ){
146444     u32 *aSz = 0;
146445     u32 *aSzIns = 0;
146446     u32 *aSzDel = 0;
146447     sqlite3_stmt *pStmt = 0;
146448     int nEntry = 0;
146449 
146450     /* Compose and prepare an SQL statement to loop through the content table */
146451     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
146452     if( !zSql ){
146453       rc = SQLITE_NOMEM;
146454     }else{
146455       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
146456       sqlite3_free(zSql);
146457     }
146458 
146459     if( rc==SQLITE_OK ){
146460       int nByte = sizeof(u32) * (p->nColumn+1)*3;
146461       aSz = (u32 *)sqlite3_malloc(nByte);
146462       if( aSz==0 ){
146463         rc = SQLITE_NOMEM;
146464       }else{
146465         memset(aSz, 0, nByte);
146466         aSzIns = &aSz[p->nColumn+1];
146467         aSzDel = &aSzIns[p->nColumn+1];
146468       }
146469     }
146470 
146471     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
146472       int iCol;
146473       int iLangid = langidFromSelect(p, pStmt);
146474       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
146475       memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
146476       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
146477         if( p->abNotindexed[iCol]==0 ){
146478           const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
146479           rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
146480           aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
146481         }
146482       }
146483       if( p->bHasDocsize ){
146484         fts3InsertDocsize(&rc, p, aSz);
146485       }
146486       if( rc!=SQLITE_OK ){
146487         sqlite3_finalize(pStmt);
146488         pStmt = 0;
146489       }else{
146490         nEntry++;
146491         for(iCol=0; iCol<=p->nColumn; iCol++){
146492           aSzIns[iCol] += aSz[iCol];
146493         }
146494       }
146495     }
146496     if( p->bFts4 ){
146497       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
146498     }
146499     sqlite3_free(aSz);
146500 
146501     if( pStmt ){
146502       int rc2 = sqlite3_finalize(pStmt);
146503       if( rc==SQLITE_OK ){
146504         rc = rc2;
146505       }
146506     }
146507   }
146508 
146509   return rc;
146510 }
146511 
146512 
146513 /*
146514 ** This function opens a cursor used to read the input data for an
146515 ** incremental merge operation. Specifically, it opens a cursor to scan
146516 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
146517 ** level iAbsLevel.
146518 */
146519 static int fts3IncrmergeCsr(
146520   Fts3Table *p,                   /* FTS3 table handle */
146521   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
146522   int nSeg,                       /* Number of segments to merge */
146523   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
146524 ){
146525   int rc;                         /* Return Code */
146526   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
146527   int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
146528 
146529   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
146530   memset(pCsr, 0, sizeof(*pCsr));
146531   nByte = sizeof(Fts3SegReader *) * nSeg;
146532   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
146533 
146534   if( pCsr->apSegment==0 ){
146535     rc = SQLITE_NOMEM;
146536   }else{
146537     memset(pCsr->apSegment, 0, nByte);
146538     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
146539   }
146540   if( rc==SQLITE_OK ){
146541     int i;
146542     int rc2;
146543     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
146544     assert( pCsr->nSegment==0 );
146545     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
146546       rc = sqlite3Fts3SegReaderNew(i, 0,
146547           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
146548           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
146549           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
146550           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
146551           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
146552           &pCsr->apSegment[i]
146553       );
146554       pCsr->nSegment++;
146555     }
146556     rc2 = sqlite3_reset(pStmt);
146557     if( rc==SQLITE_OK ) rc = rc2;
146558   }
146559 
146560   return rc;
146561 }
146562 
146563 typedef struct IncrmergeWriter IncrmergeWriter;
146564 typedef struct NodeWriter NodeWriter;
146565 typedef struct Blob Blob;
146566 typedef struct NodeReader NodeReader;
146567 
146568 /*
146569 ** An instance of the following structure is used as a dynamic buffer
146570 ** to build up nodes or other blobs of data in.
146571 **
146572 ** The function blobGrowBuffer() is used to extend the allocation.
146573 */
146574 struct Blob {
146575   char *a;                        /* Pointer to allocation */
146576   int n;                          /* Number of valid bytes of data in a[] */
146577   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
146578 };
146579 
146580 /*
146581 ** This structure is used to build up buffers containing segment b-tree
146582 ** nodes (blocks).
146583 */
146584 struct NodeWriter {
146585   sqlite3_int64 iBlock;           /* Current block id */
146586   Blob key;                       /* Last key written to the current block */
146587   Blob block;                     /* Current block image */
146588 };
146589 
146590 /*
146591 ** An object of this type contains the state required to create or append
146592 ** to an appendable b-tree segment.
146593 */
146594 struct IncrmergeWriter {
146595   int nLeafEst;                   /* Space allocated for leaf blocks */
146596   int nWork;                      /* Number of leaf pages flushed */
146597   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
146598   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
146599   sqlite3_int64 iStart;           /* Block number of first allocated block */
146600   sqlite3_int64 iEnd;             /* Block number of last allocated block */
146601   sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
146602   u8 bNoLeafData;                 /* If true, store 0 for segment size */
146603   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
146604 };
146605 
146606 /*
146607 ** An object of the following type is used to read data from a single
146608 ** FTS segment node. See the following functions:
146609 **
146610 **     nodeReaderInit()
146611 **     nodeReaderNext()
146612 **     nodeReaderRelease()
146613 */
146614 struct NodeReader {
146615   const char *aNode;
146616   int nNode;
146617   int iOff;                       /* Current offset within aNode[] */
146618 
146619   /* Output variables. Containing the current node entry. */
146620   sqlite3_int64 iChild;           /* Pointer to child node */
146621   Blob term;                      /* Current term */
146622   const char *aDoclist;           /* Pointer to doclist */
146623   int nDoclist;                   /* Size of doclist in bytes */
146624 };
146625 
146626 /*
146627 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
146628 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
146629 ** bytes in size, extend (realloc) it to be so.
146630 **
146631 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
146632 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
146633 ** to reflect the new size of the pBlob->a[] buffer.
146634 */
146635 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
146636   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
146637     int nAlloc = nMin;
146638     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
146639     if( a ){
146640       pBlob->nAlloc = nAlloc;
146641       pBlob->a = a;
146642     }else{
146643       *pRc = SQLITE_NOMEM;
146644     }
146645   }
146646 }
146647 
146648 /*
146649 ** Attempt to advance the node-reader object passed as the first argument to
146650 ** the next entry on the node.
146651 **
146652 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
146653 ** Otherwise return SQLITE_OK. If there is no next entry on the node
146654 ** (e.g. because the current entry is the last) set NodeReader->aNode to
146655 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
146656 ** variables for the new entry.
146657 */
146658 static int nodeReaderNext(NodeReader *p){
146659   int bFirst = (p->term.n==0);    /* True for first term on the node */
146660   int nPrefix = 0;                /* Bytes to copy from previous term */
146661   int nSuffix = 0;                /* Bytes to append to the prefix */
146662   int rc = SQLITE_OK;             /* Return code */
146663 
146664   assert( p->aNode );
146665   if( p->iChild && bFirst==0 ) p->iChild++;
146666   if( p->iOff>=p->nNode ){
146667     /* EOF */
146668     p->aNode = 0;
146669   }else{
146670     if( bFirst==0 ){
146671       p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
146672     }
146673     p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
146674 
146675     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
146676     if( rc==SQLITE_OK ){
146677       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
146678       p->term.n = nPrefix+nSuffix;
146679       p->iOff += nSuffix;
146680       if( p->iChild==0 ){
146681         p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
146682         p->aDoclist = &p->aNode[p->iOff];
146683         p->iOff += p->nDoclist;
146684       }
146685     }
146686   }
146687 
146688   assert( p->iOff<=p->nNode );
146689 
146690   return rc;
146691 }
146692 
146693 /*
146694 ** Release all dynamic resources held by node-reader object *p.
146695 */
146696 static void nodeReaderRelease(NodeReader *p){
146697   sqlite3_free(p->term.a);
146698 }
146699 
146700 /*
146701 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
146702 **
146703 ** If successful, SQLITE_OK is returned and the NodeReader object set to
146704 ** point to the first entry on the node (if any). Otherwise, an SQLite
146705 ** error code is returned.
146706 */
146707 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
146708   memset(p, 0, sizeof(NodeReader));
146709   p->aNode = aNode;
146710   p->nNode = nNode;
146711 
146712   /* Figure out if this is a leaf or an internal node. */
146713   if( p->aNode[0] ){
146714     /* An internal node. */
146715     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
146716   }else{
146717     p->iOff = 1;
146718   }
146719 
146720   return nodeReaderNext(p);
146721 }
146722 
146723 /*
146724 ** This function is called while writing an FTS segment each time a leaf o
146725 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
146726 ** to be greater than the largest key on the node just written, but smaller
146727 ** than or equal to the first key that will be written to the next leaf
146728 ** node.
146729 **
146730 ** The block id of the leaf node just written to disk may be found in
146731 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
146732 */
146733 static int fts3IncrmergePush(
146734   Fts3Table *p,                   /* Fts3 table handle */
146735   IncrmergeWriter *pWriter,       /* Writer object */
146736   const char *zTerm,              /* Term to write to internal node */
146737   int nTerm                       /* Bytes at zTerm */
146738 ){
146739   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
146740   int iLayer;
146741 
146742   assert( nTerm>0 );
146743   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
146744     sqlite3_int64 iNextPtr = 0;
146745     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
146746     int rc = SQLITE_OK;
146747     int nPrefix;
146748     int nSuffix;
146749     int nSpace;
146750 
146751     /* Figure out how much space the key will consume if it is written to
146752     ** the current node of layer iLayer. Due to the prefix compression,
146753     ** the space required changes depending on which node the key is to
146754     ** be added to.  */
146755     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
146756     nSuffix = nTerm - nPrefix;
146757     nSpace  = sqlite3Fts3VarintLen(nPrefix);
146758     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
146759 
146760     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
146761       /* If the current node of layer iLayer contains zero keys, or if adding
146762       ** the key to it will not cause it to grow to larger than nNodeSize
146763       ** bytes in size, write the key here.  */
146764 
146765       Blob *pBlk = &pNode->block;
146766       if( pBlk->n==0 ){
146767         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
146768         if( rc==SQLITE_OK ){
146769           pBlk->a[0] = (char)iLayer;
146770           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
146771         }
146772       }
146773       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
146774       blobGrowBuffer(&pNode->key, nTerm, &rc);
146775 
146776       if( rc==SQLITE_OK ){
146777         if( pNode->key.n ){
146778           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
146779         }
146780         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
146781         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
146782         pBlk->n += nSuffix;
146783 
146784         memcpy(pNode->key.a, zTerm, nTerm);
146785         pNode->key.n = nTerm;
146786       }
146787     }else{
146788       /* Otherwise, flush the current node of layer iLayer to disk.
146789       ** Then allocate a new, empty sibling node. The key will be written
146790       ** into the parent of this node. */
146791       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
146792 
146793       assert( pNode->block.nAlloc>=p->nNodeSize );
146794       pNode->block.a[0] = (char)iLayer;
146795       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
146796 
146797       iNextPtr = pNode->iBlock;
146798       pNode->iBlock++;
146799       pNode->key.n = 0;
146800     }
146801 
146802     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
146803     iPtr = iNextPtr;
146804   }
146805 
146806   assert( 0 );
146807   return 0;
146808 }
146809 
146810 /*
146811 ** Append a term and (optionally) doclist to the FTS segment node currently
146812 ** stored in blob *pNode. The node need not contain any terms, but the
146813 ** header must be written before this function is called.
146814 **
146815 ** A node header is a single 0x00 byte for a leaf node, or a height varint
146816 ** followed by the left-hand-child varint for an internal node.
146817 **
146818 ** The term to be appended is passed via arguments zTerm/nTerm. For a
146819 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
146820 ** node, both aDoclist and nDoclist must be passed 0.
146821 **
146822 ** If the size of the value in blob pPrev is zero, then this is the first
146823 ** term written to the node. Otherwise, pPrev contains a copy of the
146824 ** previous term. Before this function returns, it is updated to contain a
146825 ** copy of zTerm/nTerm.
146826 **
146827 ** It is assumed that the buffer associated with pNode is already large
146828 ** enough to accommodate the new entry. The buffer associated with pPrev
146829 ** is extended by this function if requrired.
146830 **
146831 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
146832 ** returned. Otherwise, SQLITE_OK.
146833 */
146834 static int fts3AppendToNode(
146835   Blob *pNode,                    /* Current node image to append to */
146836   Blob *pPrev,                    /* Buffer containing previous term written */
146837   const char *zTerm,              /* New term to write */
146838   int nTerm,                      /* Size of zTerm in bytes */
146839   const char *aDoclist,           /* Doclist (or NULL) to write */
146840   int nDoclist                    /* Size of aDoclist in bytes */
146841 ){
146842   int rc = SQLITE_OK;             /* Return code */
146843   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
146844   int nPrefix;                    /* Size of term prefix in bytes */
146845   int nSuffix;                    /* Size of term suffix in bytes */
146846 
146847   /* Node must have already been started. There must be a doclist for a
146848   ** leaf node, and there must not be a doclist for an internal node.  */
146849   assert( pNode->n>0 );
146850   assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
146851 
146852   blobGrowBuffer(pPrev, nTerm, &rc);
146853   if( rc!=SQLITE_OK ) return rc;
146854 
146855   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
146856   nSuffix = nTerm - nPrefix;
146857   memcpy(pPrev->a, zTerm, nTerm);
146858   pPrev->n = nTerm;
146859 
146860   if( bFirst==0 ){
146861     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
146862   }
146863   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
146864   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
146865   pNode->n += nSuffix;
146866 
146867   if( aDoclist ){
146868     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
146869     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
146870     pNode->n += nDoclist;
146871   }
146872 
146873   assert( pNode->n<=pNode->nAlloc );
146874 
146875   return SQLITE_OK;
146876 }
146877 
146878 /*
146879 ** Append the current term and doclist pointed to by cursor pCsr to the
146880 ** appendable b-tree segment opened for writing by pWriter.
146881 **
146882 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
146883 */
146884 static int fts3IncrmergeAppend(
146885   Fts3Table *p,                   /* Fts3 table handle */
146886   IncrmergeWriter *pWriter,       /* Writer object */
146887   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
146888 ){
146889   const char *zTerm = pCsr->zTerm;
146890   int nTerm = pCsr->nTerm;
146891   const char *aDoclist = pCsr->aDoclist;
146892   int nDoclist = pCsr->nDoclist;
146893   int rc = SQLITE_OK;           /* Return code */
146894   int nSpace;                   /* Total space in bytes required on leaf */
146895   int nPrefix;                  /* Size of prefix shared with previous term */
146896   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
146897   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
146898 
146899   pLeaf = &pWriter->aNodeWriter[0];
146900   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
146901   nSuffix = nTerm - nPrefix;
146902 
146903   nSpace  = sqlite3Fts3VarintLen(nPrefix);
146904   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
146905   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
146906 
146907   /* If the current block is not empty, and if adding this term/doclist
146908   ** to the current block would make it larger than Fts3Table.nNodeSize
146909   ** bytes, write this block out to the database. */
146910   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
146911     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
146912     pWriter->nWork++;
146913 
146914     /* Add the current term to the parent node. The term added to the
146915     ** parent must:
146916     **
146917     **   a) be greater than the largest term on the leaf node just written
146918     **      to the database (still available in pLeaf->key), and
146919     **
146920     **   b) be less than or equal to the term about to be added to the new
146921     **      leaf node (zTerm/nTerm).
146922     **
146923     ** In other words, it must be the prefix of zTerm 1 byte longer than
146924     ** the common prefix (if any) of zTerm and pWriter->zTerm.
146925     */
146926     if( rc==SQLITE_OK ){
146927       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
146928     }
146929 
146930     /* Advance to the next output block */
146931     pLeaf->iBlock++;
146932     pLeaf->key.n = 0;
146933     pLeaf->block.n = 0;
146934 
146935     nSuffix = nTerm;
146936     nSpace  = 1;
146937     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
146938     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
146939   }
146940 
146941   pWriter->nLeafData += nSpace;
146942   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
146943   if( rc==SQLITE_OK ){
146944     if( pLeaf->block.n==0 ){
146945       pLeaf->block.n = 1;
146946       pLeaf->block.a[0] = '\0';
146947     }
146948     rc = fts3AppendToNode(
146949         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
146950     );
146951   }
146952 
146953   return rc;
146954 }
146955 
146956 /*
146957 ** This function is called to release all dynamic resources held by the
146958 ** merge-writer object pWriter, and if no error has occurred, to flush
146959 ** all outstanding node buffers held by pWriter to disk.
146960 **
146961 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
146962 ** is made to write any data to disk. Instead, this function serves only
146963 ** to release outstanding resources.
146964 **
146965 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
146966 ** flushing buffers to disk, *pRc is set to an SQLite error code before
146967 ** returning.
146968 */
146969 static void fts3IncrmergeRelease(
146970   Fts3Table *p,                   /* FTS3 table handle */
146971   IncrmergeWriter *pWriter,       /* Merge-writer object */
146972   int *pRc                        /* IN/OUT: Error code */
146973 ){
146974   int i;                          /* Used to iterate through non-root layers */
146975   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
146976   NodeWriter *pRoot;              /* NodeWriter for root node */
146977   int rc = *pRc;                  /* Error code */
146978 
146979   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
146980   ** root node. If the segment fits entirely on a single leaf node, iRoot
146981   ** will be set to 0. If the root node is the parent of the leaves, iRoot
146982   ** will be 1. And so on.  */
146983   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
146984     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
146985     if( pNode->block.n>0 ) break;
146986     assert( *pRc || pNode->block.nAlloc==0 );
146987     assert( *pRc || pNode->key.nAlloc==0 );
146988     sqlite3_free(pNode->block.a);
146989     sqlite3_free(pNode->key.a);
146990   }
146991 
146992   /* Empty output segment. This is a no-op. */
146993   if( iRoot<0 ) return;
146994 
146995   /* The entire output segment fits on a single node. Normally, this means
146996   ** the node would be stored as a blob in the "root" column of the %_segdir
146997   ** table. However, this is not permitted in this case. The problem is that
146998   ** space has already been reserved in the %_segments table, and so the
146999   ** start_block and end_block fields of the %_segdir table must be populated.
147000   ** And, by design or by accident, released versions of FTS cannot handle
147001   ** segments that fit entirely on the root node with start_block!=0.
147002   **
147003   ** Instead, create a synthetic root node that contains nothing but a
147004   ** pointer to the single content node. So that the segment consists of a
147005   ** single leaf and a single interior (root) node.
147006   **
147007   ** Todo: Better might be to defer allocating space in the %_segments
147008   ** table until we are sure it is needed.
147009   */
147010   if( iRoot==0 ){
147011     Blob *pBlock = &pWriter->aNodeWriter[1].block;
147012     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
147013     if( rc==SQLITE_OK ){
147014       pBlock->a[0] = 0x01;
147015       pBlock->n = 1 + sqlite3Fts3PutVarint(
147016           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
147017       );
147018     }
147019     iRoot = 1;
147020   }
147021   pRoot = &pWriter->aNodeWriter[iRoot];
147022 
147023   /* Flush all currently outstanding nodes to disk. */
147024   for(i=0; i<iRoot; i++){
147025     NodeWriter *pNode = &pWriter->aNodeWriter[i];
147026     if( pNode->block.n>0 && rc==SQLITE_OK ){
147027       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
147028     }
147029     sqlite3_free(pNode->block.a);
147030     sqlite3_free(pNode->key.a);
147031   }
147032 
147033   /* Write the %_segdir record. */
147034   if( rc==SQLITE_OK ){
147035     rc = fts3WriteSegdir(p,
147036         pWriter->iAbsLevel+1,               /* level */
147037         pWriter->iIdx,                      /* idx */
147038         pWriter->iStart,                    /* start_block */
147039         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
147040         pWriter->iEnd,                      /* end_block */
147041         (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
147042         pRoot->block.a, pRoot->block.n      /* root */
147043     );
147044   }
147045   sqlite3_free(pRoot->block.a);
147046   sqlite3_free(pRoot->key.a);
147047 
147048   *pRc = rc;
147049 }
147050 
147051 /*
147052 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
147053 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
147054 ** the other, it is considered to be smaller than the other.
147055 **
147056 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
147057 ** if it is greater.
147058 */
147059 static int fts3TermCmp(
147060   const char *zLhs, int nLhs,     /* LHS of comparison */
147061   const char *zRhs, int nRhs      /* RHS of comparison */
147062 ){
147063   int nCmp = MIN(nLhs, nRhs);
147064   int res;
147065 
147066   res = memcmp(zLhs, zRhs, nCmp);
147067   if( res==0 ) res = nLhs - nRhs;
147068 
147069   return res;
147070 }
147071 
147072 
147073 /*
147074 ** Query to see if the entry in the %_segments table with blockid iEnd is
147075 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
147076 ** returning. Otherwise, set *pbRes to 0.
147077 **
147078 ** Or, if an error occurs while querying the database, return an SQLite
147079 ** error code. The final value of *pbRes is undefined in this case.
147080 **
147081 ** This is used to test if a segment is an "appendable" segment. If it
147082 ** is, then a NULL entry has been inserted into the %_segments table
147083 ** with blockid %_segdir.end_block.
147084 */
147085 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
147086   int bRes = 0;                   /* Result to set *pbRes to */
147087   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
147088   int rc;                         /* Return code */
147089 
147090   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
147091   if( rc==SQLITE_OK ){
147092     sqlite3_bind_int64(pCheck, 1, iEnd);
147093     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
147094     rc = sqlite3_reset(pCheck);
147095   }
147096 
147097   *pbRes = bRes;
147098   return rc;
147099 }
147100 
147101 /*
147102 ** This function is called when initializing an incremental-merge operation.
147103 ** It checks if the existing segment with index value iIdx at absolute level
147104 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
147105 ** merge-writer object *pWriter is initialized to write to it.
147106 **
147107 ** An existing segment can be appended to by an incremental merge if:
147108 **
147109 **   * It was initially created as an appendable segment (with all required
147110 **     space pre-allocated), and
147111 **
147112 **   * The first key read from the input (arguments zKey and nKey) is
147113 **     greater than the largest key currently stored in the potential
147114 **     output segment.
147115 */
147116 static int fts3IncrmergeLoad(
147117   Fts3Table *p,                   /* Fts3 table handle */
147118   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
147119   int iIdx,                       /* Index of candidate output segment */
147120   const char *zKey,               /* First key to write */
147121   int nKey,                       /* Number of bytes in nKey */
147122   IncrmergeWriter *pWriter        /* Populate this object */
147123 ){
147124   int rc;                         /* Return code */
147125   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
147126 
147127   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
147128   if( rc==SQLITE_OK ){
147129     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
147130     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
147131     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
147132     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
147133     int nRoot = 0;                /* Size of aRoot[] in bytes */
147134     int rc2;                      /* Return code from sqlite3_reset() */
147135     int bAppendable = 0;          /* Set to true if segment is appendable */
147136 
147137     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
147138     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
147139     sqlite3_bind_int(pSelect, 2, iIdx);
147140     if( sqlite3_step(pSelect)==SQLITE_ROW ){
147141       iStart = sqlite3_column_int64(pSelect, 1);
147142       iLeafEnd = sqlite3_column_int64(pSelect, 2);
147143       fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
147144       if( pWriter->nLeafData<0 ){
147145         pWriter->nLeafData = pWriter->nLeafData * -1;
147146       }
147147       pWriter->bNoLeafData = (pWriter->nLeafData==0);
147148       nRoot = sqlite3_column_bytes(pSelect, 4);
147149       aRoot = sqlite3_column_blob(pSelect, 4);
147150     }else{
147151       return sqlite3_reset(pSelect);
147152     }
147153 
147154     /* Check for the zero-length marker in the %_segments table */
147155     rc = fts3IsAppendable(p, iEnd, &bAppendable);
147156 
147157     /* Check that zKey/nKey is larger than the largest key the candidate */
147158     if( rc==SQLITE_OK && bAppendable ){
147159       char *aLeaf = 0;
147160       int nLeaf = 0;
147161 
147162       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
147163       if( rc==SQLITE_OK ){
147164         NodeReader reader;
147165         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
147166             rc==SQLITE_OK && reader.aNode;
147167             rc = nodeReaderNext(&reader)
147168         ){
147169           assert( reader.aNode );
147170         }
147171         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
147172           bAppendable = 0;
147173         }
147174         nodeReaderRelease(&reader);
147175       }
147176       sqlite3_free(aLeaf);
147177     }
147178 
147179     if( rc==SQLITE_OK && bAppendable ){
147180       /* It is possible to append to this segment. Set up the IncrmergeWriter
147181       ** object to do so.  */
147182       int i;
147183       int nHeight = (int)aRoot[0];
147184       NodeWriter *pNode;
147185 
147186       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
147187       pWriter->iStart = iStart;
147188       pWriter->iEnd = iEnd;
147189       pWriter->iAbsLevel = iAbsLevel;
147190       pWriter->iIdx = iIdx;
147191 
147192       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
147193         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
147194       }
147195 
147196       pNode = &pWriter->aNodeWriter[nHeight];
147197       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
147198       blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
147199       if( rc==SQLITE_OK ){
147200         memcpy(pNode->block.a, aRoot, nRoot);
147201         pNode->block.n = nRoot;
147202       }
147203 
147204       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
147205         NodeReader reader;
147206         pNode = &pWriter->aNodeWriter[i];
147207 
147208         rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
147209         while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
147210         blobGrowBuffer(&pNode->key, reader.term.n, &rc);
147211         if( rc==SQLITE_OK ){
147212           memcpy(pNode->key.a, reader.term.a, reader.term.n);
147213           pNode->key.n = reader.term.n;
147214           if( i>0 ){
147215             char *aBlock = 0;
147216             int nBlock = 0;
147217             pNode = &pWriter->aNodeWriter[i-1];
147218             pNode->iBlock = reader.iChild;
147219             rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
147220             blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
147221             if( rc==SQLITE_OK ){
147222               memcpy(pNode->block.a, aBlock, nBlock);
147223               pNode->block.n = nBlock;
147224             }
147225             sqlite3_free(aBlock);
147226           }
147227         }
147228         nodeReaderRelease(&reader);
147229       }
147230     }
147231 
147232     rc2 = sqlite3_reset(pSelect);
147233     if( rc==SQLITE_OK ) rc = rc2;
147234   }
147235 
147236   return rc;
147237 }
147238 
147239 /*
147240 ** Determine the largest segment index value that exists within absolute
147241 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
147242 ** one before returning SQLITE_OK. Or, if there are no segments at all
147243 ** within level iAbsLevel, set *piIdx to zero.
147244 **
147245 ** If an error occurs, return an SQLite error code. The final value of
147246 ** *piIdx is undefined in this case.
147247 */
147248 static int fts3IncrmergeOutputIdx(
147249   Fts3Table *p,                   /* FTS Table handle */
147250   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
147251   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
147252 ){
147253   int rc;
147254   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
147255 
147256   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
147257   if( rc==SQLITE_OK ){
147258     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
147259     sqlite3_step(pOutputIdx);
147260     *piIdx = sqlite3_column_int(pOutputIdx, 0);
147261     rc = sqlite3_reset(pOutputIdx);
147262   }
147263 
147264   return rc;
147265 }
147266 
147267 /*
147268 ** Allocate an appendable output segment on absolute level iAbsLevel+1
147269 ** with idx value iIdx.
147270 **
147271 ** In the %_segdir table, a segment is defined by the values in three
147272 ** columns:
147273 **
147274 **     start_block
147275 **     leaves_end_block
147276 **     end_block
147277 **
147278 ** When an appendable segment is allocated, it is estimated that the
147279 ** maximum number of leaf blocks that may be required is the sum of the
147280 ** number of leaf blocks consumed by the input segments, plus the number
147281 ** of input segments, multiplied by two. This value is stored in stack
147282 ** variable nLeafEst.
147283 **
147284 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
147285 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
147286 ** array of leaf nodes starts at the first block allocated. The array
147287 ** of interior nodes that are parents of the leaf nodes start at block
147288 ** (start_block + (1 + end_block - start_block) / 16). And so on.
147289 **
147290 ** In the actual code below, the value "16" is replaced with the
147291 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
147292 */
147293 static int fts3IncrmergeWriter(
147294   Fts3Table *p,                   /* Fts3 table handle */
147295   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
147296   int iIdx,                       /* Index of new output segment */
147297   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
147298   IncrmergeWriter *pWriter        /* Populate this object */
147299 ){
147300   int rc;                         /* Return Code */
147301   int i;                          /* Iterator variable */
147302   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
147303   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
147304   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
147305 
147306   /* Calculate nLeafEst. */
147307   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
147308   if( rc==SQLITE_OK ){
147309     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
147310     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
147311     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
147312       nLeafEst = sqlite3_column_int(pLeafEst, 0);
147313     }
147314     rc = sqlite3_reset(pLeafEst);
147315   }
147316   if( rc!=SQLITE_OK ) return rc;
147317 
147318   /* Calculate the first block to use in the output segment */
147319   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
147320   if( rc==SQLITE_OK ){
147321     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
147322       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
147323       pWriter->iEnd = pWriter->iStart - 1;
147324       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
147325     }
147326     rc = sqlite3_reset(pFirstBlock);
147327   }
147328   if( rc!=SQLITE_OK ) return rc;
147329 
147330   /* Insert the marker in the %_segments table to make sure nobody tries
147331   ** to steal the space just allocated. This is also used to identify
147332   ** appendable segments.  */
147333   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
147334   if( rc!=SQLITE_OK ) return rc;
147335 
147336   pWriter->iAbsLevel = iAbsLevel;
147337   pWriter->nLeafEst = nLeafEst;
147338   pWriter->iIdx = iIdx;
147339 
147340   /* Set up the array of NodeWriter objects */
147341   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
147342     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
147343   }
147344   return SQLITE_OK;
147345 }
147346 
147347 /*
147348 ** Remove an entry from the %_segdir table. This involves running the
147349 ** following two statements:
147350 **
147351 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
147352 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
147353 **
147354 ** The DELETE statement removes the specific %_segdir level. The UPDATE
147355 ** statement ensures that the remaining segments have contiguously allocated
147356 ** idx values.
147357 */
147358 static int fts3RemoveSegdirEntry(
147359   Fts3Table *p,                   /* FTS3 table handle */
147360   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
147361   int iIdx                        /* Index of %_segdir entry to delete */
147362 ){
147363   int rc;                         /* Return code */
147364   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
147365 
147366   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
147367   if( rc==SQLITE_OK ){
147368     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
147369     sqlite3_bind_int(pDelete, 2, iIdx);
147370     sqlite3_step(pDelete);
147371     rc = sqlite3_reset(pDelete);
147372   }
147373 
147374   return rc;
147375 }
147376 
147377 /*
147378 ** One or more segments have just been removed from absolute level iAbsLevel.
147379 ** Update the 'idx' values of the remaining segments in the level so that
147380 ** the idx values are a contiguous sequence starting from 0.
147381 */
147382 static int fts3RepackSegdirLevel(
147383   Fts3Table *p,                   /* FTS3 table handle */
147384   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
147385 ){
147386   int rc;                         /* Return code */
147387   int *aIdx = 0;                  /* Array of remaining idx values */
147388   int nIdx = 0;                   /* Valid entries in aIdx[] */
147389   int nAlloc = 0;                 /* Allocated size of aIdx[] */
147390   int i;                          /* Iterator variable */
147391   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
147392   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
147393 
147394   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
147395   if( rc==SQLITE_OK ){
147396     int rc2;
147397     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
147398     while( SQLITE_ROW==sqlite3_step(pSelect) ){
147399       if( nIdx>=nAlloc ){
147400         int *aNew;
147401         nAlloc += 16;
147402         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
147403         if( !aNew ){
147404           rc = SQLITE_NOMEM;
147405           break;
147406         }
147407         aIdx = aNew;
147408       }
147409       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
147410     }
147411     rc2 = sqlite3_reset(pSelect);
147412     if( rc==SQLITE_OK ) rc = rc2;
147413   }
147414 
147415   if( rc==SQLITE_OK ){
147416     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
147417   }
147418   if( rc==SQLITE_OK ){
147419     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
147420   }
147421 
147422   assert( p->bIgnoreSavepoint==0 );
147423   p->bIgnoreSavepoint = 1;
147424   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
147425     if( aIdx[i]!=i ){
147426       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
147427       sqlite3_bind_int(pUpdate, 1, i);
147428       sqlite3_step(pUpdate);
147429       rc = sqlite3_reset(pUpdate);
147430     }
147431   }
147432   p->bIgnoreSavepoint = 0;
147433 
147434   sqlite3_free(aIdx);
147435   return rc;
147436 }
147437 
147438 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
147439   pNode->a[0] = (char)iHeight;
147440   if( iChild ){
147441     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
147442     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
147443   }else{
147444     assert( pNode->nAlloc>=1 );
147445     pNode->n = 1;
147446   }
147447 }
147448 
147449 /*
147450 ** The first two arguments are a pointer to and the size of a segment b-tree
147451 ** node. The node may be a leaf or an internal node.
147452 **
147453 ** This function creates a new node image in blob object *pNew by copying
147454 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
147455 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
147456 */
147457 static int fts3TruncateNode(
147458   const char *aNode,              /* Current node image */
147459   int nNode,                      /* Size of aNode in bytes */
147460   Blob *pNew,                     /* OUT: Write new node image here */
147461   const char *zTerm,              /* Omit all terms smaller than this */
147462   int nTerm,                      /* Size of zTerm in bytes */
147463   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
147464 ){
147465   NodeReader reader;              /* Reader object */
147466   Blob prev = {0, 0, 0};          /* Previous term written to new node */
147467   int rc = SQLITE_OK;             /* Return code */
147468   int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
147469 
147470   /* Allocate required output space */
147471   blobGrowBuffer(pNew, nNode, &rc);
147472   if( rc!=SQLITE_OK ) return rc;
147473   pNew->n = 0;
147474 
147475   /* Populate new node buffer */
147476   for(rc = nodeReaderInit(&reader, aNode, nNode);
147477       rc==SQLITE_OK && reader.aNode;
147478       rc = nodeReaderNext(&reader)
147479   ){
147480     if( pNew->n==0 ){
147481       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
147482       if( res<0 || (bLeaf==0 && res==0) ) continue;
147483       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
147484       *piBlock = reader.iChild;
147485     }
147486     rc = fts3AppendToNode(
147487         pNew, &prev, reader.term.a, reader.term.n,
147488         reader.aDoclist, reader.nDoclist
147489     );
147490     if( rc!=SQLITE_OK ) break;
147491   }
147492   if( pNew->n==0 ){
147493     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
147494     *piBlock = reader.iChild;
147495   }
147496   assert( pNew->n<=pNew->nAlloc );
147497 
147498   nodeReaderRelease(&reader);
147499   sqlite3_free(prev.a);
147500   return rc;
147501 }
147502 
147503 /*
147504 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
147505 ** level iAbsLevel. This may involve deleting entries from the %_segments
147506 ** table, and modifying existing entries in both the %_segments and %_segdir
147507 ** tables.
147508 **
147509 ** SQLITE_OK is returned if the segment is updated successfully. Or an
147510 ** SQLite error code otherwise.
147511 */
147512 static int fts3TruncateSegment(
147513   Fts3Table *p,                   /* FTS3 table handle */
147514   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
147515   int iIdx,                       /* Index within level of segment to modify */
147516   const char *zTerm,              /* Remove terms smaller than this */
147517   int nTerm                      /* Number of bytes in buffer zTerm */
147518 ){
147519   int rc = SQLITE_OK;             /* Return code */
147520   Blob root = {0,0,0};            /* New root page image */
147521   Blob block = {0,0,0};           /* Buffer used for any other block */
147522   sqlite3_int64 iBlock = 0;       /* Block id */
147523   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
147524   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
147525   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
147526 
147527   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
147528   if( rc==SQLITE_OK ){
147529     int rc2;                      /* sqlite3_reset() return code */
147530     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
147531     sqlite3_bind_int(pFetch, 2, iIdx);
147532     if( SQLITE_ROW==sqlite3_step(pFetch) ){
147533       const char *aRoot = sqlite3_column_blob(pFetch, 4);
147534       int nRoot = sqlite3_column_bytes(pFetch, 4);
147535       iOldStart = sqlite3_column_int64(pFetch, 1);
147536       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
147537     }
147538     rc2 = sqlite3_reset(pFetch);
147539     if( rc==SQLITE_OK ) rc = rc2;
147540   }
147541 
147542   while( rc==SQLITE_OK && iBlock ){
147543     char *aBlock = 0;
147544     int nBlock = 0;
147545     iNewStart = iBlock;
147546 
147547     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
147548     if( rc==SQLITE_OK ){
147549       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
147550     }
147551     if( rc==SQLITE_OK ){
147552       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
147553     }
147554     sqlite3_free(aBlock);
147555   }
147556 
147557   /* Variable iNewStart now contains the first valid leaf node. */
147558   if( rc==SQLITE_OK && iNewStart ){
147559     sqlite3_stmt *pDel = 0;
147560     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
147561     if( rc==SQLITE_OK ){
147562       sqlite3_bind_int64(pDel, 1, iOldStart);
147563       sqlite3_bind_int64(pDel, 2, iNewStart-1);
147564       sqlite3_step(pDel);
147565       rc = sqlite3_reset(pDel);
147566     }
147567   }
147568 
147569   if( rc==SQLITE_OK ){
147570     sqlite3_stmt *pChomp = 0;
147571     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
147572     if( rc==SQLITE_OK ){
147573       sqlite3_bind_int64(pChomp, 1, iNewStart);
147574       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
147575       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
147576       sqlite3_bind_int(pChomp, 4, iIdx);
147577       sqlite3_step(pChomp);
147578       rc = sqlite3_reset(pChomp);
147579     }
147580   }
147581 
147582   sqlite3_free(root.a);
147583   sqlite3_free(block.a);
147584   return rc;
147585 }
147586 
147587 /*
147588 ** This function is called after an incrmental-merge operation has run to
147589 ** merge (or partially merge) two or more segments from absolute level
147590 ** iAbsLevel.
147591 **
147592 ** Each input segment is either removed from the db completely (if all of
147593 ** its data was copied to the output segment by the incrmerge operation)
147594 ** or modified in place so that it no longer contains those entries that
147595 ** have been duplicated in the output segment.
147596 */
147597 static int fts3IncrmergeChomp(
147598   Fts3Table *p,                   /* FTS table handle */
147599   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
147600   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
147601   int *pnRem                      /* Number of segments not deleted */
147602 ){
147603   int i;
147604   int nRem = 0;
147605   int rc = SQLITE_OK;
147606 
147607   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
147608     Fts3SegReader *pSeg = 0;
147609     int j;
147610 
147611     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
147612     ** somewhere in the pCsr->apSegment[] array.  */
147613     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
147614       pSeg = pCsr->apSegment[j];
147615       if( pSeg->iIdx==i ) break;
147616     }
147617     assert( j<pCsr->nSegment && pSeg->iIdx==i );
147618 
147619     if( pSeg->aNode==0 ){
147620       /* Seg-reader is at EOF. Remove the entire input segment. */
147621       rc = fts3DeleteSegment(p, pSeg);
147622       if( rc==SQLITE_OK ){
147623         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
147624       }
147625       *pnRem = 0;
147626     }else{
147627       /* The incremental merge did not copy all the data from this
147628       ** segment to the upper level. The segment is modified in place
147629       ** so that it contains no keys smaller than zTerm/nTerm. */
147630       const char *zTerm = pSeg->zTerm;
147631       int nTerm = pSeg->nTerm;
147632       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
147633       nRem++;
147634     }
147635   }
147636 
147637   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
147638     rc = fts3RepackSegdirLevel(p, iAbsLevel);
147639   }
147640 
147641   *pnRem = nRem;
147642   return rc;
147643 }
147644 
147645 /*
147646 ** Store an incr-merge hint in the database.
147647 */
147648 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
147649   sqlite3_stmt *pReplace = 0;
147650   int rc;                         /* Return code */
147651 
147652   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
147653   if( rc==SQLITE_OK ){
147654     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
147655     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
147656     sqlite3_step(pReplace);
147657     rc = sqlite3_reset(pReplace);
147658   }
147659 
147660   return rc;
147661 }
147662 
147663 /*
147664 ** Load an incr-merge hint from the database. The incr-merge hint, if one
147665 ** exists, is stored in the rowid==1 row of the %_stat table.
147666 **
147667 ** If successful, populate blob *pHint with the value read from the %_stat
147668 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
147669 ** SQLite error code.
147670 */
147671 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
147672   sqlite3_stmt *pSelect = 0;
147673   int rc;
147674 
147675   pHint->n = 0;
147676   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
147677   if( rc==SQLITE_OK ){
147678     int rc2;
147679     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
147680     if( SQLITE_ROW==sqlite3_step(pSelect) ){
147681       const char *aHint = sqlite3_column_blob(pSelect, 0);
147682       int nHint = sqlite3_column_bytes(pSelect, 0);
147683       if( aHint ){
147684         blobGrowBuffer(pHint, nHint, &rc);
147685         if( rc==SQLITE_OK ){
147686           memcpy(pHint->a, aHint, nHint);
147687           pHint->n = nHint;
147688         }
147689       }
147690     }
147691     rc2 = sqlite3_reset(pSelect);
147692     if( rc==SQLITE_OK ) rc = rc2;
147693   }
147694 
147695   return rc;
147696 }
147697 
147698 /*
147699 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
147700 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
147701 ** consists of two varints, the absolute level number of the input segments
147702 ** and the number of input segments.
147703 **
147704 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
147705 ** set *pRc to an SQLite error code before returning.
147706 */
147707 static void fts3IncrmergeHintPush(
147708   Blob *pHint,                    /* Hint blob to append to */
147709   i64 iAbsLevel,                  /* First varint to store in hint */
147710   int nInput,                     /* Second varint to store in hint */
147711   int *pRc                        /* IN/OUT: Error code */
147712 ){
147713   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
147714   if( *pRc==SQLITE_OK ){
147715     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
147716     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
147717   }
147718 }
147719 
147720 /*
147721 ** Read the last entry (most recently pushed) from the hint blob *pHint
147722 ** and then remove the entry. Write the two values read to *piAbsLevel and
147723 ** *pnInput before returning.
147724 **
147725 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
147726 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
147727 */
147728 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
147729   const int nHint = pHint->n;
147730   int i;
147731 
147732   i = pHint->n-2;
147733   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
147734   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
147735 
147736   pHint->n = i;
147737   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
147738   i += fts3GetVarint32(&pHint->a[i], pnInput);
147739   if( i!=nHint ) return FTS_CORRUPT_VTAB;
147740 
147741   return SQLITE_OK;
147742 }
147743 
147744 
147745 /*
147746 ** Attempt an incremental merge that writes nMerge leaf blocks.
147747 **
147748 ** Incremental merges happen nMin segments at a time. The segments
147749 ** to be merged are the nMin oldest segments (the ones with the smallest
147750 ** values for the _segdir.idx field) in the highest level that contains
147751 ** at least nMin segments. Multiple merges might occur in an attempt to
147752 ** write the quota of nMerge leaf blocks.
147753 */
147754 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
147755   int rc;                         /* Return code */
147756   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
147757   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
147758   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
147759   IncrmergeWriter *pWriter;       /* Writer object */
147760   int nSeg = 0;                   /* Number of input segments */
147761   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
147762   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
147763   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
147764 
147765   /* Allocate space for the cursor, filter and writer objects */
147766   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
147767   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
147768   if( !pWriter ) return SQLITE_NOMEM;
147769   pFilter = (Fts3SegFilter *)&pWriter[1];
147770   pCsr = (Fts3MultiSegReader *)&pFilter[1];
147771 
147772   rc = fts3IncrmergeHintLoad(p, &hint);
147773   while( rc==SQLITE_OK && nRem>0 ){
147774     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
147775     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
147776     int bUseHint = 0;             /* True if attempting to append */
147777     int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
147778 
147779     /* Search the %_segdir table for the absolute level with the smallest
147780     ** relative level number that contains at least nMin segments, if any.
147781     ** If one is found, set iAbsLevel to the absolute level number and
147782     ** nSeg to nMin. If no level with at least nMin segments can be found,
147783     ** set nSeg to -1.
147784     */
147785     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
147786     sqlite3_bind_int(pFindLevel, 1, nMin);
147787     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
147788       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
147789       nSeg = nMin;
147790     }else{
147791       nSeg = -1;
147792     }
147793     rc = sqlite3_reset(pFindLevel);
147794 
147795     /* If the hint read from the %_stat table is not empty, check if the
147796     ** last entry in it specifies a relative level smaller than or equal
147797     ** to the level identified by the block above (if any). If so, this
147798     ** iteration of the loop will work on merging at the hinted level.
147799     */
147800     if( rc==SQLITE_OK && hint.n ){
147801       int nHint = hint.n;
147802       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
147803       int nHintSeg = 0;                     /* Hint number of segments */
147804 
147805       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
147806       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
147807         iAbsLevel = iHintAbsLevel;
147808         nSeg = nHintSeg;
147809         bUseHint = 1;
147810         bDirtyHint = 1;
147811       }else{
147812         /* This undoes the effect of the HintPop() above - so that no entry
147813         ** is removed from the hint blob.  */
147814         hint.n = nHint;
147815       }
147816     }
147817 
147818     /* If nSeg is less that zero, then there is no level with at least
147819     ** nMin segments and no hint in the %_stat table. No work to do.
147820     ** Exit early in this case.  */
147821     if( nSeg<0 ) break;
147822 
147823     /* Open a cursor to iterate through the contents of the oldest nSeg
147824     ** indexes of absolute level iAbsLevel. If this cursor is opened using
147825     ** the 'hint' parameters, it is possible that there are less than nSeg
147826     ** segments available in level iAbsLevel. In this case, no work is
147827     ** done on iAbsLevel - fall through to the next iteration of the loop
147828     ** to start work on some other level.  */
147829     memset(pWriter, 0, nAlloc);
147830     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
147831 
147832     if( rc==SQLITE_OK ){
147833       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
147834       assert( bUseHint==1 || bUseHint==0 );
147835       if( iIdx==0 || (bUseHint && iIdx==1) ){
147836         int bIgnore = 0;
147837         rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
147838         if( bIgnore ){
147839           pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
147840         }
147841       }
147842     }
147843 
147844     if( rc==SQLITE_OK ){
147845       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
147846     }
147847     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
147848      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
147849      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
147850     ){
147851       if( bUseHint && iIdx>0 ){
147852         const char *zKey = pCsr->zTerm;
147853         int nKey = pCsr->nTerm;
147854         rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
147855       }else{
147856         rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
147857       }
147858 
147859       if( rc==SQLITE_OK && pWriter->nLeafEst ){
147860         fts3LogMerge(nSeg, iAbsLevel);
147861         do {
147862           rc = fts3IncrmergeAppend(p, pWriter, pCsr);
147863           if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
147864           if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
147865         }while( rc==SQLITE_ROW );
147866 
147867         /* Update or delete the input segments */
147868         if( rc==SQLITE_OK ){
147869           nRem -= (1 + pWriter->nWork);
147870           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
147871           if( nSeg!=0 ){
147872             bDirtyHint = 1;
147873             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
147874           }
147875         }
147876       }
147877 
147878       if( nSeg!=0 ){
147879         pWriter->nLeafData = pWriter->nLeafData * -1;
147880       }
147881       fts3IncrmergeRelease(p, pWriter, &rc);
147882       if( nSeg==0 && pWriter->bNoLeafData==0 ){
147883         fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
147884       }
147885     }
147886 
147887     sqlite3Fts3SegReaderFinish(pCsr);
147888   }
147889 
147890   /* Write the hint values into the %_stat table for the next incr-merger */
147891   if( bDirtyHint && rc==SQLITE_OK ){
147892     rc = fts3IncrmergeHintStore(p, &hint);
147893   }
147894 
147895   sqlite3_free(pWriter);
147896   sqlite3_free(hint.a);
147897   return rc;
147898 }
147899 
147900 /*
147901 ** Convert the text beginning at *pz into an integer and return
147902 ** its value.  Advance *pz to point to the first character past
147903 ** the integer.
147904 */
147905 static int fts3Getint(const char **pz){
147906   const char *z = *pz;
147907   int i = 0;
147908   while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
147909   *pz = z;
147910   return i;
147911 }
147912 
147913 /*
147914 ** Process statements of the form:
147915 **
147916 **    INSERT INTO table(table) VALUES('merge=A,B');
147917 **
147918 ** A and B are integers that decode to be the number of leaf pages
147919 ** written for the merge, and the minimum number of segments on a level
147920 ** before it will be selected for a merge, respectively.
147921 */
147922 static int fts3DoIncrmerge(
147923   Fts3Table *p,                   /* FTS3 table handle */
147924   const char *zParam              /* Nul-terminated string containing "A,B" */
147925 ){
147926   int rc;
147927   int nMin = (FTS3_MERGE_COUNT / 2);
147928   int nMerge = 0;
147929   const char *z = zParam;
147930 
147931   /* Read the first integer value */
147932   nMerge = fts3Getint(&z);
147933 
147934   /* If the first integer value is followed by a ',',  read the second
147935   ** integer value. */
147936   if( z[0]==',' && z[1]!='\0' ){
147937     z++;
147938     nMin = fts3Getint(&z);
147939   }
147940 
147941   if( z[0]!='\0' || nMin<2 ){
147942     rc = SQLITE_ERROR;
147943   }else{
147944     rc = SQLITE_OK;
147945     if( !p->bHasStat ){
147946       assert( p->bFts4==0 );
147947       sqlite3Fts3CreateStatTable(&rc, p);
147948     }
147949     if( rc==SQLITE_OK ){
147950       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
147951     }
147952     sqlite3Fts3SegmentsClose(p);
147953   }
147954   return rc;
147955 }
147956 
147957 /*
147958 ** Process statements of the form:
147959 **
147960 **    INSERT INTO table(table) VALUES('automerge=X');
147961 **
147962 ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
147963 ** turn it on.  The setting is persistent.
147964 */
147965 static int fts3DoAutoincrmerge(
147966   Fts3Table *p,                   /* FTS3 table handle */
147967   const char *zParam              /* Nul-terminated string containing boolean */
147968 ){
147969   int rc = SQLITE_OK;
147970   sqlite3_stmt *pStmt = 0;
147971   p->nAutoincrmerge = fts3Getint(&zParam);
147972   if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
147973     p->nAutoincrmerge = 8;
147974   }
147975   if( !p->bHasStat ){
147976     assert( p->bFts4==0 );
147977     sqlite3Fts3CreateStatTable(&rc, p);
147978     if( rc ) return rc;
147979   }
147980   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
147981   if( rc ) return rc;
147982   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
147983   sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
147984   sqlite3_step(pStmt);
147985   rc = sqlite3_reset(pStmt);
147986   return rc;
147987 }
147988 
147989 /*
147990 ** Return a 64-bit checksum for the FTS index entry specified by the
147991 ** arguments to this function.
147992 */
147993 static u64 fts3ChecksumEntry(
147994   const char *zTerm,              /* Pointer to buffer containing term */
147995   int nTerm,                      /* Size of zTerm in bytes */
147996   int iLangid,                    /* Language id for current row */
147997   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
147998   i64 iDocid,                     /* Docid for current row. */
147999   int iCol,                       /* Column number */
148000   int iPos                        /* Position */
148001 ){
148002   int i;
148003   u64 ret = (u64)iDocid;
148004 
148005   ret += (ret<<3) + iLangid;
148006   ret += (ret<<3) + iIndex;
148007   ret += (ret<<3) + iCol;
148008   ret += (ret<<3) + iPos;
148009   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
148010 
148011   return ret;
148012 }
148013 
148014 /*
148015 ** Return a checksum of all entries in the FTS index that correspond to
148016 ** language id iLangid. The checksum is calculated by XORing the checksums
148017 ** of each individual entry (see fts3ChecksumEntry()) together.
148018 **
148019 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
148020 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
148021 ** return value is undefined in this case.
148022 */
148023 static u64 fts3ChecksumIndex(
148024   Fts3Table *p,                   /* FTS3 table handle */
148025   int iLangid,                    /* Language id to return cksum for */
148026   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
148027   int *pRc                        /* OUT: Return code */
148028 ){
148029   Fts3SegFilter filter;
148030   Fts3MultiSegReader csr;
148031   int rc;
148032   u64 cksum = 0;
148033 
148034   assert( *pRc==SQLITE_OK );
148035 
148036   memset(&filter, 0, sizeof(filter));
148037   memset(&csr, 0, sizeof(csr));
148038   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
148039   filter.flags |= FTS3_SEGMENT_SCAN;
148040 
148041   rc = sqlite3Fts3SegReaderCursor(
148042       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
148043   );
148044   if( rc==SQLITE_OK ){
148045     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
148046   }
148047 
148048   if( rc==SQLITE_OK ){
148049     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
148050       char *pCsr = csr.aDoclist;
148051       char *pEnd = &pCsr[csr.nDoclist];
148052 
148053       i64 iDocid = 0;
148054       i64 iCol = 0;
148055       i64 iPos = 0;
148056 
148057       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
148058       while( pCsr<pEnd ){
148059         i64 iVal = 0;
148060         pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
148061         if( pCsr<pEnd ){
148062           if( iVal==0 || iVal==1 ){
148063             iCol = 0;
148064             iPos = 0;
148065             if( iVal ){
148066               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
148067             }else{
148068               pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
148069               iDocid += iVal;
148070             }
148071           }else{
148072             iPos += (iVal - 2);
148073             cksum = cksum ^ fts3ChecksumEntry(
148074                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
148075                 (int)iCol, (int)iPos
148076             );
148077           }
148078         }
148079       }
148080     }
148081   }
148082   sqlite3Fts3SegReaderFinish(&csr);
148083 
148084   *pRc = rc;
148085   return cksum;
148086 }
148087 
148088 /*
148089 ** Check if the contents of the FTS index match the current contents of the
148090 ** content table. If no error occurs and the contents do match, set *pbOk
148091 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
148092 ** to false before returning.
148093 **
148094 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
148095 ** code. The final value of *pbOk is undefined in this case.
148096 */
148097 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
148098   int rc = SQLITE_OK;             /* Return code */
148099   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
148100   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
148101   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
148102 
148103   /* This block calculates the checksum according to the FTS index. */
148104   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
148105   if( rc==SQLITE_OK ){
148106     int rc2;
148107     sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
148108     sqlite3_bind_int(pAllLangid, 2, p->nIndex);
148109     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
148110       int iLangid = sqlite3_column_int(pAllLangid, 0);
148111       int i;
148112       for(i=0; i<p->nIndex; i++){
148113         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
148114       }
148115     }
148116     rc2 = sqlite3_reset(pAllLangid);
148117     if( rc==SQLITE_OK ) rc = rc2;
148118   }
148119 
148120   /* This block calculates the checksum according to the %_content table */
148121   if( rc==SQLITE_OK ){
148122     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
148123     sqlite3_stmt *pStmt = 0;
148124     char *zSql;
148125 
148126     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
148127     if( !zSql ){
148128       rc = SQLITE_NOMEM;
148129     }else{
148130       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
148131       sqlite3_free(zSql);
148132     }
148133 
148134     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
148135       i64 iDocid = sqlite3_column_int64(pStmt, 0);
148136       int iLang = langidFromSelect(p, pStmt);
148137       int iCol;
148138 
148139       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
148140         if( p->abNotindexed[iCol]==0 ){
148141           const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
148142           int nText = sqlite3_column_bytes(pStmt, iCol+1);
148143           sqlite3_tokenizer_cursor *pT = 0;
148144 
148145           rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
148146           while( rc==SQLITE_OK ){
148147             char const *zToken;       /* Buffer containing token */
148148             int nToken = 0;           /* Number of bytes in token */
148149             int iDum1 = 0, iDum2 = 0; /* Dummy variables */
148150             int iPos = 0;             /* Position of token in zText */
148151 
148152             rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
148153             if( rc==SQLITE_OK ){
148154               int i;
148155               cksum2 = cksum2 ^ fts3ChecksumEntry(
148156                   zToken, nToken, iLang, 0, iDocid, iCol, iPos
148157               );
148158               for(i=1; i<p->nIndex; i++){
148159                 if( p->aIndex[i].nPrefix<=nToken ){
148160                   cksum2 = cksum2 ^ fts3ChecksumEntry(
148161                       zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
148162                   );
148163                 }
148164               }
148165             }
148166           }
148167           if( pT ) pModule->xClose(pT);
148168           if( rc==SQLITE_DONE ) rc = SQLITE_OK;
148169         }
148170       }
148171     }
148172 
148173     sqlite3_finalize(pStmt);
148174   }
148175 
148176   *pbOk = (cksum1==cksum2);
148177   return rc;
148178 }
148179 
148180 /*
148181 ** Run the integrity-check. If no error occurs and the current contents of
148182 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
148183 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
148184 **
148185 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
148186 ** error code.
148187 **
148188 ** The integrity-check works as follows. For each token and indexed token
148189 ** prefix in the document set, a 64-bit checksum is calculated (by code
148190 ** in fts3ChecksumEntry()) based on the following:
148191 **
148192 **     + The index number (0 for the main index, 1 for the first prefix
148193 **       index etc.),
148194 **     + The token (or token prefix) text itself,
148195 **     + The language-id of the row it appears in,
148196 **     + The docid of the row it appears in,
148197 **     + The column it appears in, and
148198 **     + The tokens position within that column.
148199 **
148200 ** The checksums for all entries in the index are XORed together to create
148201 ** a single checksum for the entire index.
148202 **
148203 ** The integrity-check code calculates the same checksum in two ways:
148204 **
148205 **     1. By scanning the contents of the FTS index, and
148206 **     2. By scanning and tokenizing the content table.
148207 **
148208 ** If the two checksums are identical, the integrity-check is deemed to have
148209 ** passed.
148210 */
148211 static int fts3DoIntegrityCheck(
148212   Fts3Table *p                    /* FTS3 table handle */
148213 ){
148214   int rc;
148215   int bOk = 0;
148216   rc = fts3IntegrityCheck(p, &bOk);
148217   if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
148218   return rc;
148219 }
148220 
148221 /*
148222 ** Handle a 'special' INSERT of the form:
148223 **
148224 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
148225 **
148226 ** Argument pVal contains the result of <expr>. Currently the only
148227 ** meaningful value to insert is the text 'optimize'.
148228 */
148229 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
148230   int rc;                         /* Return Code */
148231   const char *zVal = (const char *)sqlite3_value_text(pVal);
148232   int nVal = sqlite3_value_bytes(pVal);
148233 
148234   if( !zVal ){
148235     return SQLITE_NOMEM;
148236   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
148237     rc = fts3DoOptimize(p, 0);
148238   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
148239     rc = fts3DoRebuild(p);
148240   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
148241     rc = fts3DoIntegrityCheck(p);
148242   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
148243     rc = fts3DoIncrmerge(p, &zVal[6]);
148244   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
148245     rc = fts3DoAutoincrmerge(p, &zVal[10]);
148246 #ifdef SQLITE_TEST
148247   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
148248     p->nNodeSize = atoi(&zVal[9]);
148249     rc = SQLITE_OK;
148250   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
148251     p->nMaxPendingData = atoi(&zVal[11]);
148252     rc = SQLITE_OK;
148253   }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
148254     p->bNoIncrDoclist = atoi(&zVal[21]);
148255     rc = SQLITE_OK;
148256 #endif
148257   }else{
148258     rc = SQLITE_ERROR;
148259   }
148260 
148261   return rc;
148262 }
148263 
148264 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
148265 /*
148266 ** Delete all cached deferred doclists. Deferred doclists are cached
148267 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
148268 */
148269 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
148270   Fts3DeferredToken *pDef;
148271   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
148272     fts3PendingListDelete(pDef->pList);
148273     pDef->pList = 0;
148274   }
148275 }
148276 
148277 /*
148278 ** Free all entries in the pCsr->pDeffered list. Entries are added to
148279 ** this list using sqlite3Fts3DeferToken().
148280 */
148281 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
148282   Fts3DeferredToken *pDef;
148283   Fts3DeferredToken *pNext;
148284   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
148285     pNext = pDef->pNext;
148286     fts3PendingListDelete(pDef->pList);
148287     sqlite3_free(pDef);
148288   }
148289   pCsr->pDeferred = 0;
148290 }
148291 
148292 /*
148293 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
148294 ** based on the row that pCsr currently points to.
148295 **
148296 ** A deferred-doclist is like any other doclist with position information
148297 ** included, except that it only contains entries for a single row of the
148298 ** table, not for all rows.
148299 */
148300 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
148301   int rc = SQLITE_OK;             /* Return code */
148302   if( pCsr->pDeferred ){
148303     int i;                        /* Used to iterate through table columns */
148304     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
148305     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
148306 
148307     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
148308     sqlite3_tokenizer *pT = p->pTokenizer;
148309     sqlite3_tokenizer_module const *pModule = pT->pModule;
148310 
148311     assert( pCsr->isRequireSeek==0 );
148312     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
148313 
148314     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
148315       if( p->abNotindexed[i]==0 ){
148316         const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
148317         sqlite3_tokenizer_cursor *pTC = 0;
148318 
148319         rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
148320         while( rc==SQLITE_OK ){
148321           char const *zToken;       /* Buffer containing token */
148322           int nToken = 0;           /* Number of bytes in token */
148323           int iDum1 = 0, iDum2 = 0; /* Dummy variables */
148324           int iPos = 0;             /* Position of token in zText */
148325 
148326           rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
148327           for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
148328             Fts3PhraseToken *pPT = pDef->pToken;
148329             if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
148330                 && (pPT->bFirst==0 || iPos==0)
148331                 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
148332                 && (0==memcmp(zToken, pPT->z, pPT->n))
148333               ){
148334               fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
148335             }
148336           }
148337         }
148338         if( pTC ) pModule->xClose(pTC);
148339         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
148340       }
148341     }
148342 
148343     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
148344       if( pDef->pList ){
148345         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
148346       }
148347     }
148348   }
148349 
148350   return rc;
148351 }
148352 
148353 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
148354   Fts3DeferredToken *p,
148355   char **ppData,
148356   int *pnData
148357 ){
148358   char *pRet;
148359   int nSkip;
148360   sqlite3_int64 dummy;
148361 
148362   *ppData = 0;
148363   *pnData = 0;
148364 
148365   if( p->pList==0 ){
148366     return SQLITE_OK;
148367   }
148368 
148369   pRet = (char *)sqlite3_malloc(p->pList->nData);
148370   if( !pRet ) return SQLITE_NOMEM;
148371 
148372   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
148373   *pnData = p->pList->nData - nSkip;
148374   *ppData = pRet;
148375 
148376   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
148377   return SQLITE_OK;
148378 }
148379 
148380 /*
148381 ** Add an entry for token pToken to the pCsr->pDeferred list.
148382 */
148383 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
148384   Fts3Cursor *pCsr,               /* Fts3 table cursor */
148385   Fts3PhraseToken *pToken,        /* Token to defer */
148386   int iCol                        /* Column that token must appear in (or -1) */
148387 ){
148388   Fts3DeferredToken *pDeferred;
148389   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
148390   if( !pDeferred ){
148391     return SQLITE_NOMEM;
148392   }
148393   memset(pDeferred, 0, sizeof(*pDeferred));
148394   pDeferred->pToken = pToken;
148395   pDeferred->pNext = pCsr->pDeferred;
148396   pDeferred->iCol = iCol;
148397   pCsr->pDeferred = pDeferred;
148398 
148399   assert( pToken->pDeferred==0 );
148400   pToken->pDeferred = pDeferred;
148401 
148402   return SQLITE_OK;
148403 }
148404 #endif
148405 
148406 /*
148407 ** SQLite value pRowid contains the rowid of a row that may or may not be
148408 ** present in the FTS3 table. If it is, delete it and adjust the contents
148409 ** of subsiduary data structures accordingly.
148410 */
148411 static int fts3DeleteByRowid(
148412   Fts3Table *p,
148413   sqlite3_value *pRowid,
148414   int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
148415   u32 *aSzDel
148416 ){
148417   int rc = SQLITE_OK;             /* Return code */
148418   int bFound = 0;                 /* True if *pRowid really is in the table */
148419 
148420   fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
148421   if( bFound && rc==SQLITE_OK ){
148422     int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
148423     rc = fts3IsEmpty(p, pRowid, &isEmpty);
148424     if( rc==SQLITE_OK ){
148425       if( isEmpty ){
148426         /* Deleting this row means the whole table is empty. In this case
148427         ** delete the contents of all three tables and throw away any
148428         ** data in the pendingTerms hash table.  */
148429         rc = fts3DeleteAll(p, 1);
148430         *pnChng = 0;
148431         memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
148432       }else{
148433         *pnChng = *pnChng - 1;
148434         if( p->zContentTbl==0 ){
148435           fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
148436         }
148437         if( p->bHasDocsize ){
148438           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
148439         }
148440       }
148441     }
148442   }
148443 
148444   return rc;
148445 }
148446 
148447 /*
148448 ** This function does the work for the xUpdate method of FTS3 virtual
148449 ** tables. The schema of the virtual table being:
148450 **
148451 **     CREATE TABLE <table name>(
148452 **       <user columns>,
148453 **       <table name> HIDDEN,
148454 **       docid HIDDEN,
148455 **       <langid> HIDDEN
148456 **     );
148457 **
148458 **
148459 */
148460 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
148461   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
148462   int nArg,                       /* Size of argument array */
148463   sqlite3_value **apVal,          /* Array of arguments */
148464   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
148465 ){
148466   Fts3Table *p = (Fts3Table *)pVtab;
148467   int rc = SQLITE_OK;             /* Return Code */
148468   int isRemove = 0;               /* True for an UPDATE or DELETE */
148469   u32 *aSzIns = 0;                /* Sizes of inserted documents */
148470   u32 *aSzDel = 0;                /* Sizes of deleted documents */
148471   int nChng = 0;                  /* Net change in number of documents */
148472   int bInsertDone = 0;
148473 
148474   /* At this point it must be known if the %_stat table exists or not.
148475   ** So bHasStat may not be 2.  */
148476   assert( p->bHasStat==0 || p->bHasStat==1 );
148477 
148478   assert( p->pSegments==0 );
148479   assert(
148480       nArg==1                     /* DELETE operations */
148481    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
148482   );
148483 
148484   /* Check for a "special" INSERT operation. One of the form:
148485   **
148486   **   INSERT INTO xyz(xyz) VALUES('command');
148487   */
148488   if( nArg>1
148489    && sqlite3_value_type(apVal[0])==SQLITE_NULL
148490    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
148491   ){
148492     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
148493     goto update_out;
148494   }
148495 
148496   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
148497     rc = SQLITE_CONSTRAINT;
148498     goto update_out;
148499   }
148500 
148501   /* Allocate space to hold the change in document sizes */
148502   aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
148503   if( aSzDel==0 ){
148504     rc = SQLITE_NOMEM;
148505     goto update_out;
148506   }
148507   aSzIns = &aSzDel[p->nColumn+1];
148508   memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
148509 
148510   rc = fts3Writelock(p);
148511   if( rc!=SQLITE_OK ) goto update_out;
148512 
148513   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
148514   ** value, then this operation requires constraint handling.
148515   **
148516   ** If the on-conflict mode is REPLACE, this means that the existing row
148517   ** should be deleted from the database before inserting the new row. Or,
148518   ** if the on-conflict mode is other than REPLACE, then this method must
148519   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
148520   ** modify the database file.
148521   */
148522   if( nArg>1 && p->zContentTbl==0 ){
148523     /* Find the value object that holds the new rowid value. */
148524     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
148525     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
148526       pNewRowid = apVal[1];
148527     }
148528 
148529     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
148530         sqlite3_value_type(apVal[0])==SQLITE_NULL
148531      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
148532     )){
148533       /* The new rowid is not NULL (in this case the rowid will be
148534       ** automatically assigned and there is no chance of a conflict), and
148535       ** the statement is either an INSERT or an UPDATE that modifies the
148536       ** rowid column. So if the conflict mode is REPLACE, then delete any
148537       ** existing row with rowid=pNewRowid.
148538       **
148539       ** Or, if the conflict mode is not REPLACE, insert the new record into
148540       ** the %_content table. If we hit the duplicate rowid constraint (or any
148541       ** other error) while doing so, return immediately.
148542       **
148543       ** This branch may also run if pNewRowid contains a value that cannot
148544       ** be losslessly converted to an integer. In this case, the eventual
148545       ** call to fts3InsertData() (either just below or further on in this
148546       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
148547       ** invoked, it will delete zero rows (since no row will have
148548       ** docid=$pNewRowid if $pNewRowid is not an integer value).
148549       */
148550       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
148551         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
148552       }else{
148553         rc = fts3InsertData(p, apVal, pRowid);
148554         bInsertDone = 1;
148555       }
148556     }
148557   }
148558   if( rc!=SQLITE_OK ){
148559     goto update_out;
148560   }
148561 
148562   /* If this is a DELETE or UPDATE operation, remove the old record. */
148563   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
148564     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
148565     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
148566     isRemove = 1;
148567   }
148568 
148569   /* If this is an INSERT or UPDATE operation, insert the new record. */
148570   if( nArg>1 && rc==SQLITE_OK ){
148571     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
148572     if( bInsertDone==0 ){
148573       rc = fts3InsertData(p, apVal, pRowid);
148574       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
148575         rc = FTS_CORRUPT_VTAB;
148576       }
148577     }
148578     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
148579       rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
148580     }
148581     if( rc==SQLITE_OK ){
148582       assert( p->iPrevDocid==*pRowid );
148583       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
148584     }
148585     if( p->bHasDocsize ){
148586       fts3InsertDocsize(&rc, p, aSzIns);
148587     }
148588     nChng++;
148589   }
148590 
148591   if( p->bFts4 ){
148592     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
148593   }
148594 
148595  update_out:
148596   sqlite3_free(aSzDel);
148597   sqlite3Fts3SegmentsClose(p);
148598   return rc;
148599 }
148600 
148601 /*
148602 ** Flush any data in the pending-terms hash table to disk. If successful,
148603 ** merge all segments in the database (including the new segment, if
148604 ** there was any data to flush) into a single segment.
148605 */
148606 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
148607   int rc;
148608   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
148609   if( rc==SQLITE_OK ){
148610     rc = fts3DoOptimize(p, 1);
148611     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
148612       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
148613       if( rc2!=SQLITE_OK ) rc = rc2;
148614     }else{
148615       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
148616       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
148617     }
148618   }
148619   sqlite3Fts3SegmentsClose(p);
148620   return rc;
148621 }
148622 
148623 #endif
148624 
148625 /************** End of fts3_write.c ******************************************/
148626 /************** Begin file fts3_snippet.c ************************************/
148627 /*
148628 ** 2009 Oct 23
148629 **
148630 ** The author disclaims copyright to this source code.  In place of
148631 ** a legal notice, here is a blessing:
148632 **
148633 **    May you do good and not evil.
148634 **    May you find forgiveness for yourself and forgive others.
148635 **    May you share freely, never taking more than you give.
148636 **
148637 ******************************************************************************
148638 */
148639 
148640 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
148641 
148642 /* #include <string.h> */
148643 /* #include <assert.h> */
148644 
148645 /*
148646 ** Characters that may appear in the second argument to matchinfo().
148647 */
148648 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
148649 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
148650 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
148651 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
148652 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
148653 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
148654 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
148655 #define FTS3_MATCHINFO_LHITS     'y'        /* nCol*nPhrase values */
148656 
148657 /*
148658 ** The default value for the second argument to matchinfo().
148659 */
148660 #define FTS3_MATCHINFO_DEFAULT   "pcx"
148661 
148662 
148663 /*
148664 ** Used as an fts3ExprIterate() context when loading phrase doclists to
148665 ** Fts3Expr.aDoclist[]/nDoclist.
148666 */
148667 typedef struct LoadDoclistCtx LoadDoclistCtx;
148668 struct LoadDoclistCtx {
148669   Fts3Cursor *pCsr;               /* FTS3 Cursor */
148670   int nPhrase;                    /* Number of phrases seen so far */
148671   int nToken;                     /* Number of tokens seen so far */
148672 };
148673 
148674 /*
148675 ** The following types are used as part of the implementation of the
148676 ** fts3BestSnippet() routine.
148677 */
148678 typedef struct SnippetIter SnippetIter;
148679 typedef struct SnippetPhrase SnippetPhrase;
148680 typedef struct SnippetFragment SnippetFragment;
148681 
148682 struct SnippetIter {
148683   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
148684   int iCol;                       /* Extract snippet from this column */
148685   int nSnippet;                   /* Requested snippet length (in tokens) */
148686   int nPhrase;                    /* Number of phrases in query */
148687   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
148688   int iCurrent;                   /* First token of current snippet */
148689 };
148690 
148691 struct SnippetPhrase {
148692   int nToken;                     /* Number of tokens in phrase */
148693   char *pList;                    /* Pointer to start of phrase position list */
148694   int iHead;                      /* Next value in position list */
148695   char *pHead;                    /* Position list data following iHead */
148696   int iTail;                      /* Next value in trailing position list */
148697   char *pTail;                    /* Position list data following iTail */
148698 };
148699 
148700 struct SnippetFragment {
148701   int iCol;                       /* Column snippet is extracted from */
148702   int iPos;                       /* Index of first token in snippet */
148703   u64 covered;                    /* Mask of query phrases covered */
148704   u64 hlmask;                     /* Mask of snippet terms to highlight */
148705 };
148706 
148707 /*
148708 ** This type is used as an fts3ExprIterate() context object while
148709 ** accumulating the data returned by the matchinfo() function.
148710 */
148711 typedef struct MatchInfo MatchInfo;
148712 struct MatchInfo {
148713   Fts3Cursor *pCursor;            /* FTS3 Cursor */
148714   int nCol;                       /* Number of columns in table */
148715   int nPhrase;                    /* Number of matchable phrases in query */
148716   sqlite3_int64 nDoc;             /* Number of docs in database */
148717   u32 *aMatchinfo;                /* Pre-allocated buffer */
148718 };
148719 
148720 
148721 
148722 /*
148723 ** The snippet() and offsets() functions both return text values. An instance
148724 ** of the following structure is used to accumulate those values while the
148725 ** functions are running. See fts3StringAppend() for details.
148726 */
148727 typedef struct StrBuffer StrBuffer;
148728 struct StrBuffer {
148729   char *z;                        /* Pointer to buffer containing string */
148730   int n;                          /* Length of z in bytes (excl. nul-term) */
148731   int nAlloc;                     /* Allocated size of buffer z in bytes */
148732 };
148733 
148734 
148735 /*
148736 ** This function is used to help iterate through a position-list. A position
148737 ** list is a list of unique integers, sorted from smallest to largest. Each
148738 ** element of the list is represented by an FTS3 varint that takes the value
148739 ** of the difference between the current element and the previous one plus
148740 ** two. For example, to store the position-list:
148741 **
148742 **     4 9 113
148743 **
148744 ** the three varints:
148745 **
148746 **     6 7 106
148747 **
148748 ** are encoded.
148749 **
148750 ** When this function is called, *pp points to the start of an element of
148751 ** the list. *piPos contains the value of the previous entry in the list.
148752 ** After it returns, *piPos contains the value of the next element of the
148753 ** list and *pp is advanced to the following varint.
148754 */
148755 static void fts3GetDeltaPosition(char **pp, int *piPos){
148756   int iVal;
148757   *pp += fts3GetVarint32(*pp, &iVal);
148758   *piPos += (iVal-2);
148759 }
148760 
148761 /*
148762 ** Helper function for fts3ExprIterate() (see below).
148763 */
148764 static int fts3ExprIterate2(
148765   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
148766   int *piPhrase,                  /* Pointer to phrase counter */
148767   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
148768   void *pCtx                      /* Second argument to pass to callback */
148769 ){
148770   int rc;                         /* Return code */
148771   int eType = pExpr->eType;       /* Type of expression node pExpr */
148772 
148773   if( eType!=FTSQUERY_PHRASE ){
148774     assert( pExpr->pLeft && pExpr->pRight );
148775     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
148776     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
148777       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
148778     }
148779   }else{
148780     rc = x(pExpr, *piPhrase, pCtx);
148781     (*piPhrase)++;
148782   }
148783   return rc;
148784 }
148785 
148786 /*
148787 ** Iterate through all phrase nodes in an FTS3 query, except those that
148788 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
148789 ** For each phrase node found, the supplied callback function is invoked.
148790 **
148791 ** If the callback function returns anything other than SQLITE_OK,
148792 ** the iteration is abandoned and the error code returned immediately.
148793 ** Otherwise, SQLITE_OK is returned after a callback has been made for
148794 ** all eligible phrase nodes.
148795 */
148796 static int fts3ExprIterate(
148797   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
148798   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
148799   void *pCtx                      /* Second argument to pass to callback */
148800 ){
148801   int iPhrase = 0;                /* Variable used as the phrase counter */
148802   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
148803 }
148804 
148805 /*
148806 ** This is an fts3ExprIterate() callback used while loading the doclists
148807 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
148808 ** fts3ExprLoadDoclists().
148809 */
148810 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
148811   int rc = SQLITE_OK;
148812   Fts3Phrase *pPhrase = pExpr->pPhrase;
148813   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
148814 
148815   UNUSED_PARAMETER(iPhrase);
148816 
148817   p->nPhrase++;
148818   p->nToken += pPhrase->nToken;
148819 
148820   return rc;
148821 }
148822 
148823 /*
148824 ** Load the doclists for each phrase in the query associated with FTS3 cursor
148825 ** pCsr.
148826 **
148827 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
148828 ** phrases in the expression (all phrases except those directly or
148829 ** indirectly descended from the right-hand-side of a NOT operator). If
148830 ** pnToken is not NULL, then it is set to the number of tokens in all
148831 ** matchable phrases of the expression.
148832 */
148833 static int fts3ExprLoadDoclists(
148834   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
148835   int *pnPhrase,                  /* OUT: Number of phrases in query */
148836   int *pnToken                    /* OUT: Number of tokens in query */
148837 ){
148838   int rc;                         /* Return Code */
148839   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
148840   sCtx.pCsr = pCsr;
148841   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
148842   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
148843   if( pnToken ) *pnToken = sCtx.nToken;
148844   return rc;
148845 }
148846 
148847 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
148848   (*(int *)ctx)++;
148849   UNUSED_PARAMETER(pExpr);
148850   UNUSED_PARAMETER(iPhrase);
148851   return SQLITE_OK;
148852 }
148853 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
148854   int nPhrase = 0;
148855   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
148856   return nPhrase;
148857 }
148858 
148859 /*
148860 ** Advance the position list iterator specified by the first two
148861 ** arguments so that it points to the first element with a value greater
148862 ** than or equal to parameter iNext.
148863 */
148864 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
148865   char *pIter = *ppIter;
148866   if( pIter ){
148867     int iIter = *piIter;
148868 
148869     while( iIter<iNext ){
148870       if( 0==(*pIter & 0xFE) ){
148871         iIter = -1;
148872         pIter = 0;
148873         break;
148874       }
148875       fts3GetDeltaPosition(&pIter, &iIter);
148876     }
148877 
148878     *piIter = iIter;
148879     *ppIter = pIter;
148880   }
148881 }
148882 
148883 /*
148884 ** Advance the snippet iterator to the next candidate snippet.
148885 */
148886 static int fts3SnippetNextCandidate(SnippetIter *pIter){
148887   int i;                          /* Loop counter */
148888 
148889   if( pIter->iCurrent<0 ){
148890     /* The SnippetIter object has just been initialized. The first snippet
148891     ** candidate always starts at offset 0 (even if this candidate has a
148892     ** score of 0.0).
148893     */
148894     pIter->iCurrent = 0;
148895 
148896     /* Advance the 'head' iterator of each phrase to the first offset that
148897     ** is greater than or equal to (iNext+nSnippet).
148898     */
148899     for(i=0; i<pIter->nPhrase; i++){
148900       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
148901       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
148902     }
148903   }else{
148904     int iStart;
148905     int iEnd = 0x7FFFFFFF;
148906 
148907     for(i=0; i<pIter->nPhrase; i++){
148908       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
148909       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
148910         iEnd = pPhrase->iHead;
148911       }
148912     }
148913     if( iEnd==0x7FFFFFFF ){
148914       return 1;
148915     }
148916 
148917     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
148918     for(i=0; i<pIter->nPhrase; i++){
148919       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
148920       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
148921       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
148922     }
148923   }
148924 
148925   return 0;
148926 }
148927 
148928 /*
148929 ** Retrieve information about the current candidate snippet of snippet
148930 ** iterator pIter.
148931 */
148932 static void fts3SnippetDetails(
148933   SnippetIter *pIter,             /* Snippet iterator */
148934   u64 mCovered,                   /* Bitmask of phrases already covered */
148935   int *piToken,                   /* OUT: First token of proposed snippet */
148936   int *piScore,                   /* OUT: "Score" for this snippet */
148937   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
148938   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
148939 ){
148940   int iStart = pIter->iCurrent;   /* First token of snippet */
148941   int iScore = 0;                 /* Score of this snippet */
148942   int i;                          /* Loop counter */
148943   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
148944   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
148945 
148946   for(i=0; i<pIter->nPhrase; i++){
148947     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
148948     if( pPhrase->pTail ){
148949       char *pCsr = pPhrase->pTail;
148950       int iCsr = pPhrase->iTail;
148951 
148952       while( iCsr<(iStart+pIter->nSnippet) ){
148953         int j;
148954         u64 mPhrase = (u64)1 << i;
148955         u64 mPos = (u64)1 << (iCsr - iStart);
148956         assert( iCsr>=iStart );
148957         if( (mCover|mCovered)&mPhrase ){
148958           iScore++;
148959         }else{
148960           iScore += 1000;
148961         }
148962         mCover |= mPhrase;
148963 
148964         for(j=0; j<pPhrase->nToken; j++){
148965           mHighlight |= (mPos>>j);
148966         }
148967 
148968         if( 0==(*pCsr & 0x0FE) ) break;
148969         fts3GetDeltaPosition(&pCsr, &iCsr);
148970       }
148971     }
148972   }
148973 
148974   /* Set the output variables before returning. */
148975   *piToken = iStart;
148976   *piScore = iScore;
148977   *pmCover = mCover;
148978   *pmHighlight = mHighlight;
148979 }
148980 
148981 /*
148982 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
148983 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
148984 */
148985 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
148986   SnippetIter *p = (SnippetIter *)ctx;
148987   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
148988   char *pCsr;
148989   int rc;
148990 
148991   pPhrase->nToken = pExpr->pPhrase->nToken;
148992   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
148993   assert( rc==SQLITE_OK || pCsr==0 );
148994   if( pCsr ){
148995     int iFirst = 0;
148996     pPhrase->pList = pCsr;
148997     fts3GetDeltaPosition(&pCsr, &iFirst);
148998     assert( iFirst>=0 );
148999     pPhrase->pHead = pCsr;
149000     pPhrase->pTail = pCsr;
149001     pPhrase->iHead = iFirst;
149002     pPhrase->iTail = iFirst;
149003   }else{
149004     assert( rc!=SQLITE_OK || (
149005        pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
149006     ));
149007   }
149008 
149009   return rc;
149010 }
149011 
149012 /*
149013 ** Select the fragment of text consisting of nFragment contiguous tokens
149014 ** from column iCol that represent the "best" snippet. The best snippet
149015 ** is the snippet with the highest score, where scores are calculated
149016 ** by adding:
149017 **
149018 **   (a) +1 point for each occurrence of a matchable phrase in the snippet.
149019 **
149020 **   (b) +1000 points for the first occurrence of each matchable phrase in
149021 **       the snippet for which the corresponding mCovered bit is not set.
149022 **
149023 ** The selected snippet parameters are stored in structure *pFragment before
149024 ** returning. The score of the selected snippet is stored in *piScore
149025 ** before returning.
149026 */
149027 static int fts3BestSnippet(
149028   int nSnippet,                   /* Desired snippet length */
149029   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
149030   int iCol,                       /* Index of column to create snippet from */
149031   u64 mCovered,                   /* Mask of phrases already covered */
149032   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
149033   SnippetFragment *pFragment,     /* OUT: Best snippet found */
149034   int *piScore                    /* OUT: Score of snippet pFragment */
149035 ){
149036   int rc;                         /* Return Code */
149037   int nList;                      /* Number of phrases in expression */
149038   SnippetIter sIter;              /* Iterates through snippet candidates */
149039   int nByte;                      /* Number of bytes of space to allocate */
149040   int iBestScore = -1;            /* Best snippet score found so far */
149041   int i;                          /* Loop counter */
149042 
149043   memset(&sIter, 0, sizeof(sIter));
149044 
149045   /* Iterate through the phrases in the expression to count them. The same
149046   ** callback makes sure the doclists are loaded for each phrase.
149047   */
149048   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
149049   if( rc!=SQLITE_OK ){
149050     return rc;
149051   }
149052 
149053   /* Now that it is known how many phrases there are, allocate and zero
149054   ** the required space using malloc().
149055   */
149056   nByte = sizeof(SnippetPhrase) * nList;
149057   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
149058   if( !sIter.aPhrase ){
149059     return SQLITE_NOMEM;
149060   }
149061   memset(sIter.aPhrase, 0, nByte);
149062 
149063   /* Initialize the contents of the SnippetIter object. Then iterate through
149064   ** the set of phrases in the expression to populate the aPhrase[] array.
149065   */
149066   sIter.pCsr = pCsr;
149067   sIter.iCol = iCol;
149068   sIter.nSnippet = nSnippet;
149069   sIter.nPhrase = nList;
149070   sIter.iCurrent = -1;
149071   rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
149072   if( rc==SQLITE_OK ){
149073 
149074     /* Set the *pmSeen output variable. */
149075     for(i=0; i<nList; i++){
149076       if( sIter.aPhrase[i].pHead ){
149077         *pmSeen |= (u64)1 << i;
149078       }
149079     }
149080 
149081     /* Loop through all candidate snippets. Store the best snippet in
149082      ** *pFragment. Store its associated 'score' in iBestScore.
149083      */
149084     pFragment->iCol = iCol;
149085     while( !fts3SnippetNextCandidate(&sIter) ){
149086       int iPos;
149087       int iScore;
149088       u64 mCover;
149089       u64 mHighlite;
149090       fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
149091       assert( iScore>=0 );
149092       if( iScore>iBestScore ){
149093         pFragment->iPos = iPos;
149094         pFragment->hlmask = mHighlite;
149095         pFragment->covered = mCover;
149096         iBestScore = iScore;
149097       }
149098     }
149099 
149100     *piScore = iBestScore;
149101   }
149102   sqlite3_free(sIter.aPhrase);
149103   return rc;
149104 }
149105 
149106 
149107 /*
149108 ** Append a string to the string-buffer passed as the first argument.
149109 **
149110 ** If nAppend is negative, then the length of the string zAppend is
149111 ** determined using strlen().
149112 */
149113 static int fts3StringAppend(
149114   StrBuffer *pStr,                /* Buffer to append to */
149115   const char *zAppend,            /* Pointer to data to append to buffer */
149116   int nAppend                     /* Size of zAppend in bytes (or -1) */
149117 ){
149118   if( nAppend<0 ){
149119     nAppend = (int)strlen(zAppend);
149120   }
149121 
149122   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
149123   ** to grow the buffer until so that it is big enough to accomadate the
149124   ** appended data.
149125   */
149126   if( pStr->n+nAppend+1>=pStr->nAlloc ){
149127     int nAlloc = pStr->nAlloc+nAppend+100;
149128     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
149129     if( !zNew ){
149130       return SQLITE_NOMEM;
149131     }
149132     pStr->z = zNew;
149133     pStr->nAlloc = nAlloc;
149134   }
149135   assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
149136 
149137   /* Append the data to the string buffer. */
149138   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
149139   pStr->n += nAppend;
149140   pStr->z[pStr->n] = '\0';
149141 
149142   return SQLITE_OK;
149143 }
149144 
149145 /*
149146 ** The fts3BestSnippet() function often selects snippets that end with a
149147 ** query term. That is, the final term of the snippet is always a term
149148 ** that requires highlighting. For example, if 'X' is a highlighted term
149149 ** and '.' is a non-highlighted term, BestSnippet() may select:
149150 **
149151 **     ........X.....X
149152 **
149153 ** This function "shifts" the beginning of the snippet forward in the
149154 ** document so that there are approximately the same number of
149155 ** non-highlighted terms to the right of the final highlighted term as there
149156 ** are to the left of the first highlighted term. For example, to this:
149157 **
149158 **     ....X.....X....
149159 **
149160 ** This is done as part of extracting the snippet text, not when selecting
149161 ** the snippet. Snippet selection is done based on doclists only, so there
149162 ** is no way for fts3BestSnippet() to know whether or not the document
149163 ** actually contains terms that follow the final highlighted term.
149164 */
149165 static int fts3SnippetShift(
149166   Fts3Table *pTab,                /* FTS3 table snippet comes from */
149167   int iLangid,                    /* Language id to use in tokenizing */
149168   int nSnippet,                   /* Number of tokens desired for snippet */
149169   const char *zDoc,               /* Document text to extract snippet from */
149170   int nDoc,                       /* Size of buffer zDoc in bytes */
149171   int *piPos,                     /* IN/OUT: First token of snippet */
149172   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
149173 ){
149174   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
149175 
149176   if( hlmask ){
149177     int nLeft;                    /* Tokens to the left of first highlight */
149178     int nRight;                   /* Tokens to the right of last highlight */
149179     int nDesired;                 /* Ideal number of tokens to shift forward */
149180 
149181     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
149182     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
149183     nDesired = (nLeft-nRight)/2;
149184 
149185     /* Ideally, the start of the snippet should be pushed forward in the
149186     ** document nDesired tokens. This block checks if there are actually
149187     ** nDesired tokens to the right of the snippet. If so, *piPos and
149188     ** *pHlMask are updated to shift the snippet nDesired tokens to the
149189     ** right. Otherwise, the snippet is shifted by the number of tokens
149190     ** available.
149191     */
149192     if( nDesired>0 ){
149193       int nShift;                 /* Number of tokens to shift snippet by */
149194       int iCurrent = 0;           /* Token counter */
149195       int rc;                     /* Return Code */
149196       sqlite3_tokenizer_module *pMod;
149197       sqlite3_tokenizer_cursor *pC;
149198       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
149199 
149200       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
149201       ** or more tokens in zDoc/nDoc.
149202       */
149203       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
149204       if( rc!=SQLITE_OK ){
149205         return rc;
149206       }
149207       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
149208         const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
149209         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
149210       }
149211       pMod->xClose(pC);
149212       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
149213 
149214       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
149215       assert( nShift<=nDesired );
149216       if( nShift>0 ){
149217         *piPos += nShift;
149218         *pHlmask = hlmask >> nShift;
149219       }
149220     }
149221   }
149222   return SQLITE_OK;
149223 }
149224 
149225 /*
149226 ** Extract the snippet text for fragment pFragment from cursor pCsr and
149227 ** append it to string buffer pOut.
149228 */
149229 static int fts3SnippetText(
149230   Fts3Cursor *pCsr,               /* FTS3 Cursor */
149231   SnippetFragment *pFragment,     /* Snippet to extract */
149232   int iFragment,                  /* Fragment number */
149233   int isLast,                     /* True for final fragment in snippet */
149234   int nSnippet,                   /* Number of tokens in extracted snippet */
149235   const char *zOpen,              /* String inserted before highlighted term */
149236   const char *zClose,             /* String inserted after highlighted term */
149237   const char *zEllipsis,          /* String inserted between snippets */
149238   StrBuffer *pOut                 /* Write output here */
149239 ){
149240   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
149241   int rc;                         /* Return code */
149242   const char *zDoc;               /* Document text to extract snippet from */
149243   int nDoc;                       /* Size of zDoc in bytes */
149244   int iCurrent = 0;               /* Current token number of document */
149245   int iEnd = 0;                   /* Byte offset of end of current token */
149246   int isShiftDone = 0;            /* True after snippet is shifted */
149247   int iPos = pFragment->iPos;     /* First token of snippet */
149248   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
149249   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
149250   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
149251   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
149252 
149253   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
149254   if( zDoc==0 ){
149255     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
149256       return SQLITE_NOMEM;
149257     }
149258     return SQLITE_OK;
149259   }
149260   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
149261 
149262   /* Open a token cursor on the document. */
149263   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
149264   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
149265   if( rc!=SQLITE_OK ){
149266     return rc;
149267   }
149268 
149269   while( rc==SQLITE_OK ){
149270     const char *ZDUMMY;           /* Dummy argument used with tokenizer */
149271     int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
149272     int iBegin = 0;               /* Offset in zDoc of start of token */
149273     int iFin = 0;                 /* Offset in zDoc of end of token */
149274     int isHighlight = 0;          /* True for highlighted terms */
149275 
149276     /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
149277     ** in the FTS code the variable that the third argument to xNext points to
149278     ** is initialized to zero before the first (*but not necessarily
149279     ** subsequent*) call to xNext(). This is done for a particular application
149280     ** that needs to know whether or not the tokenizer is being used for
149281     ** snippet generation or for some other purpose.
149282     **
149283     ** Extreme care is required when writing code to depend on this
149284     ** initialization. It is not a documented part of the tokenizer interface.
149285     ** If a tokenizer is used directly by any code outside of FTS, this
149286     ** convention might not be respected.  */
149287     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
149288     if( rc!=SQLITE_OK ){
149289       if( rc==SQLITE_DONE ){
149290         /* Special case - the last token of the snippet is also the last token
149291         ** of the column. Append any punctuation that occurred between the end
149292         ** of the previous token and the end of the document to the output.
149293         ** Then break out of the loop. */
149294         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
149295       }
149296       break;
149297     }
149298     if( iCurrent<iPos ){ continue; }
149299 
149300     if( !isShiftDone ){
149301       int n = nDoc - iBegin;
149302       rc = fts3SnippetShift(
149303           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
149304       );
149305       isShiftDone = 1;
149306 
149307       /* Now that the shift has been done, check if the initial "..." are
149308       ** required. They are required if (a) this is not the first fragment,
149309       ** or (b) this fragment does not begin at position 0 of its column.
149310       */
149311       if( rc==SQLITE_OK ){
149312         if( iPos>0 || iFragment>0 ){
149313           rc = fts3StringAppend(pOut, zEllipsis, -1);
149314         }else if( iBegin ){
149315           rc = fts3StringAppend(pOut, zDoc, iBegin);
149316         }
149317       }
149318       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
149319     }
149320 
149321     if( iCurrent>=(iPos+nSnippet) ){
149322       if( isLast ){
149323         rc = fts3StringAppend(pOut, zEllipsis, -1);
149324       }
149325       break;
149326     }
149327 
149328     /* Set isHighlight to true if this term should be highlighted. */
149329     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
149330 
149331     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
149332     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
149333     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
149334     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
149335 
149336     iEnd = iFin;
149337   }
149338 
149339   pMod->xClose(pC);
149340   return rc;
149341 }
149342 
149343 
149344 /*
149345 ** This function is used to count the entries in a column-list (a
149346 ** delta-encoded list of term offsets within a single column of a single
149347 ** row). When this function is called, *ppCollist should point to the
149348 ** beginning of the first varint in the column-list (the varint that
149349 ** contains the position of the first matching term in the column data).
149350 ** Before returning, *ppCollist is set to point to the first byte after
149351 ** the last varint in the column-list (either the 0x00 signifying the end
149352 ** of the position-list, or the 0x01 that precedes the column number of
149353 ** the next column in the position-list).
149354 **
149355 ** The number of elements in the column-list is returned.
149356 */
149357 static int fts3ColumnlistCount(char **ppCollist){
149358   char *pEnd = *ppCollist;
149359   char c = 0;
149360   int nEntry = 0;
149361 
149362   /* A column-list is terminated by either a 0x01 or 0x00. */
149363   while( 0xFE & (*pEnd | c) ){
149364     c = *pEnd++ & 0x80;
149365     if( !c ) nEntry++;
149366   }
149367 
149368   *ppCollist = pEnd;
149369   return nEntry;
149370 }
149371 
149372 /*
149373 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
149374 ** for a single query.
149375 **
149376 ** fts3ExprIterate() callback to load the 'global' elements of a
149377 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
149378 ** of the matchinfo array that are constant for all rows returned by the
149379 ** current query.
149380 **
149381 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
149382 ** function populates Matchinfo.aMatchinfo[] as follows:
149383 **
149384 **   for(iCol=0; iCol<nCol; iCol++){
149385 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
149386 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
149387 **   }
149388 **
149389 ** where X is the number of matches for phrase iPhrase is column iCol of all
149390 ** rows of the table. Y is the number of rows for which column iCol contains
149391 ** at least one instance of phrase iPhrase.
149392 **
149393 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
149394 ** Y values are set to nDoc, where nDoc is the number of documents in the
149395 ** file system. This is done because the full-text index doclist is required
149396 ** to calculate these values properly, and the full-text index doclist is
149397 ** not available for deferred tokens.
149398 */
149399 static int fts3ExprGlobalHitsCb(
149400   Fts3Expr *pExpr,                /* Phrase expression node */
149401   int iPhrase,                    /* Phrase number (numbered from zero) */
149402   void *pCtx                      /* Pointer to MatchInfo structure */
149403 ){
149404   MatchInfo *p = (MatchInfo *)pCtx;
149405   return sqlite3Fts3EvalPhraseStats(
149406       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
149407   );
149408 }
149409 
149410 /*
149411 ** fts3ExprIterate() callback used to collect the "local" part of the
149412 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
149413 ** array that are different for each row returned by the query.
149414 */
149415 static int fts3ExprLocalHitsCb(
149416   Fts3Expr *pExpr,                /* Phrase expression node */
149417   int iPhrase,                    /* Phrase number */
149418   void *pCtx                      /* Pointer to MatchInfo structure */
149419 ){
149420   int rc = SQLITE_OK;
149421   MatchInfo *p = (MatchInfo *)pCtx;
149422   int iStart = iPhrase * p->nCol * 3;
149423   int i;
149424 
149425   for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
149426     char *pCsr;
149427     rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
149428     if( pCsr ){
149429       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
149430     }else{
149431       p->aMatchinfo[iStart+i*3] = 0;
149432     }
149433   }
149434 
149435   return rc;
149436 }
149437 
149438 /*
149439 ** fts3ExprIterate() callback used to gather information for the matchinfo
149440 ** directive 'y'.
149441 */
149442 static int fts3ExprLHitsCb(
149443   Fts3Expr *pExpr,                /* Phrase expression node */
149444   int iPhrase,                    /* Phrase number */
149445   void *pCtx                      /* Pointer to MatchInfo structure */
149446 ){
149447   MatchInfo *p = (MatchInfo *)pCtx;
149448   Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
149449   int rc = SQLITE_OK;
149450   int iStart = iPhrase * p->nCol;
149451   Fts3Expr *pEof;                 /* Ancestor node already at EOF */
149452 
149453   /* This must be a phrase */
149454   assert( pExpr->pPhrase );
149455 
149456   /* Initialize all output integers to zero. */
149457   memset(&p->aMatchinfo[iStart], 0, sizeof(u32) * p->nCol);
149458 
149459   /* Check if this or any parent node is at EOF. If so, then all output
149460   ** values are zero.  */
149461   for(pEof=pExpr; pEof && pEof->bEof==0; pEof=pEof->pParent);
149462 
149463   if( pEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
149464     Fts3Phrase *pPhrase = pExpr->pPhrase;
149465     char *pIter = pPhrase->doclist.pList;
149466     int iCol = 0;
149467 
149468     while( 1 ){
149469       int nHit = fts3ColumnlistCount(&pIter);
149470       if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
149471         p->aMatchinfo[iStart + iCol] = (u32)nHit;
149472       }
149473       assert( *pIter==0x00 || *pIter==0x01 );
149474       if( *pIter!=0x01 ) break;
149475       pIter++;
149476       pIter += fts3GetVarint32(pIter, &iCol);
149477     }
149478   }
149479 
149480   return rc;
149481 }
149482 
149483 static int fts3MatchinfoCheck(
149484   Fts3Table *pTab,
149485   char cArg,
149486   char **pzErr
149487 ){
149488   if( (cArg==FTS3_MATCHINFO_NPHRASE)
149489    || (cArg==FTS3_MATCHINFO_NCOL)
149490    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
149491    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
149492    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
149493    || (cArg==FTS3_MATCHINFO_LCS)
149494    || (cArg==FTS3_MATCHINFO_HITS)
149495    || (cArg==FTS3_MATCHINFO_LHITS)
149496   ){
149497     return SQLITE_OK;
149498   }
149499   sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
149500   return SQLITE_ERROR;
149501 }
149502 
149503 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
149504   int nVal;                       /* Number of integers output by cArg */
149505 
149506   switch( cArg ){
149507     case FTS3_MATCHINFO_NDOC:
149508     case FTS3_MATCHINFO_NPHRASE:
149509     case FTS3_MATCHINFO_NCOL:
149510       nVal = 1;
149511       break;
149512 
149513     case FTS3_MATCHINFO_AVGLENGTH:
149514     case FTS3_MATCHINFO_LENGTH:
149515     case FTS3_MATCHINFO_LCS:
149516       nVal = pInfo->nCol;
149517       break;
149518 
149519     case FTS3_MATCHINFO_LHITS:
149520       nVal = pInfo->nCol * pInfo->nPhrase;
149521       break;
149522 
149523     default:
149524       assert( cArg==FTS3_MATCHINFO_HITS );
149525       nVal = pInfo->nCol * pInfo->nPhrase * 3;
149526       break;
149527   }
149528 
149529   return nVal;
149530 }
149531 
149532 static int fts3MatchinfoSelectDoctotal(
149533   Fts3Table *pTab,
149534   sqlite3_stmt **ppStmt,
149535   sqlite3_int64 *pnDoc,
149536   const char **paLen
149537 ){
149538   sqlite3_stmt *pStmt;
149539   const char *a;
149540   sqlite3_int64 nDoc;
149541 
149542   if( !*ppStmt ){
149543     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
149544     if( rc!=SQLITE_OK ) return rc;
149545   }
149546   pStmt = *ppStmt;
149547   assert( sqlite3_data_count(pStmt)==1 );
149548 
149549   a = sqlite3_column_blob(pStmt, 0);
149550   a += sqlite3Fts3GetVarint(a, &nDoc);
149551   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
149552   *pnDoc = (u32)nDoc;
149553 
149554   if( paLen ) *paLen = a;
149555   return SQLITE_OK;
149556 }
149557 
149558 /*
149559 ** An instance of the following structure is used to store state while
149560 ** iterating through a multi-column position-list corresponding to the
149561 ** hits for a single phrase on a single row in order to calculate the
149562 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
149563 */
149564 typedef struct LcsIterator LcsIterator;
149565 struct LcsIterator {
149566   Fts3Expr *pExpr;                /* Pointer to phrase expression */
149567   int iPosOffset;                 /* Tokens count up to end of this phrase */
149568   char *pRead;                    /* Cursor used to iterate through aDoclist */
149569   int iPos;                       /* Current position */
149570 };
149571 
149572 /*
149573 ** If LcsIterator.iCol is set to the following value, the iterator has
149574 ** finished iterating through all offsets for all columns.
149575 */
149576 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
149577 
149578 static int fts3MatchinfoLcsCb(
149579   Fts3Expr *pExpr,                /* Phrase expression node */
149580   int iPhrase,                    /* Phrase number (numbered from zero) */
149581   void *pCtx                      /* Pointer to MatchInfo structure */
149582 ){
149583   LcsIterator *aIter = (LcsIterator *)pCtx;
149584   aIter[iPhrase].pExpr = pExpr;
149585   return SQLITE_OK;
149586 }
149587 
149588 /*
149589 ** Advance the iterator passed as an argument to the next position. Return
149590 ** 1 if the iterator is at EOF or if it now points to the start of the
149591 ** position list for the next column.
149592 */
149593 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
149594   char *pRead = pIter->pRead;
149595   sqlite3_int64 iRead;
149596   int rc = 0;
149597 
149598   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
149599   if( iRead==0 || iRead==1 ){
149600     pRead = 0;
149601     rc = 1;
149602   }else{
149603     pIter->iPos += (int)(iRead-2);
149604   }
149605 
149606   pIter->pRead = pRead;
149607   return rc;
149608 }
149609 
149610 /*
149611 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
149612 **
149613 ** If the call is successful, the longest-common-substring lengths for each
149614 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
149615 ** array before returning. SQLITE_OK is returned in this case.
149616 **
149617 ** Otherwise, if an error occurs, an SQLite error code is returned and the
149618 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
149619 ** undefined.
149620 */
149621 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
149622   LcsIterator *aIter;
149623   int i;
149624   int iCol;
149625   int nToken = 0;
149626 
149627   /* Allocate and populate the array of LcsIterator objects. The array
149628   ** contains one element for each matchable phrase in the query.
149629   **/
149630   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
149631   if( !aIter ) return SQLITE_NOMEM;
149632   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
149633   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
149634 
149635   for(i=0; i<pInfo->nPhrase; i++){
149636     LcsIterator *pIter = &aIter[i];
149637     nToken -= pIter->pExpr->pPhrase->nToken;
149638     pIter->iPosOffset = nToken;
149639   }
149640 
149641   for(iCol=0; iCol<pInfo->nCol; iCol++){
149642     int nLcs = 0;                 /* LCS value for this column */
149643     int nLive = 0;                /* Number of iterators in aIter not at EOF */
149644 
149645     for(i=0; i<pInfo->nPhrase; i++){
149646       int rc;
149647       LcsIterator *pIt = &aIter[i];
149648       rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
149649       if( rc!=SQLITE_OK ) return rc;
149650       if( pIt->pRead ){
149651         pIt->iPos = pIt->iPosOffset;
149652         fts3LcsIteratorAdvance(&aIter[i]);
149653         nLive++;
149654       }
149655     }
149656 
149657     while( nLive>0 ){
149658       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
149659       int nThisLcs = 0;           /* LCS for the current iterator positions */
149660 
149661       for(i=0; i<pInfo->nPhrase; i++){
149662         LcsIterator *pIter = &aIter[i];
149663         if( pIter->pRead==0 ){
149664           /* This iterator is already at EOF for this column. */
149665           nThisLcs = 0;
149666         }else{
149667           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
149668             pAdv = pIter;
149669           }
149670           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
149671             nThisLcs++;
149672           }else{
149673             nThisLcs = 1;
149674           }
149675           if( nThisLcs>nLcs ) nLcs = nThisLcs;
149676         }
149677       }
149678       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
149679     }
149680 
149681     pInfo->aMatchinfo[iCol] = nLcs;
149682   }
149683 
149684   sqlite3_free(aIter);
149685   return SQLITE_OK;
149686 }
149687 
149688 /*
149689 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
149690 ** be returned by the matchinfo() function. Argument zArg contains the
149691 ** format string passed as the second argument to matchinfo (or the
149692 ** default value "pcx" if no second argument was specified). The format
149693 ** string has already been validated and the pInfo->aMatchinfo[] array
149694 ** is guaranteed to be large enough for the output.
149695 **
149696 ** If bGlobal is true, then populate all fields of the matchinfo() output.
149697 ** If it is false, then assume that those fields that do not change between
149698 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
149699 ** have already been populated.
149700 **
149701 ** Return SQLITE_OK if successful, or an SQLite error code if an error
149702 ** occurs. If a value other than SQLITE_OK is returned, the state the
149703 ** pInfo->aMatchinfo[] buffer is left in is undefined.
149704 */
149705 static int fts3MatchinfoValues(
149706   Fts3Cursor *pCsr,               /* FTS3 cursor object */
149707   int bGlobal,                    /* True to grab the global stats */
149708   MatchInfo *pInfo,               /* Matchinfo context object */
149709   const char *zArg                /* Matchinfo format string */
149710 ){
149711   int rc = SQLITE_OK;
149712   int i;
149713   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
149714   sqlite3_stmt *pSelect = 0;
149715 
149716   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
149717 
149718     switch( zArg[i] ){
149719       case FTS3_MATCHINFO_NPHRASE:
149720         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
149721         break;
149722 
149723       case FTS3_MATCHINFO_NCOL:
149724         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
149725         break;
149726 
149727       case FTS3_MATCHINFO_NDOC:
149728         if( bGlobal ){
149729           sqlite3_int64 nDoc = 0;
149730           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
149731           pInfo->aMatchinfo[0] = (u32)nDoc;
149732         }
149733         break;
149734 
149735       case FTS3_MATCHINFO_AVGLENGTH:
149736         if( bGlobal ){
149737           sqlite3_int64 nDoc;     /* Number of rows in table */
149738           const char *a;          /* Aggregate column length array */
149739 
149740           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
149741           if( rc==SQLITE_OK ){
149742             int iCol;
149743             for(iCol=0; iCol<pInfo->nCol; iCol++){
149744               u32 iVal;
149745               sqlite3_int64 nToken;
149746               a += sqlite3Fts3GetVarint(a, &nToken);
149747               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
149748               pInfo->aMatchinfo[iCol] = iVal;
149749             }
149750           }
149751         }
149752         break;
149753 
149754       case FTS3_MATCHINFO_LENGTH: {
149755         sqlite3_stmt *pSelectDocsize = 0;
149756         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
149757         if( rc==SQLITE_OK ){
149758           int iCol;
149759           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
149760           for(iCol=0; iCol<pInfo->nCol; iCol++){
149761             sqlite3_int64 nToken;
149762             a += sqlite3Fts3GetVarint(a, &nToken);
149763             pInfo->aMatchinfo[iCol] = (u32)nToken;
149764           }
149765         }
149766         sqlite3_reset(pSelectDocsize);
149767         break;
149768       }
149769 
149770       case FTS3_MATCHINFO_LCS:
149771         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
149772         if( rc==SQLITE_OK ){
149773           rc = fts3MatchinfoLcs(pCsr, pInfo);
149774         }
149775         break;
149776 
149777       case FTS3_MATCHINFO_LHITS:
149778         (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLHitsCb, (void*)pInfo);
149779         break;
149780 
149781       default: {
149782         Fts3Expr *pExpr;
149783         assert( zArg[i]==FTS3_MATCHINFO_HITS );
149784         pExpr = pCsr->pExpr;
149785         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
149786         if( rc!=SQLITE_OK ) break;
149787         if( bGlobal ){
149788           if( pCsr->pDeferred ){
149789             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
149790             if( rc!=SQLITE_OK ) break;
149791           }
149792           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
149793           if( rc!=SQLITE_OK ) break;
149794         }
149795         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
149796         break;
149797       }
149798     }
149799 
149800     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
149801   }
149802 
149803   sqlite3_reset(pSelect);
149804   return rc;
149805 }
149806 
149807 
149808 /*
149809 ** Populate pCsr->aMatchinfo[] with data for the current row. The
149810 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
149811 */
149812 static int fts3GetMatchinfo(
149813   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
149814   const char *zArg                /* Second argument to matchinfo() function */
149815 ){
149816   MatchInfo sInfo;
149817   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
149818   int rc = SQLITE_OK;
149819   int bGlobal = 0;                /* Collect 'global' stats as well as local */
149820 
149821   memset(&sInfo, 0, sizeof(MatchInfo));
149822   sInfo.pCursor = pCsr;
149823   sInfo.nCol = pTab->nColumn;
149824 
149825   /* If there is cached matchinfo() data, but the format string for the
149826   ** cache does not match the format string for this request, discard
149827   ** the cached data. */
149828   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
149829     assert( pCsr->aMatchinfo );
149830     sqlite3_free(pCsr->aMatchinfo);
149831     pCsr->zMatchinfo = 0;
149832     pCsr->aMatchinfo = 0;
149833   }
149834 
149835   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
149836   ** matchinfo function has been called for this query. In this case
149837   ** allocate the array used to accumulate the matchinfo data and
149838   ** initialize those elements that are constant for every row.
149839   */
149840   if( pCsr->aMatchinfo==0 ){
149841     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
149842     int nArg;                     /* Bytes in zArg */
149843     int i;                        /* Used to iterate through zArg */
149844 
149845     /* Determine the number of phrases in the query */
149846     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
149847     sInfo.nPhrase = pCsr->nPhrase;
149848 
149849     /* Determine the number of integers in the buffer returned by this call. */
149850     for(i=0; zArg[i]; i++){
149851       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
149852     }
149853 
149854     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
149855     nArg = (int)strlen(zArg);
149856     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
149857     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
149858 
149859     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
149860     pCsr->nMatchinfo = nMatchinfo;
149861     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
149862     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
149863     pCsr->isMatchinfoNeeded = 1;
149864     bGlobal = 1;
149865   }
149866 
149867   sInfo.aMatchinfo = pCsr->aMatchinfo;
149868   sInfo.nPhrase = pCsr->nPhrase;
149869   if( pCsr->isMatchinfoNeeded ){
149870     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
149871     pCsr->isMatchinfoNeeded = 0;
149872   }
149873 
149874   return rc;
149875 }
149876 
149877 /*
149878 ** Implementation of snippet() function.
149879 */
149880 SQLITE_PRIVATE void sqlite3Fts3Snippet(
149881   sqlite3_context *pCtx,          /* SQLite function call context */
149882   Fts3Cursor *pCsr,               /* Cursor object */
149883   const char *zStart,             /* Snippet start text - "<b>" */
149884   const char *zEnd,               /* Snippet end text - "</b>" */
149885   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
149886   int iCol,                       /* Extract snippet from this column */
149887   int nToken                      /* Approximate number of tokens in snippet */
149888 ){
149889   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
149890   int rc = SQLITE_OK;
149891   int i;
149892   StrBuffer res = {0, 0, 0};
149893 
149894   /* The returned text includes up to four fragments of text extracted from
149895   ** the data in the current row. The first iteration of the for(...) loop
149896   ** below attempts to locate a single fragment of text nToken tokens in
149897   ** size that contains at least one instance of all phrases in the query
149898   ** expression that appear in the current row. If such a fragment of text
149899   ** cannot be found, the second iteration of the loop attempts to locate
149900   ** a pair of fragments, and so on.
149901   */
149902   int nSnippet = 0;               /* Number of fragments in this snippet */
149903   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
149904   int nFToken = -1;               /* Number of tokens in each fragment */
149905 
149906   if( !pCsr->pExpr ){
149907     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
149908     return;
149909   }
149910 
149911   for(nSnippet=1; 1; nSnippet++){
149912 
149913     int iSnip;                    /* Loop counter 0..nSnippet-1 */
149914     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
149915     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
149916 
149917     if( nToken>=0 ){
149918       nFToken = (nToken+nSnippet-1) / nSnippet;
149919     }else{
149920       nFToken = -1 * nToken;
149921     }
149922 
149923     for(iSnip=0; iSnip<nSnippet; iSnip++){
149924       int iBestScore = -1;        /* Best score of columns checked so far */
149925       int iRead;                  /* Used to iterate through columns */
149926       SnippetFragment *pFragment = &aSnippet[iSnip];
149927 
149928       memset(pFragment, 0, sizeof(*pFragment));
149929 
149930       /* Loop through all columns of the table being considered for snippets.
149931       ** If the iCol argument to this function was negative, this means all
149932       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
149933       */
149934       for(iRead=0; iRead<pTab->nColumn; iRead++){
149935         SnippetFragment sF = {0, 0, 0, 0};
149936         int iS = 0;
149937         if( iCol>=0 && iRead!=iCol ) continue;
149938 
149939         /* Find the best snippet of nFToken tokens in column iRead. */
149940         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
149941         if( rc!=SQLITE_OK ){
149942           goto snippet_out;
149943         }
149944         if( iS>iBestScore ){
149945           *pFragment = sF;
149946           iBestScore = iS;
149947         }
149948       }
149949 
149950       mCovered |= pFragment->covered;
149951     }
149952 
149953     /* If all query phrases seen by fts3BestSnippet() are present in at least
149954     ** one of the nSnippet snippet fragments, break out of the loop.
149955     */
149956     assert( (mCovered&mSeen)==mCovered );
149957     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
149958   }
149959 
149960   assert( nFToken>0 );
149961 
149962   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
149963     rc = fts3SnippetText(pCsr, &aSnippet[i],
149964         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
149965     );
149966   }
149967 
149968  snippet_out:
149969   sqlite3Fts3SegmentsClose(pTab);
149970   if( rc!=SQLITE_OK ){
149971     sqlite3_result_error_code(pCtx, rc);
149972     sqlite3_free(res.z);
149973   }else{
149974     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
149975   }
149976 }
149977 
149978 
149979 typedef struct TermOffset TermOffset;
149980 typedef struct TermOffsetCtx TermOffsetCtx;
149981 
149982 struct TermOffset {
149983   char *pList;                    /* Position-list */
149984   int iPos;                       /* Position just read from pList */
149985   int iOff;                       /* Offset of this term from read positions */
149986 };
149987 
149988 struct TermOffsetCtx {
149989   Fts3Cursor *pCsr;
149990   int iCol;                       /* Column of table to populate aTerm for */
149991   int iTerm;
149992   sqlite3_int64 iDocid;
149993   TermOffset *aTerm;
149994 };
149995 
149996 /*
149997 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
149998 */
149999 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
150000   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
150001   int nTerm;                      /* Number of tokens in phrase */
150002   int iTerm;                      /* For looping through nTerm phrase terms */
150003   char *pList;                    /* Pointer to position list for phrase */
150004   int iPos = 0;                   /* First position in position-list */
150005   int rc;
150006 
150007   UNUSED_PARAMETER(iPhrase);
150008   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
150009   nTerm = pExpr->pPhrase->nToken;
150010   if( pList ){
150011     fts3GetDeltaPosition(&pList, &iPos);
150012     assert( iPos>=0 );
150013   }
150014 
150015   for(iTerm=0; iTerm<nTerm; iTerm++){
150016     TermOffset *pT = &p->aTerm[p->iTerm++];
150017     pT->iOff = nTerm-iTerm-1;
150018     pT->pList = pList;
150019     pT->iPos = iPos;
150020   }
150021 
150022   return rc;
150023 }
150024 
150025 /*
150026 ** Implementation of offsets() function.
150027 */
150028 SQLITE_PRIVATE void sqlite3Fts3Offsets(
150029   sqlite3_context *pCtx,          /* SQLite function call context */
150030   Fts3Cursor *pCsr                /* Cursor object */
150031 ){
150032   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
150033   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
150034   int rc;                         /* Return Code */
150035   int nToken;                     /* Number of tokens in query */
150036   int iCol;                       /* Column currently being processed */
150037   StrBuffer res = {0, 0, 0};      /* Result string */
150038   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
150039 
150040   if( !pCsr->pExpr ){
150041     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
150042     return;
150043   }
150044 
150045   memset(&sCtx, 0, sizeof(sCtx));
150046   assert( pCsr->isRequireSeek==0 );
150047 
150048   /* Count the number of terms in the query */
150049   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
150050   if( rc!=SQLITE_OK ) goto offsets_out;
150051 
150052   /* Allocate the array of TermOffset iterators. */
150053   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
150054   if( 0==sCtx.aTerm ){
150055     rc = SQLITE_NOMEM;
150056     goto offsets_out;
150057   }
150058   sCtx.iDocid = pCsr->iPrevId;
150059   sCtx.pCsr = pCsr;
150060 
150061   /* Loop through the table columns, appending offset information to
150062   ** string-buffer res for each column.
150063   */
150064   for(iCol=0; iCol<pTab->nColumn; iCol++){
150065     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
150066     const char *ZDUMMY;           /* Dummy argument used with xNext() */
150067     int NDUMMY = 0;               /* Dummy argument used with xNext() */
150068     int iStart = 0;
150069     int iEnd = 0;
150070     int iCurrent = 0;
150071     const char *zDoc;
150072     int nDoc;
150073 
150074     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
150075     ** no way that this operation can fail, so the return code from
150076     ** fts3ExprIterate() can be discarded.
150077     */
150078     sCtx.iCol = iCol;
150079     sCtx.iTerm = 0;
150080     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
150081 
150082     /* Retreive the text stored in column iCol. If an SQL NULL is stored
150083     ** in column iCol, jump immediately to the next iteration of the loop.
150084     ** If an OOM occurs while retrieving the data (this can happen if SQLite
150085     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
150086     ** to the caller.
150087     */
150088     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
150089     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
150090     if( zDoc==0 ){
150091       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
150092         continue;
150093       }
150094       rc = SQLITE_NOMEM;
150095       goto offsets_out;
150096     }
150097 
150098     /* Initialize a tokenizer iterator to iterate through column iCol. */
150099     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
150100         zDoc, nDoc, &pC
150101     );
150102     if( rc!=SQLITE_OK ) goto offsets_out;
150103 
150104     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
150105     while( rc==SQLITE_OK ){
150106       int i;                      /* Used to loop through terms */
150107       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
150108       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
150109 
150110       for(i=0; i<nToken; i++){
150111         TermOffset *pT = &sCtx.aTerm[i];
150112         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
150113           iMinPos = pT->iPos-pT->iOff;
150114           pTerm = pT;
150115         }
150116       }
150117 
150118       if( !pTerm ){
150119         /* All offsets for this column have been gathered. */
150120         rc = SQLITE_DONE;
150121       }else{
150122         assert( iCurrent<=iMinPos );
150123         if( 0==(0xFE&*pTerm->pList) ){
150124           pTerm->pList = 0;
150125         }else{
150126           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
150127         }
150128         while( rc==SQLITE_OK && iCurrent<iMinPos ){
150129           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
150130         }
150131         if( rc==SQLITE_OK ){
150132           char aBuffer[64];
150133           sqlite3_snprintf(sizeof(aBuffer), aBuffer,
150134               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
150135           );
150136           rc = fts3StringAppend(&res, aBuffer, -1);
150137         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
150138           rc = FTS_CORRUPT_VTAB;
150139         }
150140       }
150141     }
150142     if( rc==SQLITE_DONE ){
150143       rc = SQLITE_OK;
150144     }
150145 
150146     pMod->xClose(pC);
150147     if( rc!=SQLITE_OK ) goto offsets_out;
150148   }
150149 
150150  offsets_out:
150151   sqlite3_free(sCtx.aTerm);
150152   assert( rc!=SQLITE_DONE );
150153   sqlite3Fts3SegmentsClose(pTab);
150154   if( rc!=SQLITE_OK ){
150155     sqlite3_result_error_code(pCtx,  rc);
150156     sqlite3_free(res.z);
150157   }else{
150158     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
150159   }
150160   return;
150161 }
150162 
150163 /*
150164 ** Implementation of matchinfo() function.
150165 */
150166 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
150167   sqlite3_context *pContext,      /* Function call context */
150168   Fts3Cursor *pCsr,               /* FTS3 table cursor */
150169   const char *zArg                /* Second arg to matchinfo() function */
150170 ){
150171   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
150172   int rc;
150173   int i;
150174   const char *zFormat;
150175 
150176   if( zArg ){
150177     for(i=0; zArg[i]; i++){
150178       char *zErr = 0;
150179       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
150180         sqlite3_result_error(pContext, zErr, -1);
150181         sqlite3_free(zErr);
150182         return;
150183       }
150184     }
150185     zFormat = zArg;
150186   }else{
150187     zFormat = FTS3_MATCHINFO_DEFAULT;
150188   }
150189 
150190   if( !pCsr->pExpr ){
150191     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
150192     return;
150193   }
150194 
150195   /* Retrieve matchinfo() data. */
150196   rc = fts3GetMatchinfo(pCsr, zFormat);
150197   sqlite3Fts3SegmentsClose(pTab);
150198 
150199   if( rc!=SQLITE_OK ){
150200     sqlite3_result_error_code(pContext, rc);
150201   }else{
150202     int n = pCsr->nMatchinfo * sizeof(u32);
150203     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
150204   }
150205 }
150206 
150207 #endif
150208 
150209 /************** End of fts3_snippet.c ****************************************/
150210 /************** Begin file fts3_unicode.c ************************************/
150211 /*
150212 ** 2012 May 24
150213 **
150214 ** The author disclaims copyright to this source code.  In place of
150215 ** a legal notice, here is a blessing:
150216 **
150217 **    May you do good and not evil.
150218 **    May you find forgiveness for yourself and forgive others.
150219 **    May you share freely, never taking more than you give.
150220 **
150221 ******************************************************************************
150222 **
150223 ** Implementation of the "unicode" full-text-search tokenizer.
150224 */
150225 
150226 #ifndef SQLITE_DISABLE_FTS3_UNICODE
150227 
150228 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
150229 
150230 /* #include <assert.h> */
150231 /* #include <stdlib.h> */
150232 /* #include <stdio.h> */
150233 /* #include <string.h> */
150234 
150235 
150236 /*
150237 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
150238 ** from the sqlite3 source file utf.c. If this file is compiled as part
150239 ** of the amalgamation, they are not required.
150240 */
150241 #ifndef SQLITE_AMALGAMATION
150242 
150243 static const unsigned char sqlite3Utf8Trans1[] = {
150244   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
150245   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
150246   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
150247   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
150248   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
150249   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
150250   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
150251   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
150252 };
150253 
150254 #define READ_UTF8(zIn, zTerm, c)                           \
150255   c = *(zIn++);                                            \
150256   if( c>=0xc0 ){                                           \
150257     c = sqlite3Utf8Trans1[c-0xc0];                         \
150258     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
150259       c = (c<<6) + (0x3f & *(zIn++));                      \
150260     }                                                      \
150261     if( c<0x80                                             \
150262         || (c&0xFFFFF800)==0xD800                          \
150263         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
150264   }
150265 
150266 #define WRITE_UTF8(zOut, c) {                          \
150267   if( c<0x00080 ){                                     \
150268     *zOut++ = (u8)(c&0xFF);                            \
150269   }                                                    \
150270   else if( c<0x00800 ){                                \
150271     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
150272     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
150273   }                                                    \
150274   else if( c<0x10000 ){                                \
150275     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
150276     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
150277     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
150278   }else{                                               \
150279     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
150280     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
150281     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
150282     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
150283   }                                                    \
150284 }
150285 
150286 #endif /* ifndef SQLITE_AMALGAMATION */
150287 
150288 typedef struct unicode_tokenizer unicode_tokenizer;
150289 typedef struct unicode_cursor unicode_cursor;
150290 
150291 struct unicode_tokenizer {
150292   sqlite3_tokenizer base;
150293   int bRemoveDiacritic;
150294   int nException;
150295   int *aiException;
150296 };
150297 
150298 struct unicode_cursor {
150299   sqlite3_tokenizer_cursor base;
150300   const unsigned char *aInput;    /* Input text being tokenized */
150301   int nInput;                     /* Size of aInput[] in bytes */
150302   int iOff;                       /* Current offset within aInput[] */
150303   int iToken;                     /* Index of next token to be returned */
150304   char *zToken;                   /* storage for current token */
150305   int nAlloc;                     /* space allocated at zToken */
150306 };
150307 
150308 
150309 /*
150310 ** Destroy a tokenizer allocated by unicodeCreate().
150311 */
150312 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
150313   if( pTokenizer ){
150314     unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
150315     sqlite3_free(p->aiException);
150316     sqlite3_free(p);
150317   }
150318   return SQLITE_OK;
150319 }
150320 
150321 /*
150322 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
150323 ** statement has specified that the tokenizer for this table shall consider
150324 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
150325 ** token characters (if bAlnum==1).
150326 **
150327 ** For each codepoint in the zIn/nIn string, this function checks if the
150328 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
150329 ** If so, no action is taken. Otherwise, the codepoint is added to the
150330 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
150331 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
150332 ** codepoints in the aiException[] array.
150333 **
150334 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
150335 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
150336 ** It is not possible to change the behavior of the tokenizer with respect
150337 ** to these codepoints.
150338 */
150339 static int unicodeAddExceptions(
150340   unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
150341   int bAlnum,                     /* Replace Isalnum() return value with this */
150342   const char *zIn,                /* Array of characters to make exceptions */
150343   int nIn                         /* Length of z in bytes */
150344 ){
150345   const unsigned char *z = (const unsigned char *)zIn;
150346   const unsigned char *zTerm = &z[nIn];
150347   int iCode;
150348   int nEntry = 0;
150349 
150350   assert( bAlnum==0 || bAlnum==1 );
150351 
150352   while( z<zTerm ){
150353     READ_UTF8(z, zTerm, iCode);
150354     assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
150355     if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
150356      && sqlite3FtsUnicodeIsdiacritic(iCode)==0
150357     ){
150358       nEntry++;
150359     }
150360   }
150361 
150362   if( nEntry ){
150363     int *aNew;                    /* New aiException[] array */
150364     int nNew;                     /* Number of valid entries in array aNew[] */
150365 
150366     aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
150367     if( aNew==0 ) return SQLITE_NOMEM;
150368     nNew = p->nException;
150369 
150370     z = (const unsigned char *)zIn;
150371     while( z<zTerm ){
150372       READ_UTF8(z, zTerm, iCode);
150373       if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
150374        && sqlite3FtsUnicodeIsdiacritic(iCode)==0
150375       ){
150376         int i, j;
150377         for(i=0; i<nNew && aNew[i]<iCode; i++);
150378         for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
150379         aNew[i] = iCode;
150380         nNew++;
150381       }
150382     }
150383     p->aiException = aNew;
150384     p->nException = nNew;
150385   }
150386 
150387   return SQLITE_OK;
150388 }
150389 
150390 /*
150391 ** Return true if the p->aiException[] array contains the value iCode.
150392 */
150393 static int unicodeIsException(unicode_tokenizer *p, int iCode){
150394   if( p->nException>0 ){
150395     int *a = p->aiException;
150396     int iLo = 0;
150397     int iHi = p->nException-1;
150398 
150399     while( iHi>=iLo ){
150400       int iTest = (iHi + iLo) / 2;
150401       if( iCode==a[iTest] ){
150402         return 1;
150403       }else if( iCode>a[iTest] ){
150404         iLo = iTest+1;
150405       }else{
150406         iHi = iTest-1;
150407       }
150408     }
150409   }
150410 
150411   return 0;
150412 }
150413 
150414 /*
150415 ** Return true if, for the purposes of tokenization, codepoint iCode is
150416 ** considered a token character (not a separator).
150417 */
150418 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
150419   assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
150420   return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
150421 }
150422 
150423 /*
150424 ** Create a new tokenizer instance.
150425 */
150426 static int unicodeCreate(
150427   int nArg,                       /* Size of array argv[] */
150428   const char * const *azArg,      /* Tokenizer creation arguments */
150429   sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
150430 ){
150431   unicode_tokenizer *pNew;        /* New tokenizer object */
150432   int i;
150433   int rc = SQLITE_OK;
150434 
150435   pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
150436   if( pNew==NULL ) return SQLITE_NOMEM;
150437   memset(pNew, 0, sizeof(unicode_tokenizer));
150438   pNew->bRemoveDiacritic = 1;
150439 
150440   for(i=0; rc==SQLITE_OK && i<nArg; i++){
150441     const char *z = azArg[i];
150442     int n = (int)strlen(z);
150443 
150444     if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
150445       pNew->bRemoveDiacritic = 1;
150446     }
150447     else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
150448       pNew->bRemoveDiacritic = 0;
150449     }
150450     else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
150451       rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
150452     }
150453     else if( n>=11 && memcmp("separators=", z, 11)==0 ){
150454       rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
150455     }
150456     else{
150457       /* Unrecognized argument */
150458       rc  = SQLITE_ERROR;
150459     }
150460   }
150461 
150462   if( rc!=SQLITE_OK ){
150463     unicodeDestroy((sqlite3_tokenizer *)pNew);
150464     pNew = 0;
150465   }
150466   *pp = (sqlite3_tokenizer *)pNew;
150467   return rc;
150468 }
150469 
150470 /*
150471 ** Prepare to begin tokenizing a particular string.  The input
150472 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
150473 ** used to incrementally tokenize this string is returned in
150474 ** *ppCursor.
150475 */
150476 static int unicodeOpen(
150477   sqlite3_tokenizer *p,           /* The tokenizer */
150478   const char *aInput,             /* Input string */
150479   int nInput,                     /* Size of string aInput in bytes */
150480   sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
150481 ){
150482   unicode_cursor *pCsr;
150483 
150484   pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
150485   if( pCsr==0 ){
150486     return SQLITE_NOMEM;
150487   }
150488   memset(pCsr, 0, sizeof(unicode_cursor));
150489 
150490   pCsr->aInput = (const unsigned char *)aInput;
150491   if( aInput==0 ){
150492     pCsr->nInput = 0;
150493   }else if( nInput<0 ){
150494     pCsr->nInput = (int)strlen(aInput);
150495   }else{
150496     pCsr->nInput = nInput;
150497   }
150498 
150499   *pp = &pCsr->base;
150500   UNUSED_PARAMETER(p);
150501   return SQLITE_OK;
150502 }
150503 
150504 /*
150505 ** Close a tokenization cursor previously opened by a call to
150506 ** simpleOpen() above.
150507 */
150508 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
150509   unicode_cursor *pCsr = (unicode_cursor *) pCursor;
150510   sqlite3_free(pCsr->zToken);
150511   sqlite3_free(pCsr);
150512   return SQLITE_OK;
150513 }
150514 
150515 /*
150516 ** Extract the next token from a tokenization cursor.  The cursor must
150517 ** have been opened by a prior call to simpleOpen().
150518 */
150519 static int unicodeNext(
150520   sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
150521   const char **paToken,           /* OUT: Token text */
150522   int *pnToken,                   /* OUT: Number of bytes at *paToken */
150523   int *piStart,                   /* OUT: Starting offset of token */
150524   int *piEnd,                     /* OUT: Ending offset of token */
150525   int *piPos                      /* OUT: Position integer of token */
150526 ){
150527   unicode_cursor *pCsr = (unicode_cursor *)pC;
150528   unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
150529   int iCode = 0;
150530   char *zOut;
150531   const unsigned char *z = &pCsr->aInput[pCsr->iOff];
150532   const unsigned char *zStart = z;
150533   const unsigned char *zEnd;
150534   const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
150535 
150536   /* Scan past any delimiter characters before the start of the next token.
150537   ** Return SQLITE_DONE early if this takes us all the way to the end of
150538   ** the input.  */
150539   while( z<zTerm ){
150540     READ_UTF8(z, zTerm, iCode);
150541     if( unicodeIsAlnum(p, iCode) ) break;
150542     zStart = z;
150543   }
150544   if( zStart>=zTerm ) return SQLITE_DONE;
150545 
150546   zOut = pCsr->zToken;
150547   do {
150548     int iOut;
150549 
150550     /* Grow the output buffer if required. */
150551     if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
150552       char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
150553       if( !zNew ) return SQLITE_NOMEM;
150554       zOut = &zNew[zOut - pCsr->zToken];
150555       pCsr->zToken = zNew;
150556       pCsr->nAlloc += 64;
150557     }
150558 
150559     /* Write the folded case of the last character read to the output */
150560     zEnd = z;
150561     iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
150562     if( iOut ){
150563       WRITE_UTF8(zOut, iOut);
150564     }
150565 
150566     /* If the cursor is not at EOF, read the next character */
150567     if( z>=zTerm ) break;
150568     READ_UTF8(z, zTerm, iCode);
150569   }while( unicodeIsAlnum(p, iCode)
150570        || sqlite3FtsUnicodeIsdiacritic(iCode)
150571   );
150572 
150573   /* Set the output variables and return. */
150574   pCsr->iOff = (int)(z - pCsr->aInput);
150575   *paToken = pCsr->zToken;
150576   *pnToken = (int)(zOut - pCsr->zToken);
150577   *piStart = (int)(zStart - pCsr->aInput);
150578   *piEnd = (int)(zEnd - pCsr->aInput);
150579   *piPos = pCsr->iToken++;
150580   return SQLITE_OK;
150581 }
150582 
150583 /*
150584 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
150585 ** structure for the unicode tokenizer.
150586 */
150587 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
150588   static const sqlite3_tokenizer_module module = {
150589     0,
150590     unicodeCreate,
150591     unicodeDestroy,
150592     unicodeOpen,
150593     unicodeClose,
150594     unicodeNext,
150595     0,
150596   };
150597   *ppModule = &module;
150598 }
150599 
150600 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
150601 #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
150602 
150603 /************** End of fts3_unicode.c ****************************************/
150604 /************** Begin file fts3_unicode2.c ***********************************/
150605 /*
150606 ** 2012 May 25
150607 **
150608 ** The author disclaims copyright to this source code.  In place of
150609 ** a legal notice, here is a blessing:
150610 **
150611 **    May you do good and not evil.
150612 **    May you find forgiveness for yourself and forgive others.
150613 **    May you share freely, never taking more than you give.
150614 **
150615 ******************************************************************************
150616 */
150617 
150618 /*
150619 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
150620 */
150621 
150622 #ifndef SQLITE_DISABLE_FTS3_UNICODE
150623 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
150624 
150625 /* #include <assert.h> */
150626 
150627 /*
150628 ** Return true if the argument corresponds to a unicode codepoint
150629 ** classified as either a letter or a number. Otherwise false.
150630 **
150631 ** The results are undefined if the value passed to this function
150632 ** is less than zero.
150633 */
150634 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
150635   /* Each unsigned integer in the following array corresponds to a contiguous
150636   ** range of unicode codepoints that are not either letters or numbers (i.e.
150637   ** codepoints for which this function should return 0).
150638   **
150639   ** The most significant 22 bits in each 32-bit value contain the first
150640   ** codepoint in the range. The least significant 10 bits are used to store
150641   ** the size of the range (always at least 1). In other words, the value
150642   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
150643   ** C. It is not possible to represent a range larger than 1023 codepoints
150644   ** using this format.
150645   */
150646   static const unsigned int aEntry[] = {
150647     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
150648     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
150649     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
150650     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
150651     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
150652     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
150653     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
150654     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
150655     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
150656     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
150657     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
150658     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
150659     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
150660     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
150661     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
150662     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
150663     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
150664     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
150665     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
150666     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
150667     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
150668     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
150669     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
150670     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
150671     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
150672     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
150673     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
150674     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
150675     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
150676     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
150677     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
150678     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
150679     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
150680     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
150681     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
150682     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
150683     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
150684     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
150685     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
150686     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
150687     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
150688     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
150689     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
150690     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
150691     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
150692     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
150693     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
150694     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
150695     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
150696     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
150697     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
150698     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
150699     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
150700     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
150701     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
150702     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
150703     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
150704     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
150705     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
150706     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
150707     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
150708     0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
150709     0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
150710     0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
150711     0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
150712     0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
150713     0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
150714     0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
150715     0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
150716     0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
150717     0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
150718     0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
150719     0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
150720     0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
150721     0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
150722     0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
150723     0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
150724     0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
150725     0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
150726     0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
150727     0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
150728     0x380400F0,
150729   };
150730   static const unsigned int aAscii[4] = {
150731     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
150732   };
150733 
150734   if( c<128 ){
150735     return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
150736   }else if( c<(1<<22) ){
150737     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
150738     int iRes = 0;
150739     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
150740     int iLo = 0;
150741     while( iHi>=iLo ){
150742       int iTest = (iHi + iLo) / 2;
150743       if( key >= aEntry[iTest] ){
150744         iRes = iTest;
150745         iLo = iTest+1;
150746       }else{
150747         iHi = iTest-1;
150748       }
150749     }
150750     assert( aEntry[0]<key );
150751     assert( key>=aEntry[iRes] );
150752     return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
150753   }
150754   return 1;
150755 }
150756 
150757 
150758 /*
150759 ** If the argument is a codepoint corresponding to a lowercase letter
150760 ** in the ASCII range with a diacritic added, return the codepoint
150761 ** of the ASCII letter only. For example, if passed 235 - "LATIN
150762 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
150763 ** E"). The resuls of passing a codepoint that corresponds to an
150764 ** uppercase letter are undefined.
150765 */
150766 static int remove_diacritic(int c){
150767   unsigned short aDia[] = {
150768         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
150769      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
150770      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
150771      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
150772      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
150773      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
150774      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
150775      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
150776     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
150777     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
150778     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
150779     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
150780     62924, 63050, 63082, 63274, 63390,
150781   };
150782   char aChar[] = {
150783     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
150784     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
150785     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
150786     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
150787     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
150788     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
150789     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
150790     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
150791     'e',  'i',  'o',  'u',  'y',
150792   };
150793 
150794   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
150795   int iRes = 0;
150796   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
150797   int iLo = 0;
150798   while( iHi>=iLo ){
150799     int iTest = (iHi + iLo) / 2;
150800     if( key >= aDia[iTest] ){
150801       iRes = iTest;
150802       iLo = iTest+1;
150803     }else{
150804       iHi = iTest-1;
150805     }
150806   }
150807   assert( key>=aDia[iRes] );
150808   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
150809 }
150810 
150811 
150812 /*
150813 ** Return true if the argument interpreted as a unicode codepoint
150814 ** is a diacritical modifier character.
150815 */
150816 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
150817   unsigned int mask0 = 0x08029FDF;
150818   unsigned int mask1 = 0x000361F8;
150819   if( c<768 || c>817 ) return 0;
150820   return (c < 768+32) ?
150821       (mask0 & (1 << (c-768))) :
150822       (mask1 & (1 << (c-768-32)));
150823 }
150824 
150825 
150826 /*
150827 ** Interpret the argument as a unicode codepoint. If the codepoint
150828 ** is an upper case character that has a lower case equivalent,
150829 ** return the codepoint corresponding to the lower case version.
150830 ** Otherwise, return a copy of the argument.
150831 **
150832 ** The results are undefined if the value passed to this function
150833 ** is less than zero.
150834 */
150835 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
150836   /* Each entry in the following array defines a rule for folding a range
150837   ** of codepoints to lower case. The rule applies to a range of nRange
150838   ** codepoints starting at codepoint iCode.
150839   **
150840   ** If the least significant bit in flags is clear, then the rule applies
150841   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
150842   ** need to be folded). Or, if it is set, then the rule only applies to
150843   ** every second codepoint in the range, starting with codepoint C.
150844   **
150845   ** The 7 most significant bits in flags are an index into the aiOff[]
150846   ** array. If a specific codepoint C does require folding, then its lower
150847   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
150848   **
150849   ** The contents of this array are generated by parsing the CaseFolding.txt
150850   ** file distributed as part of the "Unicode Character Database". See
150851   ** http://www.unicode.org for details.
150852   */
150853   static const struct TableEntry {
150854     unsigned short iCode;
150855     unsigned char flags;
150856     unsigned char nRange;
150857   } aEntry[] = {
150858     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
150859     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
150860     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
150861     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
150862     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
150863     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
150864     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
150865     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
150866     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
150867     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
150868     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
150869     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
150870     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
150871     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
150872     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
150873     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
150874     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
150875     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
150876     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
150877     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
150878     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
150879     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
150880     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
150881     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
150882     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
150883     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
150884     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
150885     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
150886     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
150887     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
150888     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
150889     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
150890     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
150891     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
150892     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
150893     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
150894     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
150895     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
150896     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
150897     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
150898     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
150899     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
150900     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
150901     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
150902     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
150903     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
150904     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
150905     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
150906     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
150907     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
150908     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
150909     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
150910     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
150911     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
150912     {65313, 14, 26},
150913   };
150914   static const unsigned short aiOff[] = {
150915    1,     2,     8,     15,    16,    26,    28,    32,
150916    37,    38,    40,    48,    63,    64,    69,    71,
150917    79,    80,    116,   202,   203,   205,   206,   207,
150918    209,   210,   211,   213,   214,   217,   218,   219,
150919    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
150920    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
150921    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
150922    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
150923    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
150924    65514, 65521, 65527, 65528, 65529,
150925   };
150926 
150927   int ret = c;
150928 
150929   assert( c>=0 );
150930   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
150931 
150932   if( c<128 ){
150933     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
150934   }else if( c<65536 ){
150935     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
150936     int iLo = 0;
150937     int iRes = -1;
150938 
150939     while( iHi>=iLo ){
150940       int iTest = (iHi + iLo) / 2;
150941       int cmp = (c - aEntry[iTest].iCode);
150942       if( cmp>=0 ){
150943         iRes = iTest;
150944         iLo = iTest+1;
150945       }else{
150946         iHi = iTest-1;
150947       }
150948     }
150949     assert( iRes<0 || c>=aEntry[iRes].iCode );
150950 
150951     if( iRes>=0 ){
150952       const struct TableEntry *p = &aEntry[iRes];
150953       if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
150954         ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
150955         assert( ret>0 );
150956       }
150957     }
150958 
150959     if( bRemoveDiacritic ) ret = remove_diacritic(ret);
150960   }
150961 
150962   else if( c>=66560 && c<66600 ){
150963     ret = c + 40;
150964   }
150965 
150966   return ret;
150967 }
150968 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
150969 #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
150970 
150971 /************** End of fts3_unicode2.c ***************************************/
150972 /************** Begin file rtree.c *******************************************/
150973 /*
150974 ** 2001 September 15
150975 **
150976 ** The author disclaims copyright to this source code.  In place of
150977 ** a legal notice, here is a blessing:
150978 **
150979 **    May you do good and not evil.
150980 **    May you find forgiveness for yourself and forgive others.
150981 **    May you share freely, never taking more than you give.
150982 **
150983 *************************************************************************
150984 ** This file contains code for implementations of the r-tree and r*-tree
150985 ** algorithms packaged as an SQLite virtual table module.
150986 */
150987 
150988 /*
150989 ** Database Format of R-Tree Tables
150990 ** --------------------------------
150991 **
150992 ** The data structure for a single virtual r-tree table is stored in three
150993 ** native SQLite tables declared as follows. In each case, the '%' character
150994 ** in the table name is replaced with the user-supplied name of the r-tree
150995 ** table.
150996 **
150997 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
150998 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
150999 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
151000 **
151001 ** The data for each node of the r-tree structure is stored in the %_node
151002 ** table. For each node that is not the root node of the r-tree, there is
151003 ** an entry in the %_parent table associating the node with its parent.
151004 ** And for each row of data in the table, there is an entry in the %_rowid
151005 ** table that maps from the entries rowid to the id of the node that it
151006 ** is stored on.
151007 **
151008 ** The root node of an r-tree always exists, even if the r-tree table is
151009 ** empty. The nodeno of the root node is always 1. All other nodes in the
151010 ** table must be the same size as the root node. The content of each node
151011 ** is formatted as follows:
151012 **
151013 **   1. If the node is the root node (node 1), then the first 2 bytes
151014 **      of the node contain the tree depth as a big-endian integer.
151015 **      For non-root nodes, the first 2 bytes are left unused.
151016 **
151017 **   2. The next 2 bytes contain the number of entries currently
151018 **      stored in the node.
151019 **
151020 **   3. The remainder of the node contains the node entries. Each entry
151021 **      consists of a single 8-byte integer followed by an even number
151022 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
151023 **      of a record. For internal nodes it is the node number of a
151024 **      child page.
151025 */
151026 
151027 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
151028 
151029 #ifndef SQLITE_CORE
151030   SQLITE_EXTENSION_INIT1
151031 #else
151032 #endif
151033 
151034 /* #include <string.h> */
151035 /* #include <assert.h> */
151036 /* #include <stdio.h> */
151037 
151038 #ifndef SQLITE_AMALGAMATION
151039 #include "sqlite3rtree.h"
151040 typedef sqlite3_int64 i64;
151041 typedef unsigned char u8;
151042 typedef unsigned short u16;
151043 typedef unsigned int u32;
151044 #endif
151045 
151046 /*  The following macro is used to suppress compiler warnings.
151047 */
151048 #ifndef UNUSED_PARAMETER
151049 # define UNUSED_PARAMETER(x) (void)(x)
151050 #endif
151051 
151052 typedef struct Rtree Rtree;
151053 typedef struct RtreeCursor RtreeCursor;
151054 typedef struct RtreeNode RtreeNode;
151055 typedef struct RtreeCell RtreeCell;
151056 typedef struct RtreeConstraint RtreeConstraint;
151057 typedef struct RtreeMatchArg RtreeMatchArg;
151058 typedef struct RtreeGeomCallback RtreeGeomCallback;
151059 typedef union RtreeCoord RtreeCoord;
151060 typedef struct RtreeSearchPoint RtreeSearchPoint;
151061 
151062 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
151063 #define RTREE_MAX_DIMENSIONS 5
151064 
151065 /* Size of hash table Rtree.aHash. This hash table is not expected to
151066 ** ever contain very many entries, so a fixed number of buckets is
151067 ** used.
151068 */
151069 #define HASHSIZE 97
151070 
151071 /* The xBestIndex method of this virtual table requires an estimate of
151072 ** the number of rows in the virtual table to calculate the costs of
151073 ** various strategies. If possible, this estimate is loaded from the
151074 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
151075 ** Otherwise, if no sqlite_stat1 entry is available, use
151076 ** RTREE_DEFAULT_ROWEST.
151077 */
151078 #define RTREE_DEFAULT_ROWEST 1048576
151079 #define RTREE_MIN_ROWEST         100
151080 
151081 /*
151082 ** An rtree virtual-table object.
151083 */
151084 struct Rtree {
151085   sqlite3_vtab base;          /* Base class.  Must be first */
151086   sqlite3 *db;                /* Host database connection */
151087   int iNodeSize;              /* Size in bytes of each node in the node table */
151088   u8 nDim;                    /* Number of dimensions */
151089   u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
151090   u8 nBytesPerCell;           /* Bytes consumed per cell */
151091   int iDepth;                 /* Current depth of the r-tree structure */
151092   char *zDb;                  /* Name of database containing r-tree table */
151093   char *zName;                /* Name of r-tree table */
151094   int nBusy;                  /* Current number of users of this structure */
151095   i64 nRowEst;                /* Estimated number of rows in this table */
151096 
151097   /* List of nodes removed during a CondenseTree operation. List is
151098   ** linked together via the pointer normally used for hash chains -
151099   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
151100   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
151101   */
151102   RtreeNode *pDeleted;
151103   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
151104 
151105   /* Statements to read/write/delete a record from xxx_node */
151106   sqlite3_stmt *pReadNode;
151107   sqlite3_stmt *pWriteNode;
151108   sqlite3_stmt *pDeleteNode;
151109 
151110   /* Statements to read/write/delete a record from xxx_rowid */
151111   sqlite3_stmt *pReadRowid;
151112   sqlite3_stmt *pWriteRowid;
151113   sqlite3_stmt *pDeleteRowid;
151114 
151115   /* Statements to read/write/delete a record from xxx_parent */
151116   sqlite3_stmt *pReadParent;
151117   sqlite3_stmt *pWriteParent;
151118   sqlite3_stmt *pDeleteParent;
151119 
151120   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
151121 };
151122 
151123 /* Possible values for Rtree.eCoordType: */
151124 #define RTREE_COORD_REAL32 0
151125 #define RTREE_COORD_INT32  1
151126 
151127 /*
151128 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
151129 ** only deal with integer coordinates.  No floating point operations
151130 ** will be done.
151131 */
151132 #ifdef SQLITE_RTREE_INT_ONLY
151133   typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
151134   typedef int RtreeValue;                  /* Low accuracy coordinate */
151135 # define RTREE_ZERO 0
151136 #else
151137   typedef double RtreeDValue;              /* High accuracy coordinate */
151138   typedef float RtreeValue;                /* Low accuracy coordinate */
151139 # define RTREE_ZERO 0.0
151140 #endif
151141 
151142 /*
151143 ** When doing a search of an r-tree, instances of the following structure
151144 ** record intermediate results from the tree walk.
151145 **
151146 ** The id is always a node-id.  For iLevel>=1 the id is the node-id of
151147 ** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
151148 ** the id is of the parent node and the cell that RtreeSearchPoint
151149 ** represents is the iCell-th entry in the parent node.
151150 */
151151 struct RtreeSearchPoint {
151152   RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
151153   sqlite3_int64 id;      /* Node ID */
151154   u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
151155   u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
151156   u8 iCell;              /* Cell index within the node */
151157 };
151158 
151159 /*
151160 ** The minimum number of cells allowed for a node is a third of the
151161 ** maximum. In Gutman's notation:
151162 **
151163 **     m = M/3
151164 **
151165 ** If an R*-tree "Reinsert" operation is required, the same number of
151166 ** cells are removed from the overfull node and reinserted into the tree.
151167 */
151168 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
151169 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
151170 #define RTREE_MAXCELLS 51
151171 
151172 /*
151173 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
151174 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
151175 ** Therefore all non-root nodes must contain at least 3 entries. Since
151176 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
151177 ** 40 or less.
151178 */
151179 #define RTREE_MAX_DEPTH 40
151180 
151181 
151182 /*
151183 ** Number of entries in the cursor RtreeNode cache.  The first entry is
151184 ** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
151185 ** entries cache the RtreeNode for the first elements of the priority queue.
151186 */
151187 #define RTREE_CACHE_SZ  5
151188 
151189 /*
151190 ** An rtree cursor object.
151191 */
151192 struct RtreeCursor {
151193   sqlite3_vtab_cursor base;         /* Base class.  Must be first */
151194   u8 atEOF;                         /* True if at end of search */
151195   u8 bPoint;                        /* True if sPoint is valid */
151196   int iStrategy;                    /* Copy of idxNum search parameter */
151197   int nConstraint;                  /* Number of entries in aConstraint */
151198   RtreeConstraint *aConstraint;     /* Search constraints. */
151199   int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
151200   int nPoint;                       /* Number of slots used in aPoint[] */
151201   int mxLevel;                      /* iLevel value for root of the tree */
151202   RtreeSearchPoint *aPoint;         /* Priority queue for search points */
151203   RtreeSearchPoint sPoint;          /* Cached next search point */
151204   RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
151205   u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
151206 };
151207 
151208 /* Return the Rtree of a RtreeCursor */
151209 #define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
151210 
151211 /*
151212 ** A coordinate can be either a floating point number or a integer.  All
151213 ** coordinates within a single R-Tree are always of the same time.
151214 */
151215 union RtreeCoord {
151216   RtreeValue f;      /* Floating point value */
151217   int i;             /* Integer value */
151218   u32 u;             /* Unsigned for byte-order conversions */
151219 };
151220 
151221 /*
151222 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
151223 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
151224 ** variable pRtree points to the Rtree structure associated with the
151225 ** RtreeCoord.
151226 */
151227 #ifdef SQLITE_RTREE_INT_ONLY
151228 # define DCOORD(coord) ((RtreeDValue)coord.i)
151229 #else
151230 # define DCOORD(coord) (                           \
151231     (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
151232       ((double)coord.f) :                           \
151233       ((double)coord.i)                             \
151234   )
151235 #endif
151236 
151237 /*
151238 ** A search constraint.
151239 */
151240 struct RtreeConstraint {
151241   int iCoord;                     /* Index of constrained coordinate */
151242   int op;                         /* Constraining operation */
151243   union {
151244     RtreeDValue rValue;             /* Constraint value. */
151245     int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
151246     int (*xQueryFunc)(sqlite3_rtree_query_info*);
151247   } u;
151248   sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
151249 };
151250 
151251 /* Possible values for RtreeConstraint.op */
151252 #define RTREE_EQ    0x41  /* A */
151253 #define RTREE_LE    0x42  /* B */
151254 #define RTREE_LT    0x43  /* C */
151255 #define RTREE_GE    0x44  /* D */
151256 #define RTREE_GT    0x45  /* E */
151257 #define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
151258 #define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
151259 
151260 
151261 /*
151262 ** An rtree structure node.
151263 */
151264 struct RtreeNode {
151265   RtreeNode *pParent;         /* Parent node */
151266   i64 iNode;                  /* The node number */
151267   int nRef;                   /* Number of references to this node */
151268   int isDirty;                /* True if the node needs to be written to disk */
151269   u8 *zData;                  /* Content of the node, as should be on disk */
151270   RtreeNode *pNext;           /* Next node in this hash collision chain */
151271 };
151272 
151273 /* Return the number of cells in a node  */
151274 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
151275 
151276 /*
151277 ** A single cell from a node, deserialized
151278 */
151279 struct RtreeCell {
151280   i64 iRowid;                                 /* Node or entry ID */
151281   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
151282 };
151283 
151284 
151285 /*
151286 ** This object becomes the sqlite3_user_data() for the SQL functions
151287 ** that are created by sqlite3_rtree_geometry_callback() and
151288 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
151289 ** operators in order to constrain a search.
151290 **
151291 ** xGeom and xQueryFunc are the callback functions.  Exactly one of
151292 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
151293 ** SQL function was created using sqlite3_rtree_geometry_callback() or
151294 ** sqlite3_rtree_query_callback().
151295 **
151296 ** This object is deleted automatically by the destructor mechanism in
151297 ** sqlite3_create_function_v2().
151298 */
151299 struct RtreeGeomCallback {
151300   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
151301   int (*xQueryFunc)(sqlite3_rtree_query_info*);
151302   void (*xDestructor)(void*);
151303   void *pContext;
151304 };
151305 
151306 
151307 /*
151308 ** Value for the first field of every RtreeMatchArg object. The MATCH
151309 ** operator tests that the first field of a blob operand matches this
151310 ** value to avoid operating on invalid blobs (which could cause a segfault).
151311 */
151312 #define RTREE_GEOMETRY_MAGIC 0x891245AB
151313 
151314 /*
151315 ** An instance of this structure (in the form of a BLOB) is returned by
151316 ** the SQL functions that sqlite3_rtree_geometry_callback() and
151317 ** sqlite3_rtree_query_callback() create, and is read as the right-hand
151318 ** operand to the MATCH operator of an R-Tree.
151319 */
151320 struct RtreeMatchArg {
151321   u32 magic;                  /* Always RTREE_GEOMETRY_MAGIC */
151322   RtreeGeomCallback cb;       /* Info about the callback functions */
151323   int nParam;                 /* Number of parameters to the SQL function */
151324   RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
151325 };
151326 
151327 #ifndef MAX
151328 # define MAX(x,y) ((x) < (y) ? (y) : (x))
151329 #endif
151330 #ifndef MIN
151331 # define MIN(x,y) ((x) > (y) ? (y) : (x))
151332 #endif
151333 
151334 /*
151335 ** Functions to deserialize a 16 bit integer, 32 bit real number and
151336 ** 64 bit integer. The deserialized value is returned.
151337 */
151338 static int readInt16(u8 *p){
151339   return (p[0]<<8) + p[1];
151340 }
151341 static void readCoord(u8 *p, RtreeCoord *pCoord){
151342   pCoord->u = (
151343     (((u32)p[0]) << 24) +
151344     (((u32)p[1]) << 16) +
151345     (((u32)p[2]) <<  8) +
151346     (((u32)p[3]) <<  0)
151347   );
151348 }
151349 static i64 readInt64(u8 *p){
151350   return (
151351     (((i64)p[0]) << 56) +
151352     (((i64)p[1]) << 48) +
151353     (((i64)p[2]) << 40) +
151354     (((i64)p[3]) << 32) +
151355     (((i64)p[4]) << 24) +
151356     (((i64)p[5]) << 16) +
151357     (((i64)p[6]) <<  8) +
151358     (((i64)p[7]) <<  0)
151359   );
151360 }
151361 
151362 /*
151363 ** Functions to serialize a 16 bit integer, 32 bit real number and
151364 ** 64 bit integer. The value returned is the number of bytes written
151365 ** to the argument buffer (always 2, 4 and 8 respectively).
151366 */
151367 static int writeInt16(u8 *p, int i){
151368   p[0] = (i>> 8)&0xFF;
151369   p[1] = (i>> 0)&0xFF;
151370   return 2;
151371 }
151372 static int writeCoord(u8 *p, RtreeCoord *pCoord){
151373   u32 i;
151374   assert( sizeof(RtreeCoord)==4 );
151375   assert( sizeof(u32)==4 );
151376   i = pCoord->u;
151377   p[0] = (i>>24)&0xFF;
151378   p[1] = (i>>16)&0xFF;
151379   p[2] = (i>> 8)&0xFF;
151380   p[3] = (i>> 0)&0xFF;
151381   return 4;
151382 }
151383 static int writeInt64(u8 *p, i64 i){
151384   p[0] = (i>>56)&0xFF;
151385   p[1] = (i>>48)&0xFF;
151386   p[2] = (i>>40)&0xFF;
151387   p[3] = (i>>32)&0xFF;
151388   p[4] = (i>>24)&0xFF;
151389   p[5] = (i>>16)&0xFF;
151390   p[6] = (i>> 8)&0xFF;
151391   p[7] = (i>> 0)&0xFF;
151392   return 8;
151393 }
151394 
151395 /*
151396 ** Increment the reference count of node p.
151397 */
151398 static void nodeReference(RtreeNode *p){
151399   if( p ){
151400     p->nRef++;
151401   }
151402 }
151403 
151404 /*
151405 ** Clear the content of node p (set all bytes to 0x00).
151406 */
151407 static void nodeZero(Rtree *pRtree, RtreeNode *p){
151408   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
151409   p->isDirty = 1;
151410 }
151411 
151412 /*
151413 ** Given a node number iNode, return the corresponding key to use
151414 ** in the Rtree.aHash table.
151415 */
151416 static int nodeHash(i64 iNode){
151417   return iNode % HASHSIZE;
151418 }
151419 
151420 /*
151421 ** Search the node hash table for node iNode. If found, return a pointer
151422 ** to it. Otherwise, return 0.
151423 */
151424 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
151425   RtreeNode *p;
151426   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
151427   return p;
151428 }
151429 
151430 /*
151431 ** Add node pNode to the node hash table.
151432 */
151433 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
151434   int iHash;
151435   assert( pNode->pNext==0 );
151436   iHash = nodeHash(pNode->iNode);
151437   pNode->pNext = pRtree->aHash[iHash];
151438   pRtree->aHash[iHash] = pNode;
151439 }
151440 
151441 /*
151442 ** Remove node pNode from the node hash table.
151443 */
151444 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
151445   RtreeNode **pp;
151446   if( pNode->iNode!=0 ){
151447     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
151448     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
151449     *pp = pNode->pNext;
151450     pNode->pNext = 0;
151451   }
151452 }
151453 
151454 /*
151455 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
151456 ** indicating that node has not yet been assigned a node number. It is
151457 ** assigned a node number when nodeWrite() is called to write the
151458 ** node contents out to the database.
151459 */
151460 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
151461   RtreeNode *pNode;
151462   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
151463   if( pNode ){
151464     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
151465     pNode->zData = (u8 *)&pNode[1];
151466     pNode->nRef = 1;
151467     pNode->pParent = pParent;
151468     pNode->isDirty = 1;
151469     nodeReference(pParent);
151470   }
151471   return pNode;
151472 }
151473 
151474 /*
151475 ** Obtain a reference to an r-tree node.
151476 */
151477 static int nodeAcquire(
151478   Rtree *pRtree,             /* R-tree structure */
151479   i64 iNode,                 /* Node number to load */
151480   RtreeNode *pParent,        /* Either the parent node or NULL */
151481   RtreeNode **ppNode         /* OUT: Acquired node */
151482 ){
151483   int rc;
151484   int rc2 = SQLITE_OK;
151485   RtreeNode *pNode;
151486 
151487   /* Check if the requested node is already in the hash table. If so,
151488   ** increase its reference count and return it.
151489   */
151490   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
151491     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
151492     if( pParent && !pNode->pParent ){
151493       nodeReference(pParent);
151494       pNode->pParent = pParent;
151495     }
151496     pNode->nRef++;
151497     *ppNode = pNode;
151498     return SQLITE_OK;
151499   }
151500 
151501   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
151502   rc = sqlite3_step(pRtree->pReadNode);
151503   if( rc==SQLITE_ROW ){
151504     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
151505     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
151506       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
151507       if( !pNode ){
151508         rc2 = SQLITE_NOMEM;
151509       }else{
151510         pNode->pParent = pParent;
151511         pNode->zData = (u8 *)&pNode[1];
151512         pNode->nRef = 1;
151513         pNode->iNode = iNode;
151514         pNode->isDirty = 0;
151515         pNode->pNext = 0;
151516         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
151517         nodeReference(pParent);
151518       }
151519     }
151520   }
151521   rc = sqlite3_reset(pRtree->pReadNode);
151522   if( rc==SQLITE_OK ) rc = rc2;
151523 
151524   /* If the root node was just loaded, set pRtree->iDepth to the height
151525   ** of the r-tree structure. A height of zero means all data is stored on
151526   ** the root node. A height of one means the children of the root node
151527   ** are the leaves, and so on. If the depth as specified on the root node
151528   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
151529   */
151530   if( pNode && iNode==1 ){
151531     pRtree->iDepth = readInt16(pNode->zData);
151532     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
151533       rc = SQLITE_CORRUPT_VTAB;
151534     }
151535   }
151536 
151537   /* If no error has occurred so far, check if the "number of entries"
151538   ** field on the node is too large. If so, set the return code to
151539   ** SQLITE_CORRUPT_VTAB.
151540   */
151541   if( pNode && rc==SQLITE_OK ){
151542     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
151543       rc = SQLITE_CORRUPT_VTAB;
151544     }
151545   }
151546 
151547   if( rc==SQLITE_OK ){
151548     if( pNode!=0 ){
151549       nodeHashInsert(pRtree, pNode);
151550     }else{
151551       rc = SQLITE_CORRUPT_VTAB;
151552     }
151553     *ppNode = pNode;
151554   }else{
151555     sqlite3_free(pNode);
151556     *ppNode = 0;
151557   }
151558 
151559   return rc;
151560 }
151561 
151562 /*
151563 ** Overwrite cell iCell of node pNode with the contents of pCell.
151564 */
151565 static void nodeOverwriteCell(
151566   Rtree *pRtree,             /* The overall R-Tree */
151567   RtreeNode *pNode,          /* The node into which the cell is to be written */
151568   RtreeCell *pCell,          /* The cell to write */
151569   int iCell                  /* Index into pNode into which pCell is written */
151570 ){
151571   int ii;
151572   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
151573   p += writeInt64(p, pCell->iRowid);
151574   for(ii=0; ii<(pRtree->nDim*2); ii++){
151575     p += writeCoord(p, &pCell->aCoord[ii]);
151576   }
151577   pNode->isDirty = 1;
151578 }
151579 
151580 /*
151581 ** Remove the cell with index iCell from node pNode.
151582 */
151583 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
151584   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
151585   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
151586   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
151587   memmove(pDst, pSrc, nByte);
151588   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
151589   pNode->isDirty = 1;
151590 }
151591 
151592 /*
151593 ** Insert the contents of cell pCell into node pNode. If the insert
151594 ** is successful, return SQLITE_OK.
151595 **
151596 ** If there is not enough free space in pNode, return SQLITE_FULL.
151597 */
151598 static int nodeInsertCell(
151599   Rtree *pRtree,                /* The overall R-Tree */
151600   RtreeNode *pNode,             /* Write new cell into this node */
151601   RtreeCell *pCell              /* The cell to be inserted */
151602 ){
151603   int nCell;                    /* Current number of cells in pNode */
151604   int nMaxCell;                 /* Maximum number of cells for pNode */
151605 
151606   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
151607   nCell = NCELL(pNode);
151608 
151609   assert( nCell<=nMaxCell );
151610   if( nCell<nMaxCell ){
151611     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
151612     writeInt16(&pNode->zData[2], nCell+1);
151613     pNode->isDirty = 1;
151614   }
151615 
151616   return (nCell==nMaxCell);
151617 }
151618 
151619 /*
151620 ** If the node is dirty, write it out to the database.
151621 */
151622 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
151623   int rc = SQLITE_OK;
151624   if( pNode->isDirty ){
151625     sqlite3_stmt *p = pRtree->pWriteNode;
151626     if( pNode->iNode ){
151627       sqlite3_bind_int64(p, 1, pNode->iNode);
151628     }else{
151629       sqlite3_bind_null(p, 1);
151630     }
151631     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
151632     sqlite3_step(p);
151633     pNode->isDirty = 0;
151634     rc = sqlite3_reset(p);
151635     if( pNode->iNode==0 && rc==SQLITE_OK ){
151636       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
151637       nodeHashInsert(pRtree, pNode);
151638     }
151639   }
151640   return rc;
151641 }
151642 
151643 /*
151644 ** Release a reference to a node. If the node is dirty and the reference
151645 ** count drops to zero, the node data is written to the database.
151646 */
151647 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
151648   int rc = SQLITE_OK;
151649   if( pNode ){
151650     assert( pNode->nRef>0 );
151651     pNode->nRef--;
151652     if( pNode->nRef==0 ){
151653       if( pNode->iNode==1 ){
151654         pRtree->iDepth = -1;
151655       }
151656       if( pNode->pParent ){
151657         rc = nodeRelease(pRtree, pNode->pParent);
151658       }
151659       if( rc==SQLITE_OK ){
151660         rc = nodeWrite(pRtree, pNode);
151661       }
151662       nodeHashDelete(pRtree, pNode);
151663       sqlite3_free(pNode);
151664     }
151665   }
151666   return rc;
151667 }
151668 
151669 /*
151670 ** Return the 64-bit integer value associated with cell iCell of
151671 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
151672 ** an internal node, then the 64-bit integer is a child page number.
151673 */
151674 static i64 nodeGetRowid(
151675   Rtree *pRtree,       /* The overall R-Tree */
151676   RtreeNode *pNode,    /* The node from which to extract the ID */
151677   int iCell            /* The cell index from which to extract the ID */
151678 ){
151679   assert( iCell<NCELL(pNode) );
151680   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
151681 }
151682 
151683 /*
151684 ** Return coordinate iCoord from cell iCell in node pNode.
151685 */
151686 static void nodeGetCoord(
151687   Rtree *pRtree,               /* The overall R-Tree */
151688   RtreeNode *pNode,            /* The node from which to extract a coordinate */
151689   int iCell,                   /* The index of the cell within the node */
151690   int iCoord,                  /* Which coordinate to extract */
151691   RtreeCoord *pCoord           /* OUT: Space to write result to */
151692 ){
151693   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
151694 }
151695 
151696 /*
151697 ** Deserialize cell iCell of node pNode. Populate the structure pointed
151698 ** to by pCell with the results.
151699 */
151700 static void nodeGetCell(
151701   Rtree *pRtree,               /* The overall R-Tree */
151702   RtreeNode *pNode,            /* The node containing the cell to be read */
151703   int iCell,                   /* Index of the cell within the node */
151704   RtreeCell *pCell             /* OUT: Write the cell contents here */
151705 ){
151706   u8 *pData;
151707   RtreeCoord *pCoord;
151708   int ii;
151709   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
151710   pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
151711   pCoord = pCell->aCoord;
151712   for(ii=0; ii<pRtree->nDim*2; ii++){
151713     readCoord(&pData[ii*4], &pCoord[ii]);
151714   }
151715 }
151716 
151717 
151718 /* Forward declaration for the function that does the work of
151719 ** the virtual table module xCreate() and xConnect() methods.
151720 */
151721 static int rtreeInit(
151722   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
151723 );
151724 
151725 /*
151726 ** Rtree virtual table module xCreate method.
151727 */
151728 static int rtreeCreate(
151729   sqlite3 *db,
151730   void *pAux,
151731   int argc, const char *const*argv,
151732   sqlite3_vtab **ppVtab,
151733   char **pzErr
151734 ){
151735   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
151736 }
151737 
151738 /*
151739 ** Rtree virtual table module xConnect method.
151740 */
151741 static int rtreeConnect(
151742   sqlite3 *db,
151743   void *pAux,
151744   int argc, const char *const*argv,
151745   sqlite3_vtab **ppVtab,
151746   char **pzErr
151747 ){
151748   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
151749 }
151750 
151751 /*
151752 ** Increment the r-tree reference count.
151753 */
151754 static void rtreeReference(Rtree *pRtree){
151755   pRtree->nBusy++;
151756 }
151757 
151758 /*
151759 ** Decrement the r-tree reference count. When the reference count reaches
151760 ** zero the structure is deleted.
151761 */
151762 static void rtreeRelease(Rtree *pRtree){
151763   pRtree->nBusy--;
151764   if( pRtree->nBusy==0 ){
151765     sqlite3_finalize(pRtree->pReadNode);
151766     sqlite3_finalize(pRtree->pWriteNode);
151767     sqlite3_finalize(pRtree->pDeleteNode);
151768     sqlite3_finalize(pRtree->pReadRowid);
151769     sqlite3_finalize(pRtree->pWriteRowid);
151770     sqlite3_finalize(pRtree->pDeleteRowid);
151771     sqlite3_finalize(pRtree->pReadParent);
151772     sqlite3_finalize(pRtree->pWriteParent);
151773     sqlite3_finalize(pRtree->pDeleteParent);
151774     sqlite3_free(pRtree);
151775   }
151776 }
151777 
151778 /*
151779 ** Rtree virtual table module xDisconnect method.
151780 */
151781 static int rtreeDisconnect(sqlite3_vtab *pVtab){
151782   rtreeRelease((Rtree *)pVtab);
151783   return SQLITE_OK;
151784 }
151785 
151786 /*
151787 ** Rtree virtual table module xDestroy method.
151788 */
151789 static int rtreeDestroy(sqlite3_vtab *pVtab){
151790   Rtree *pRtree = (Rtree *)pVtab;
151791   int rc;
151792   char *zCreate = sqlite3_mprintf(
151793     "DROP TABLE '%q'.'%q_node';"
151794     "DROP TABLE '%q'.'%q_rowid';"
151795     "DROP TABLE '%q'.'%q_parent';",
151796     pRtree->zDb, pRtree->zName,
151797     pRtree->zDb, pRtree->zName,
151798     pRtree->zDb, pRtree->zName
151799   );
151800   if( !zCreate ){
151801     rc = SQLITE_NOMEM;
151802   }else{
151803     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
151804     sqlite3_free(zCreate);
151805   }
151806   if( rc==SQLITE_OK ){
151807     rtreeRelease(pRtree);
151808   }
151809 
151810   return rc;
151811 }
151812 
151813 /*
151814 ** Rtree virtual table module xOpen method.
151815 */
151816 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
151817   int rc = SQLITE_NOMEM;
151818   RtreeCursor *pCsr;
151819 
151820   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
151821   if( pCsr ){
151822     memset(pCsr, 0, sizeof(RtreeCursor));
151823     pCsr->base.pVtab = pVTab;
151824     rc = SQLITE_OK;
151825   }
151826   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
151827 
151828   return rc;
151829 }
151830 
151831 
151832 /*
151833 ** Free the RtreeCursor.aConstraint[] array and its contents.
151834 */
151835 static void freeCursorConstraints(RtreeCursor *pCsr){
151836   if( pCsr->aConstraint ){
151837     int i;                        /* Used to iterate through constraint array */
151838     for(i=0; i<pCsr->nConstraint; i++){
151839       sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
151840       if( pInfo ){
151841         if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
151842         sqlite3_free(pInfo);
151843       }
151844     }
151845     sqlite3_free(pCsr->aConstraint);
151846     pCsr->aConstraint = 0;
151847   }
151848 }
151849 
151850 /*
151851 ** Rtree virtual table module xClose method.
151852 */
151853 static int rtreeClose(sqlite3_vtab_cursor *cur){
151854   Rtree *pRtree = (Rtree *)(cur->pVtab);
151855   int ii;
151856   RtreeCursor *pCsr = (RtreeCursor *)cur;
151857   freeCursorConstraints(pCsr);
151858   sqlite3_free(pCsr->aPoint);
151859   for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
151860   sqlite3_free(pCsr);
151861   return SQLITE_OK;
151862 }
151863 
151864 /*
151865 ** Rtree virtual table module xEof method.
151866 **
151867 ** Return non-zero if the cursor does not currently point to a valid
151868 ** record (i.e if the scan has finished), or zero otherwise.
151869 */
151870 static int rtreeEof(sqlite3_vtab_cursor *cur){
151871   RtreeCursor *pCsr = (RtreeCursor *)cur;
151872   return pCsr->atEOF;
151873 }
151874 
151875 /*
151876 ** Convert raw bits from the on-disk RTree record into a coordinate value.
151877 ** The on-disk format is big-endian and needs to be converted for little-
151878 ** endian platforms.  The on-disk record stores integer coordinates if
151879 ** eInt is true and it stores 32-bit floating point records if eInt is
151880 ** false.  a[] is the four bytes of the on-disk record to be decoded.
151881 ** Store the results in "r".
151882 **
151883 ** There are three versions of this macro, one each for little-endian and
151884 ** big-endian processors and a third generic implementation.  The endian-
151885 ** specific implementations are much faster and are preferred if the
151886 ** processor endianness is known at compile-time.  The SQLITE_BYTEORDER
151887 ** macro is part of sqliteInt.h and hence the endian-specific
151888 ** implementation will only be used if this module is compiled as part
151889 ** of the amalgamation.
151890 */
151891 #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
151892 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
151893     RtreeCoord c;    /* Coordinate decoded */                   \
151894     memcpy(&c.u,a,4);                                           \
151895     c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
151896           ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
151897     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
151898 }
151899 #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
151900 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
151901     RtreeCoord c;    /* Coordinate decoded */                   \
151902     memcpy(&c.u,a,4);                                           \
151903     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
151904 }
151905 #else
151906 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
151907     RtreeCoord c;    /* Coordinate decoded */                   \
151908     c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
151909            +((u32)a[2]<<8) + a[3];                              \
151910     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
151911 }
151912 #endif
151913 
151914 /*
151915 ** Check the RTree node or entry given by pCellData and p against the MATCH
151916 ** constraint pConstraint.
151917 */
151918 static int rtreeCallbackConstraint(
151919   RtreeConstraint *pConstraint,  /* The constraint to test */
151920   int eInt,                      /* True if RTree holding integer coordinates */
151921   u8 *pCellData,                 /* Raw cell content */
151922   RtreeSearchPoint *pSearch,     /* Container of this cell */
151923   sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
151924   int *peWithin                  /* OUT: visibility of the cell */
151925 ){
151926   int i;                                                /* Loop counter */
151927   sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
151928   int nCoord = pInfo->nCoord;                           /* No. of coordinates */
151929   int rc;                                             /* Callback return code */
151930   sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
151931 
151932   assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
151933   assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
151934 
151935   if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
151936     pInfo->iRowid = readInt64(pCellData);
151937   }
151938   pCellData += 8;
151939   for(i=0; i<nCoord; i++, pCellData += 4){
151940     RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
151941   }
151942   if( pConstraint->op==RTREE_MATCH ){
151943     rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
151944                               nCoord, aCoord, &i);
151945     if( i==0 ) *peWithin = NOT_WITHIN;
151946     *prScore = RTREE_ZERO;
151947   }else{
151948     pInfo->aCoord = aCoord;
151949     pInfo->iLevel = pSearch->iLevel - 1;
151950     pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
151951     pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
151952     rc = pConstraint->u.xQueryFunc(pInfo);
151953     if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
151954     if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
151955       *prScore = pInfo->rScore;
151956     }
151957   }
151958   return rc;
151959 }
151960 
151961 /*
151962 ** Check the internal RTree node given by pCellData against constraint p.
151963 ** If this constraint cannot be satisfied by any child within the node,
151964 ** set *peWithin to NOT_WITHIN.
151965 */
151966 static void rtreeNonleafConstraint(
151967   RtreeConstraint *p,        /* The constraint to test */
151968   int eInt,                  /* True if RTree holds integer coordinates */
151969   u8 *pCellData,             /* Raw cell content as appears on disk */
151970   int *peWithin              /* Adjust downward, as appropriate */
151971 ){
151972   sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
151973 
151974   /* p->iCoord might point to either a lower or upper bound coordinate
151975   ** in a coordinate pair.  But make pCellData point to the lower bound.
151976   */
151977   pCellData += 8 + 4*(p->iCoord&0xfe);
151978 
151979   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
151980       || p->op==RTREE_GT || p->op==RTREE_EQ );
151981   switch( p->op ){
151982     case RTREE_LE:
151983     case RTREE_LT:
151984     case RTREE_EQ:
151985       RTREE_DECODE_COORD(eInt, pCellData, val);
151986       /* val now holds the lower bound of the coordinate pair */
151987       if( p->u.rValue>=val ) return;
151988       if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
151989       /* Fall through for the RTREE_EQ case */
151990 
151991     default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
151992       pCellData += 4;
151993       RTREE_DECODE_COORD(eInt, pCellData, val);
151994       /* val now holds the upper bound of the coordinate pair */
151995       if( p->u.rValue<=val ) return;
151996   }
151997   *peWithin = NOT_WITHIN;
151998 }
151999 
152000 /*
152001 ** Check the leaf RTree cell given by pCellData against constraint p.
152002 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
152003 ** If the constraint is satisfied, leave *peWithin unchanged.
152004 **
152005 ** The constraint is of the form:  xN op $val
152006 **
152007 ** The op is given by p->op.  The xN is p->iCoord-th coordinate in
152008 ** pCellData.  $val is given by p->u.rValue.
152009 */
152010 static void rtreeLeafConstraint(
152011   RtreeConstraint *p,        /* The constraint to test */
152012   int eInt,                  /* True if RTree holds integer coordinates */
152013   u8 *pCellData,             /* Raw cell content as appears on disk */
152014   int *peWithin              /* Adjust downward, as appropriate */
152015 ){
152016   RtreeDValue xN;      /* Coordinate value converted to a double */
152017 
152018   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
152019       || p->op==RTREE_GT || p->op==RTREE_EQ );
152020   pCellData += 8 + p->iCoord*4;
152021   RTREE_DECODE_COORD(eInt, pCellData, xN);
152022   switch( p->op ){
152023     case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
152024     case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
152025     case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
152026     case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
152027     default:       if( xN == p->u.rValue ) return;  break;
152028   }
152029   *peWithin = NOT_WITHIN;
152030 }
152031 
152032 /*
152033 ** One of the cells in node pNode is guaranteed to have a 64-bit
152034 ** integer value equal to iRowid. Return the index of this cell.
152035 */
152036 static int nodeRowidIndex(
152037   Rtree *pRtree,
152038   RtreeNode *pNode,
152039   i64 iRowid,
152040   int *piIndex
152041 ){
152042   int ii;
152043   int nCell = NCELL(pNode);
152044   assert( nCell<200 );
152045   for(ii=0; ii<nCell; ii++){
152046     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
152047       *piIndex = ii;
152048       return SQLITE_OK;
152049     }
152050   }
152051   return SQLITE_CORRUPT_VTAB;
152052 }
152053 
152054 /*
152055 ** Return the index of the cell containing a pointer to node pNode
152056 ** in its parent. If pNode is the root node, return -1.
152057 */
152058 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
152059   RtreeNode *pParent = pNode->pParent;
152060   if( pParent ){
152061     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
152062   }
152063   *piIndex = -1;
152064   return SQLITE_OK;
152065 }
152066 
152067 /*
152068 ** Compare two search points.  Return negative, zero, or positive if the first
152069 ** is less than, equal to, or greater than the second.
152070 **
152071 ** The rScore is the primary key.  Smaller rScore values come first.
152072 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
152073 ** iLevel values coming first.  In this way, if rScore is the same for all
152074 ** SearchPoints, then iLevel becomes the deciding factor and the result
152075 ** is a depth-first search, which is the desired default behavior.
152076 */
152077 static int rtreeSearchPointCompare(
152078   const RtreeSearchPoint *pA,
152079   const RtreeSearchPoint *pB
152080 ){
152081   if( pA->rScore<pB->rScore ) return -1;
152082   if( pA->rScore>pB->rScore ) return +1;
152083   if( pA->iLevel<pB->iLevel ) return -1;
152084   if( pA->iLevel>pB->iLevel ) return +1;
152085   return 0;
152086 }
152087 
152088 /*
152089 ** Interchange to search points in a cursor.
152090 */
152091 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
152092   RtreeSearchPoint t = p->aPoint[i];
152093   assert( i<j );
152094   p->aPoint[i] = p->aPoint[j];
152095   p->aPoint[j] = t;
152096   i++; j++;
152097   if( i<RTREE_CACHE_SZ ){
152098     if( j>=RTREE_CACHE_SZ ){
152099       nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
152100       p->aNode[i] = 0;
152101     }else{
152102       RtreeNode *pTemp = p->aNode[i];
152103       p->aNode[i] = p->aNode[j];
152104       p->aNode[j] = pTemp;
152105     }
152106   }
152107 }
152108 
152109 /*
152110 ** Return the search point with the lowest current score.
152111 */
152112 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
152113   return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
152114 }
152115 
152116 /*
152117 ** Get the RtreeNode for the search point with the lowest score.
152118 */
152119 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
152120   sqlite3_int64 id;
152121   int ii = 1 - pCur->bPoint;
152122   assert( ii==0 || ii==1 );
152123   assert( pCur->bPoint || pCur->nPoint );
152124   if( pCur->aNode[ii]==0 ){
152125     assert( pRC!=0 );
152126     id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
152127     *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
152128   }
152129   return pCur->aNode[ii];
152130 }
152131 
152132 /*
152133 ** Push a new element onto the priority queue
152134 */
152135 static RtreeSearchPoint *rtreeEnqueue(
152136   RtreeCursor *pCur,    /* The cursor */
152137   RtreeDValue rScore,   /* Score for the new search point */
152138   u8 iLevel             /* Level for the new search point */
152139 ){
152140   int i, j;
152141   RtreeSearchPoint *pNew;
152142   if( pCur->nPoint>=pCur->nPointAlloc ){
152143     int nNew = pCur->nPointAlloc*2 + 8;
152144     pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
152145     if( pNew==0 ) return 0;
152146     pCur->aPoint = pNew;
152147     pCur->nPointAlloc = nNew;
152148   }
152149   i = pCur->nPoint++;
152150   pNew = pCur->aPoint + i;
152151   pNew->rScore = rScore;
152152   pNew->iLevel = iLevel;
152153   assert( iLevel<=RTREE_MAX_DEPTH );
152154   while( i>0 ){
152155     RtreeSearchPoint *pParent;
152156     j = (i-1)/2;
152157     pParent = pCur->aPoint + j;
152158     if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
152159     rtreeSearchPointSwap(pCur, j, i);
152160     i = j;
152161     pNew = pParent;
152162   }
152163   return pNew;
152164 }
152165 
152166 /*
152167 ** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
152168 ** NULL if malloc fails.
152169 */
152170 static RtreeSearchPoint *rtreeSearchPointNew(
152171   RtreeCursor *pCur,    /* The cursor */
152172   RtreeDValue rScore,   /* Score for the new search point */
152173   u8 iLevel             /* Level for the new search point */
152174 ){
152175   RtreeSearchPoint *pNew, *pFirst;
152176   pFirst = rtreeSearchPointFirst(pCur);
152177   pCur->anQueue[iLevel]++;
152178   if( pFirst==0
152179    || pFirst->rScore>rScore
152180    || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
152181   ){
152182     if( pCur->bPoint ){
152183       int ii;
152184       pNew = rtreeEnqueue(pCur, rScore, iLevel);
152185       if( pNew==0 ) return 0;
152186       ii = (int)(pNew - pCur->aPoint) + 1;
152187       if( ii<RTREE_CACHE_SZ ){
152188         assert( pCur->aNode[ii]==0 );
152189         pCur->aNode[ii] = pCur->aNode[0];
152190        }else{
152191         nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
152192       }
152193       pCur->aNode[0] = 0;
152194       *pNew = pCur->sPoint;
152195     }
152196     pCur->sPoint.rScore = rScore;
152197     pCur->sPoint.iLevel = iLevel;
152198     pCur->bPoint = 1;
152199     return &pCur->sPoint;
152200   }else{
152201     return rtreeEnqueue(pCur, rScore, iLevel);
152202   }
152203 }
152204 
152205 #if 0
152206 /* Tracing routines for the RtreeSearchPoint queue */
152207 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
152208   if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
152209   printf(" %d.%05lld.%02d %g %d",
152210     p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
152211   );
152212   idx++;
152213   if( idx<RTREE_CACHE_SZ ){
152214     printf(" %p\n", pCur->aNode[idx]);
152215   }else{
152216     printf("\n");
152217   }
152218 }
152219 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
152220   int ii;
152221   printf("=== %9s ", zPrefix);
152222   if( pCur->bPoint ){
152223     tracePoint(&pCur->sPoint, -1, pCur);
152224   }
152225   for(ii=0; ii<pCur->nPoint; ii++){
152226     if( ii>0 || pCur->bPoint ) printf("              ");
152227     tracePoint(&pCur->aPoint[ii], ii, pCur);
152228   }
152229 }
152230 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
152231 #else
152232 # define RTREE_QUEUE_TRACE(A,B)   /* no-op */
152233 #endif
152234 
152235 /* Remove the search point with the lowest current score.
152236 */
152237 static void rtreeSearchPointPop(RtreeCursor *p){
152238   int i, j, k, n;
152239   i = 1 - p->bPoint;
152240   assert( i==0 || i==1 );
152241   if( p->aNode[i] ){
152242     nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
152243     p->aNode[i] = 0;
152244   }
152245   if( p->bPoint ){
152246     p->anQueue[p->sPoint.iLevel]--;
152247     p->bPoint = 0;
152248   }else if( p->nPoint ){
152249     p->anQueue[p->aPoint[0].iLevel]--;
152250     n = --p->nPoint;
152251     p->aPoint[0] = p->aPoint[n];
152252     if( n<RTREE_CACHE_SZ-1 ){
152253       p->aNode[1] = p->aNode[n+1];
152254       p->aNode[n+1] = 0;
152255     }
152256     i = 0;
152257     while( (j = i*2+1)<n ){
152258       k = j+1;
152259       if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
152260         if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
152261           rtreeSearchPointSwap(p, i, k);
152262           i = k;
152263         }else{
152264           break;
152265         }
152266       }else{
152267         if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
152268           rtreeSearchPointSwap(p, i, j);
152269           i = j;
152270         }else{
152271           break;
152272         }
152273       }
152274     }
152275   }
152276 }
152277 
152278 
152279 /*
152280 ** Continue the search on cursor pCur until the front of the queue
152281 ** contains an entry suitable for returning as a result-set row,
152282 ** or until the RtreeSearchPoint queue is empty, indicating that the
152283 ** query has completed.
152284 */
152285 static int rtreeStepToLeaf(RtreeCursor *pCur){
152286   RtreeSearchPoint *p;
152287   Rtree *pRtree = RTREE_OF_CURSOR(pCur);
152288   RtreeNode *pNode;
152289   int eWithin;
152290   int rc = SQLITE_OK;
152291   int nCell;
152292   int nConstraint = pCur->nConstraint;
152293   int ii;
152294   int eInt;
152295   RtreeSearchPoint x;
152296 
152297   eInt = pRtree->eCoordType==RTREE_COORD_INT32;
152298   while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
152299     pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
152300     if( rc ) return rc;
152301     nCell = NCELL(pNode);
152302     assert( nCell<200 );
152303     while( p->iCell<nCell ){
152304       sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
152305       u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
152306       eWithin = FULLY_WITHIN;
152307       for(ii=0; ii<nConstraint; ii++){
152308         RtreeConstraint *pConstraint = pCur->aConstraint + ii;
152309         if( pConstraint->op>=RTREE_MATCH ){
152310           rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
152311                                        &rScore, &eWithin);
152312           if( rc ) return rc;
152313         }else if( p->iLevel==1 ){
152314           rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
152315         }else{
152316           rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
152317         }
152318         if( eWithin==NOT_WITHIN ) break;
152319       }
152320       p->iCell++;
152321       if( eWithin==NOT_WITHIN ) continue;
152322       x.iLevel = p->iLevel - 1;
152323       if( x.iLevel ){
152324         x.id = readInt64(pCellData);
152325         x.iCell = 0;
152326       }else{
152327         x.id = p->id;
152328         x.iCell = p->iCell - 1;
152329       }
152330       if( p->iCell>=nCell ){
152331         RTREE_QUEUE_TRACE(pCur, "POP-S:");
152332         rtreeSearchPointPop(pCur);
152333       }
152334       if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
152335       p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
152336       if( p==0 ) return SQLITE_NOMEM;
152337       p->eWithin = eWithin;
152338       p->id = x.id;
152339       p->iCell = x.iCell;
152340       RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
152341       break;
152342     }
152343     if( p->iCell>=nCell ){
152344       RTREE_QUEUE_TRACE(pCur, "POP-Se:");
152345       rtreeSearchPointPop(pCur);
152346     }
152347   }
152348   pCur->atEOF = p==0;
152349   return SQLITE_OK;
152350 }
152351 
152352 /*
152353 ** Rtree virtual table module xNext method.
152354 */
152355 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
152356   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
152357   int rc = SQLITE_OK;
152358 
152359   /* Move to the next entry that matches the configured constraints. */
152360   RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
152361   rtreeSearchPointPop(pCsr);
152362   rc = rtreeStepToLeaf(pCsr);
152363   return rc;
152364 }
152365 
152366 /*
152367 ** Rtree virtual table module xRowid method.
152368 */
152369 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
152370   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
152371   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
152372   int rc = SQLITE_OK;
152373   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
152374   if( rc==SQLITE_OK && p ){
152375     *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
152376   }
152377   return rc;
152378 }
152379 
152380 /*
152381 ** Rtree virtual table module xColumn method.
152382 */
152383 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
152384   Rtree *pRtree = (Rtree *)cur->pVtab;
152385   RtreeCursor *pCsr = (RtreeCursor *)cur;
152386   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
152387   RtreeCoord c;
152388   int rc = SQLITE_OK;
152389   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
152390 
152391   if( rc ) return rc;
152392   if( p==0 ) return SQLITE_OK;
152393   if( i==0 ){
152394     sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
152395   }else{
152396     if( rc ) return rc;
152397     nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
152398 #ifndef SQLITE_RTREE_INT_ONLY
152399     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
152400       sqlite3_result_double(ctx, c.f);
152401     }else
152402 #endif
152403     {
152404       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
152405       sqlite3_result_int(ctx, c.i);
152406     }
152407   }
152408   return SQLITE_OK;
152409 }
152410 
152411 /*
152412 ** Use nodeAcquire() to obtain the leaf node containing the record with
152413 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
152414 ** return SQLITE_OK. If there is no such record in the table, set
152415 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
152416 ** to zero and return an SQLite error code.
152417 */
152418 static int findLeafNode(
152419   Rtree *pRtree,              /* RTree to search */
152420   i64 iRowid,                 /* The rowid searching for */
152421   RtreeNode **ppLeaf,         /* Write the node here */
152422   sqlite3_int64 *piNode       /* Write the node-id here */
152423 ){
152424   int rc;
152425   *ppLeaf = 0;
152426   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
152427   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
152428     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
152429     if( piNode ) *piNode = iNode;
152430     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
152431     sqlite3_reset(pRtree->pReadRowid);
152432   }else{
152433     rc = sqlite3_reset(pRtree->pReadRowid);
152434   }
152435   return rc;
152436 }
152437 
152438 /*
152439 ** This function is called to configure the RtreeConstraint object passed
152440 ** as the second argument for a MATCH constraint. The value passed as the
152441 ** first argument to this function is the right-hand operand to the MATCH
152442 ** operator.
152443 */
152444 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
152445   RtreeMatchArg *pBlob;              /* BLOB returned by geometry function */
152446   sqlite3_rtree_query_info *pInfo;   /* Callback information */
152447   int nBlob;                         /* Size of the geometry function blob */
152448   int nExpected;                     /* Expected size of the BLOB */
152449 
152450   /* Check that value is actually a blob. */
152451   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
152452 
152453   /* Check that the blob is roughly the right size. */
152454   nBlob = sqlite3_value_bytes(pValue);
152455   if( nBlob<(int)sizeof(RtreeMatchArg)
152456    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
152457   ){
152458     return SQLITE_ERROR;
152459   }
152460 
152461   pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
152462   if( !pInfo ) return SQLITE_NOMEM;
152463   memset(pInfo, 0, sizeof(*pInfo));
152464   pBlob = (RtreeMatchArg*)&pInfo[1];
152465 
152466   memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
152467   nExpected = (int)(sizeof(RtreeMatchArg) +
152468                     (pBlob->nParam-1)*sizeof(RtreeDValue));
152469   if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
152470     sqlite3_free(pInfo);
152471     return SQLITE_ERROR;
152472   }
152473   pInfo->pContext = pBlob->cb.pContext;
152474   pInfo->nParam = pBlob->nParam;
152475   pInfo->aParam = pBlob->aParam;
152476 
152477   if( pBlob->cb.xGeom ){
152478     pCons->u.xGeom = pBlob->cb.xGeom;
152479   }else{
152480     pCons->op = RTREE_QUERY;
152481     pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
152482   }
152483   pCons->pInfo = pInfo;
152484   return SQLITE_OK;
152485 }
152486 
152487 /*
152488 ** Rtree virtual table module xFilter method.
152489 */
152490 static int rtreeFilter(
152491   sqlite3_vtab_cursor *pVtabCursor,
152492   int idxNum, const char *idxStr,
152493   int argc, sqlite3_value **argv
152494 ){
152495   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
152496   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
152497   RtreeNode *pRoot = 0;
152498   int ii;
152499   int rc = SQLITE_OK;
152500   int iCell = 0;
152501 
152502   rtreeReference(pRtree);
152503 
152504   /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
152505   freeCursorConstraints(pCsr);
152506   sqlite3_free(pCsr->aPoint);
152507   memset(pCsr, 0, sizeof(RtreeCursor));
152508   pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
152509 
152510   pCsr->iStrategy = idxNum;
152511   if( idxNum==1 ){
152512     /* Special case - lookup by rowid. */
152513     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
152514     RtreeSearchPoint *p;     /* Search point for the the leaf */
152515     i64 iRowid = sqlite3_value_int64(argv[0]);
152516     i64 iNode = 0;
152517     rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
152518     if( rc==SQLITE_OK && pLeaf!=0 ){
152519       p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
152520       assert( p!=0 );  /* Always returns pCsr->sPoint */
152521       pCsr->aNode[0] = pLeaf;
152522       p->id = iNode;
152523       p->eWithin = PARTLY_WITHIN;
152524       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
152525       p->iCell = iCell;
152526       RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
152527     }else{
152528       pCsr->atEOF = 1;
152529     }
152530   }else{
152531     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
152532     ** with the configured constraints.
152533     */
152534     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
152535     if( rc==SQLITE_OK && argc>0 ){
152536       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
152537       pCsr->nConstraint = argc;
152538       if( !pCsr->aConstraint ){
152539         rc = SQLITE_NOMEM;
152540       }else{
152541         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
152542         memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
152543         assert( (idxStr==0 && argc==0)
152544                 || (idxStr && (int)strlen(idxStr)==argc*2) );
152545         for(ii=0; ii<argc; ii++){
152546           RtreeConstraint *p = &pCsr->aConstraint[ii];
152547           p->op = idxStr[ii*2];
152548           p->iCoord = idxStr[ii*2+1]-'0';
152549           if( p->op>=RTREE_MATCH ){
152550             /* A MATCH operator. The right-hand-side must be a blob that
152551             ** can be cast into an RtreeMatchArg object. One created using
152552             ** an sqlite3_rtree_geometry_callback() SQL user function.
152553             */
152554             rc = deserializeGeometry(argv[ii], p);
152555             if( rc!=SQLITE_OK ){
152556               break;
152557             }
152558             p->pInfo->nCoord = pRtree->nDim*2;
152559             p->pInfo->anQueue = pCsr->anQueue;
152560             p->pInfo->mxLevel = pRtree->iDepth + 1;
152561           }else{
152562 #ifdef SQLITE_RTREE_INT_ONLY
152563             p->u.rValue = sqlite3_value_int64(argv[ii]);
152564 #else
152565             p->u.rValue = sqlite3_value_double(argv[ii]);
152566 #endif
152567           }
152568         }
152569       }
152570     }
152571     if( rc==SQLITE_OK ){
152572       RtreeSearchPoint *pNew;
152573       pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
152574       if( pNew==0 ) return SQLITE_NOMEM;
152575       pNew->id = 1;
152576       pNew->iCell = 0;
152577       pNew->eWithin = PARTLY_WITHIN;
152578       assert( pCsr->bPoint==1 );
152579       pCsr->aNode[0] = pRoot;
152580       pRoot = 0;
152581       RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
152582       rc = rtreeStepToLeaf(pCsr);
152583     }
152584   }
152585 
152586   nodeRelease(pRtree, pRoot);
152587   rtreeRelease(pRtree);
152588   return rc;
152589 }
152590 
152591 /*
152592 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
152593 ** extension is currently being used by a version of SQLite too old to
152594 ** support estimatedRows. In that case this function is a no-op.
152595 */
152596 static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
152597 #if SQLITE_VERSION_NUMBER>=3008002
152598   if( sqlite3_libversion_number()>=3008002 ){
152599     pIdxInfo->estimatedRows = nRow;
152600   }
152601 #endif
152602 }
152603 
152604 /*
152605 ** Rtree virtual table module xBestIndex method. There are three
152606 ** table scan strategies to choose from (in order from most to
152607 ** least desirable):
152608 **
152609 **   idxNum     idxStr        Strategy
152610 **   ------------------------------------------------
152611 **     1        Unused        Direct lookup by rowid.
152612 **     2        See below     R-tree query or full-table scan.
152613 **   ------------------------------------------------
152614 **
152615 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
152616 ** 2 is used, idxStr is formatted to contain 2 bytes for each
152617 ** constraint used. The first two bytes of idxStr correspond to
152618 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
152619 ** (argvIndex==1) etc.
152620 **
152621 ** The first of each pair of bytes in idxStr identifies the constraint
152622 ** operator as follows:
152623 **
152624 **   Operator    Byte Value
152625 **   ----------------------
152626 **      =        0x41 ('A')
152627 **     <=        0x42 ('B')
152628 **      <        0x43 ('C')
152629 **     >=        0x44 ('D')
152630 **      >        0x45 ('E')
152631 **   MATCH       0x46 ('F')
152632 **   ----------------------
152633 **
152634 ** The second of each pair of bytes identifies the coordinate column
152635 ** to which the constraint applies. The leftmost coordinate column
152636 ** is 'a', the second from the left 'b' etc.
152637 */
152638 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
152639   Rtree *pRtree = (Rtree*)tab;
152640   int rc = SQLITE_OK;
152641   int ii;
152642   i64 nRow;                       /* Estimated rows returned by this scan */
152643 
152644   int iIdx = 0;
152645   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
152646   memset(zIdxStr, 0, sizeof(zIdxStr));
152647 
152648   assert( pIdxInfo->idxStr==0 );
152649   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
152650     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
152651 
152652     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
152653       /* We have an equality constraint on the rowid. Use strategy 1. */
152654       int jj;
152655       for(jj=0; jj<ii; jj++){
152656         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
152657         pIdxInfo->aConstraintUsage[jj].omit = 0;
152658       }
152659       pIdxInfo->idxNum = 1;
152660       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
152661       pIdxInfo->aConstraintUsage[jj].omit = 1;
152662 
152663       /* This strategy involves a two rowid lookups on an B-Tree structures
152664       ** and then a linear search of an R-Tree node. This should be
152665       ** considered almost as quick as a direct rowid lookup (for which
152666       ** sqlite uses an internal cost of 0.0). It is expected to return
152667       ** a single row.
152668       */
152669       pIdxInfo->estimatedCost = 30.0;
152670       setEstimatedRows(pIdxInfo, 1);
152671       return SQLITE_OK;
152672     }
152673 
152674     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
152675       u8 op;
152676       switch( p->op ){
152677         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
152678         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
152679         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
152680         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
152681         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
152682         default:
152683           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
152684           op = RTREE_MATCH;
152685           break;
152686       }
152687       zIdxStr[iIdx++] = op;
152688       zIdxStr[iIdx++] = p->iColumn - 1 + '0';
152689       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
152690       pIdxInfo->aConstraintUsage[ii].omit = 1;
152691     }
152692   }
152693 
152694   pIdxInfo->idxNum = 2;
152695   pIdxInfo->needToFreeIdxStr = 1;
152696   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
152697     return SQLITE_NOMEM;
152698   }
152699 
152700   nRow = pRtree->nRowEst / (iIdx + 1);
152701   pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
152702   setEstimatedRows(pIdxInfo, nRow);
152703 
152704   return rc;
152705 }
152706 
152707 /*
152708 ** Return the N-dimensional volumn of the cell stored in *p.
152709 */
152710 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
152711   RtreeDValue area = (RtreeDValue)1;
152712   int ii;
152713   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
152714     area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
152715   }
152716   return area;
152717 }
152718 
152719 /*
152720 ** Return the margin length of cell p. The margin length is the sum
152721 ** of the objects size in each dimension.
152722 */
152723 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
152724   RtreeDValue margin = (RtreeDValue)0;
152725   int ii;
152726   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
152727     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
152728   }
152729   return margin;
152730 }
152731 
152732 /*
152733 ** Store the union of cells p1 and p2 in p1.
152734 */
152735 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
152736   int ii;
152737   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
152738     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
152739       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
152740       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
152741     }
152742   }else{
152743     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
152744       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
152745       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
152746     }
152747   }
152748 }
152749 
152750 /*
152751 ** Return true if the area covered by p2 is a subset of the area covered
152752 ** by p1. False otherwise.
152753 */
152754 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
152755   int ii;
152756   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
152757   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
152758     RtreeCoord *a1 = &p1->aCoord[ii];
152759     RtreeCoord *a2 = &p2->aCoord[ii];
152760     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
152761      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
152762     ){
152763       return 0;
152764     }
152765   }
152766   return 1;
152767 }
152768 
152769 /*
152770 ** Return the amount cell p would grow by if it were unioned with pCell.
152771 */
152772 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
152773   RtreeDValue area;
152774   RtreeCell cell;
152775   memcpy(&cell, p, sizeof(RtreeCell));
152776   area = cellArea(pRtree, &cell);
152777   cellUnion(pRtree, &cell, pCell);
152778   return (cellArea(pRtree, &cell)-area);
152779 }
152780 
152781 static RtreeDValue cellOverlap(
152782   Rtree *pRtree,
152783   RtreeCell *p,
152784   RtreeCell *aCell,
152785   int nCell
152786 ){
152787   int ii;
152788   RtreeDValue overlap = RTREE_ZERO;
152789   for(ii=0; ii<nCell; ii++){
152790     int jj;
152791     RtreeDValue o = (RtreeDValue)1;
152792     for(jj=0; jj<(pRtree->nDim*2); jj+=2){
152793       RtreeDValue x1, x2;
152794       x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
152795       x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
152796       if( x2<x1 ){
152797         o = (RtreeDValue)0;
152798         break;
152799       }else{
152800         o = o * (x2-x1);
152801       }
152802     }
152803     overlap += o;
152804   }
152805   return overlap;
152806 }
152807 
152808 
152809 /*
152810 ** This function implements the ChooseLeaf algorithm from Gutman[84].
152811 ** ChooseSubTree in r*tree terminology.
152812 */
152813 static int ChooseLeaf(
152814   Rtree *pRtree,               /* Rtree table */
152815   RtreeCell *pCell,            /* Cell to insert into rtree */
152816   int iHeight,                 /* Height of sub-tree rooted at pCell */
152817   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
152818 ){
152819   int rc;
152820   int ii;
152821   RtreeNode *pNode;
152822   rc = nodeAcquire(pRtree, 1, 0, &pNode);
152823 
152824   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
152825     int iCell;
152826     sqlite3_int64 iBest = 0;
152827 
152828     RtreeDValue fMinGrowth = RTREE_ZERO;
152829     RtreeDValue fMinArea = RTREE_ZERO;
152830 
152831     int nCell = NCELL(pNode);
152832     RtreeCell cell;
152833     RtreeNode *pChild;
152834 
152835     RtreeCell *aCell = 0;
152836 
152837     /* Select the child node which will be enlarged the least if pCell
152838     ** is inserted into it. Resolve ties by choosing the entry with
152839     ** the smallest area.
152840     */
152841     for(iCell=0; iCell<nCell; iCell++){
152842       int bBest = 0;
152843       RtreeDValue growth;
152844       RtreeDValue area;
152845       nodeGetCell(pRtree, pNode, iCell, &cell);
152846       growth = cellGrowth(pRtree, &cell, pCell);
152847       area = cellArea(pRtree, &cell);
152848       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
152849         bBest = 1;
152850       }
152851       if( bBest ){
152852         fMinGrowth = growth;
152853         fMinArea = area;
152854         iBest = cell.iRowid;
152855       }
152856     }
152857 
152858     sqlite3_free(aCell);
152859     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
152860     nodeRelease(pRtree, pNode);
152861     pNode = pChild;
152862   }
152863 
152864   *ppLeaf = pNode;
152865   return rc;
152866 }
152867 
152868 /*
152869 ** A cell with the same content as pCell has just been inserted into
152870 ** the node pNode. This function updates the bounding box cells in
152871 ** all ancestor elements.
152872 */
152873 static int AdjustTree(
152874   Rtree *pRtree,                    /* Rtree table */
152875   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
152876   RtreeCell *pCell                  /* This cell was just inserted */
152877 ){
152878   RtreeNode *p = pNode;
152879   while( p->pParent ){
152880     RtreeNode *pParent = p->pParent;
152881     RtreeCell cell;
152882     int iCell;
152883 
152884     if( nodeParentIndex(pRtree, p, &iCell) ){
152885       return SQLITE_CORRUPT_VTAB;
152886     }
152887 
152888     nodeGetCell(pRtree, pParent, iCell, &cell);
152889     if( !cellContains(pRtree, &cell, pCell) ){
152890       cellUnion(pRtree, &cell, pCell);
152891       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
152892     }
152893 
152894     p = pParent;
152895   }
152896   return SQLITE_OK;
152897 }
152898 
152899 /*
152900 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
152901 */
152902 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
152903   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
152904   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
152905   sqlite3_step(pRtree->pWriteRowid);
152906   return sqlite3_reset(pRtree->pWriteRowid);
152907 }
152908 
152909 /*
152910 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
152911 */
152912 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
152913   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
152914   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
152915   sqlite3_step(pRtree->pWriteParent);
152916   return sqlite3_reset(pRtree->pWriteParent);
152917 }
152918 
152919 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
152920 
152921 
152922 /*
152923 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
152924 ** nIdx. The aIdx array contains the set of integers from 0 to
152925 ** (nIdx-1) in no particular order. This function sorts the values
152926 ** in aIdx according to the indexed values in aDistance. For
152927 ** example, assuming the inputs:
152928 **
152929 **   aIdx      = { 0,   1,   2,   3 }
152930 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
152931 **
152932 ** this function sets the aIdx array to contain:
152933 **
152934 **   aIdx      = { 0,   1,   2,   3 }
152935 **
152936 ** The aSpare array is used as temporary working space by the
152937 ** sorting algorithm.
152938 */
152939 static void SortByDistance(
152940   int *aIdx,
152941   int nIdx,
152942   RtreeDValue *aDistance,
152943   int *aSpare
152944 ){
152945   if( nIdx>1 ){
152946     int iLeft = 0;
152947     int iRight = 0;
152948 
152949     int nLeft = nIdx/2;
152950     int nRight = nIdx-nLeft;
152951     int *aLeft = aIdx;
152952     int *aRight = &aIdx[nLeft];
152953 
152954     SortByDistance(aLeft, nLeft, aDistance, aSpare);
152955     SortByDistance(aRight, nRight, aDistance, aSpare);
152956 
152957     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
152958     aLeft = aSpare;
152959 
152960     while( iLeft<nLeft || iRight<nRight ){
152961       if( iLeft==nLeft ){
152962         aIdx[iLeft+iRight] = aRight[iRight];
152963         iRight++;
152964       }else if( iRight==nRight ){
152965         aIdx[iLeft+iRight] = aLeft[iLeft];
152966         iLeft++;
152967       }else{
152968         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
152969         RtreeDValue fRight = aDistance[aRight[iRight]];
152970         if( fLeft<fRight ){
152971           aIdx[iLeft+iRight] = aLeft[iLeft];
152972           iLeft++;
152973         }else{
152974           aIdx[iLeft+iRight] = aRight[iRight];
152975           iRight++;
152976         }
152977       }
152978     }
152979 
152980 #if 0
152981     /* Check that the sort worked */
152982     {
152983       int jj;
152984       for(jj=1; jj<nIdx; jj++){
152985         RtreeDValue left = aDistance[aIdx[jj-1]];
152986         RtreeDValue right = aDistance[aIdx[jj]];
152987         assert( left<=right );
152988       }
152989     }
152990 #endif
152991   }
152992 }
152993 
152994 /*
152995 ** Arguments aIdx, aCell and aSpare all point to arrays of size
152996 ** nIdx. The aIdx array contains the set of integers from 0 to
152997 ** (nIdx-1) in no particular order. This function sorts the values
152998 ** in aIdx according to dimension iDim of the cells in aCell. The
152999 ** minimum value of dimension iDim is considered first, the
153000 ** maximum used to break ties.
153001 **
153002 ** The aSpare array is used as temporary working space by the
153003 ** sorting algorithm.
153004 */
153005 static void SortByDimension(
153006   Rtree *pRtree,
153007   int *aIdx,
153008   int nIdx,
153009   int iDim,
153010   RtreeCell *aCell,
153011   int *aSpare
153012 ){
153013   if( nIdx>1 ){
153014 
153015     int iLeft = 0;
153016     int iRight = 0;
153017 
153018     int nLeft = nIdx/2;
153019     int nRight = nIdx-nLeft;
153020     int *aLeft = aIdx;
153021     int *aRight = &aIdx[nLeft];
153022 
153023     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
153024     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
153025 
153026     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
153027     aLeft = aSpare;
153028     while( iLeft<nLeft || iRight<nRight ){
153029       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
153030       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
153031       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
153032       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
153033       if( (iLeft!=nLeft) && ((iRight==nRight)
153034        || (xleft1<xright1)
153035        || (xleft1==xright1 && xleft2<xright2)
153036       )){
153037         aIdx[iLeft+iRight] = aLeft[iLeft];
153038         iLeft++;
153039       }else{
153040         aIdx[iLeft+iRight] = aRight[iRight];
153041         iRight++;
153042       }
153043     }
153044 
153045 #if 0
153046     /* Check that the sort worked */
153047     {
153048       int jj;
153049       for(jj=1; jj<nIdx; jj++){
153050         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
153051         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
153052         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
153053         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
153054         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
153055       }
153056     }
153057 #endif
153058   }
153059 }
153060 
153061 /*
153062 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
153063 */
153064 static int splitNodeStartree(
153065   Rtree *pRtree,
153066   RtreeCell *aCell,
153067   int nCell,
153068   RtreeNode *pLeft,
153069   RtreeNode *pRight,
153070   RtreeCell *pBboxLeft,
153071   RtreeCell *pBboxRight
153072 ){
153073   int **aaSorted;
153074   int *aSpare;
153075   int ii;
153076 
153077   int iBestDim = 0;
153078   int iBestSplit = 0;
153079   RtreeDValue fBestMargin = RTREE_ZERO;
153080 
153081   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
153082 
153083   aaSorted = (int **)sqlite3_malloc(nByte);
153084   if( !aaSorted ){
153085     return SQLITE_NOMEM;
153086   }
153087 
153088   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
153089   memset(aaSorted, 0, nByte);
153090   for(ii=0; ii<pRtree->nDim; ii++){
153091     int jj;
153092     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
153093     for(jj=0; jj<nCell; jj++){
153094       aaSorted[ii][jj] = jj;
153095     }
153096     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
153097   }
153098 
153099   for(ii=0; ii<pRtree->nDim; ii++){
153100     RtreeDValue margin = RTREE_ZERO;
153101     RtreeDValue fBestOverlap = RTREE_ZERO;
153102     RtreeDValue fBestArea = RTREE_ZERO;
153103     int iBestLeft = 0;
153104     int nLeft;
153105 
153106     for(
153107       nLeft=RTREE_MINCELLS(pRtree);
153108       nLeft<=(nCell-RTREE_MINCELLS(pRtree));
153109       nLeft++
153110     ){
153111       RtreeCell left;
153112       RtreeCell right;
153113       int kk;
153114       RtreeDValue overlap;
153115       RtreeDValue area;
153116 
153117       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
153118       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
153119       for(kk=1; kk<(nCell-1); kk++){
153120         if( kk<nLeft ){
153121           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
153122         }else{
153123           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
153124         }
153125       }
153126       margin += cellMargin(pRtree, &left);
153127       margin += cellMargin(pRtree, &right);
153128       overlap = cellOverlap(pRtree, &left, &right, 1);
153129       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
153130       if( (nLeft==RTREE_MINCELLS(pRtree))
153131        || (overlap<fBestOverlap)
153132        || (overlap==fBestOverlap && area<fBestArea)
153133       ){
153134         iBestLeft = nLeft;
153135         fBestOverlap = overlap;
153136         fBestArea = area;
153137       }
153138     }
153139 
153140     if( ii==0 || margin<fBestMargin ){
153141       iBestDim = ii;
153142       fBestMargin = margin;
153143       iBestSplit = iBestLeft;
153144     }
153145   }
153146 
153147   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
153148   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
153149   for(ii=0; ii<nCell; ii++){
153150     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
153151     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
153152     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
153153     nodeInsertCell(pRtree, pTarget, pCell);
153154     cellUnion(pRtree, pBbox, pCell);
153155   }
153156 
153157   sqlite3_free(aaSorted);
153158   return SQLITE_OK;
153159 }
153160 
153161 
153162 static int updateMapping(
153163   Rtree *pRtree,
153164   i64 iRowid,
153165   RtreeNode *pNode,
153166   int iHeight
153167 ){
153168   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
153169   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
153170   if( iHeight>0 ){
153171     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
153172     if( pChild ){
153173       nodeRelease(pRtree, pChild->pParent);
153174       nodeReference(pNode);
153175       pChild->pParent = pNode;
153176     }
153177   }
153178   return xSetMapping(pRtree, iRowid, pNode->iNode);
153179 }
153180 
153181 static int SplitNode(
153182   Rtree *pRtree,
153183   RtreeNode *pNode,
153184   RtreeCell *pCell,
153185   int iHeight
153186 ){
153187   int i;
153188   int newCellIsRight = 0;
153189 
153190   int rc = SQLITE_OK;
153191   int nCell = NCELL(pNode);
153192   RtreeCell *aCell;
153193   int *aiUsed;
153194 
153195   RtreeNode *pLeft = 0;
153196   RtreeNode *pRight = 0;
153197 
153198   RtreeCell leftbbox;
153199   RtreeCell rightbbox;
153200 
153201   /* Allocate an array and populate it with a copy of pCell and
153202   ** all cells from node pLeft. Then zero the original node.
153203   */
153204   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
153205   if( !aCell ){
153206     rc = SQLITE_NOMEM;
153207     goto splitnode_out;
153208   }
153209   aiUsed = (int *)&aCell[nCell+1];
153210   memset(aiUsed, 0, sizeof(int)*(nCell+1));
153211   for(i=0; i<nCell; i++){
153212     nodeGetCell(pRtree, pNode, i, &aCell[i]);
153213   }
153214   nodeZero(pRtree, pNode);
153215   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
153216   nCell++;
153217 
153218   if( pNode->iNode==1 ){
153219     pRight = nodeNew(pRtree, pNode);
153220     pLeft = nodeNew(pRtree, pNode);
153221     pRtree->iDepth++;
153222     pNode->isDirty = 1;
153223     writeInt16(pNode->zData, pRtree->iDepth);
153224   }else{
153225     pLeft = pNode;
153226     pRight = nodeNew(pRtree, pLeft->pParent);
153227     nodeReference(pLeft);
153228   }
153229 
153230   if( !pLeft || !pRight ){
153231     rc = SQLITE_NOMEM;
153232     goto splitnode_out;
153233   }
153234 
153235   memset(pLeft->zData, 0, pRtree->iNodeSize);
153236   memset(pRight->zData, 0, pRtree->iNodeSize);
153237 
153238   rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
153239                          &leftbbox, &rightbbox);
153240   if( rc!=SQLITE_OK ){
153241     goto splitnode_out;
153242   }
153243 
153244   /* Ensure both child nodes have node numbers assigned to them by calling
153245   ** nodeWrite(). Node pRight always needs a node number, as it was created
153246   ** by nodeNew() above. But node pLeft sometimes already has a node number.
153247   ** In this case avoid the all to nodeWrite().
153248   */
153249   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
153250    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
153251   ){
153252     goto splitnode_out;
153253   }
153254 
153255   rightbbox.iRowid = pRight->iNode;
153256   leftbbox.iRowid = pLeft->iNode;
153257 
153258   if( pNode->iNode==1 ){
153259     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
153260     if( rc!=SQLITE_OK ){
153261       goto splitnode_out;
153262     }
153263   }else{
153264     RtreeNode *pParent = pLeft->pParent;
153265     int iCell;
153266     rc = nodeParentIndex(pRtree, pLeft, &iCell);
153267     if( rc==SQLITE_OK ){
153268       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
153269       rc = AdjustTree(pRtree, pParent, &leftbbox);
153270     }
153271     if( rc!=SQLITE_OK ){
153272       goto splitnode_out;
153273     }
153274   }
153275   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
153276     goto splitnode_out;
153277   }
153278 
153279   for(i=0; i<NCELL(pRight); i++){
153280     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
153281     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
153282     if( iRowid==pCell->iRowid ){
153283       newCellIsRight = 1;
153284     }
153285     if( rc!=SQLITE_OK ){
153286       goto splitnode_out;
153287     }
153288   }
153289   if( pNode->iNode==1 ){
153290     for(i=0; i<NCELL(pLeft); i++){
153291       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
153292       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
153293       if( rc!=SQLITE_OK ){
153294         goto splitnode_out;
153295       }
153296     }
153297   }else if( newCellIsRight==0 ){
153298     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
153299   }
153300 
153301   if( rc==SQLITE_OK ){
153302     rc = nodeRelease(pRtree, pRight);
153303     pRight = 0;
153304   }
153305   if( rc==SQLITE_OK ){
153306     rc = nodeRelease(pRtree, pLeft);
153307     pLeft = 0;
153308   }
153309 
153310 splitnode_out:
153311   nodeRelease(pRtree, pRight);
153312   nodeRelease(pRtree, pLeft);
153313   sqlite3_free(aCell);
153314   return rc;
153315 }
153316 
153317 /*
153318 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
153319 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
153320 ** the pLeaf->pParent chain all the way up to the root node.
153321 **
153322 ** This operation is required when a row is deleted (or updated - an update
153323 ** is implemented as a delete followed by an insert). SQLite provides the
153324 ** rowid of the row to delete, which can be used to find the leaf on which
153325 ** the entry resides (argument pLeaf). Once the leaf is located, this
153326 ** function is called to determine its ancestry.
153327 */
153328 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
153329   int rc = SQLITE_OK;
153330   RtreeNode *pChild = pLeaf;
153331   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
153332     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
153333     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
153334     rc = sqlite3_step(pRtree->pReadParent);
153335     if( rc==SQLITE_ROW ){
153336       RtreeNode *pTest;           /* Used to test for reference loops */
153337       i64 iNode;                  /* Node number of parent node */
153338 
153339       /* Before setting pChild->pParent, test that we are not creating a
153340       ** loop of references (as we would if, say, pChild==pParent). We don't
153341       ** want to do this as it leads to a memory leak when trying to delete
153342       ** the referenced counted node structures.
153343       */
153344       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
153345       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
153346       if( !pTest ){
153347         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
153348       }
153349     }
153350     rc = sqlite3_reset(pRtree->pReadParent);
153351     if( rc==SQLITE_OK ) rc = rc2;
153352     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
153353     pChild = pChild->pParent;
153354   }
153355   return rc;
153356 }
153357 
153358 static int deleteCell(Rtree *, RtreeNode *, int, int);
153359 
153360 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
153361   int rc;
153362   int rc2;
153363   RtreeNode *pParent = 0;
153364   int iCell;
153365 
153366   assert( pNode->nRef==1 );
153367 
153368   /* Remove the entry in the parent cell. */
153369   rc = nodeParentIndex(pRtree, pNode, &iCell);
153370   if( rc==SQLITE_OK ){
153371     pParent = pNode->pParent;
153372     pNode->pParent = 0;
153373     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
153374   }
153375   rc2 = nodeRelease(pRtree, pParent);
153376   if( rc==SQLITE_OK ){
153377     rc = rc2;
153378   }
153379   if( rc!=SQLITE_OK ){
153380     return rc;
153381   }
153382 
153383   /* Remove the xxx_node entry. */
153384   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
153385   sqlite3_step(pRtree->pDeleteNode);
153386   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
153387     return rc;
153388   }
153389 
153390   /* Remove the xxx_parent entry. */
153391   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
153392   sqlite3_step(pRtree->pDeleteParent);
153393   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
153394     return rc;
153395   }
153396 
153397   /* Remove the node from the in-memory hash table and link it into
153398   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
153399   */
153400   nodeHashDelete(pRtree, pNode);
153401   pNode->iNode = iHeight;
153402   pNode->pNext = pRtree->pDeleted;
153403   pNode->nRef++;
153404   pRtree->pDeleted = pNode;
153405 
153406   return SQLITE_OK;
153407 }
153408 
153409 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
153410   RtreeNode *pParent = pNode->pParent;
153411   int rc = SQLITE_OK;
153412   if( pParent ){
153413     int ii;
153414     int nCell = NCELL(pNode);
153415     RtreeCell box;                            /* Bounding box for pNode */
153416     nodeGetCell(pRtree, pNode, 0, &box);
153417     for(ii=1; ii<nCell; ii++){
153418       RtreeCell cell;
153419       nodeGetCell(pRtree, pNode, ii, &cell);
153420       cellUnion(pRtree, &box, &cell);
153421     }
153422     box.iRowid = pNode->iNode;
153423     rc = nodeParentIndex(pRtree, pNode, &ii);
153424     if( rc==SQLITE_OK ){
153425       nodeOverwriteCell(pRtree, pParent, &box, ii);
153426       rc = fixBoundingBox(pRtree, pParent);
153427     }
153428   }
153429   return rc;
153430 }
153431 
153432 /*
153433 ** Delete the cell at index iCell of node pNode. After removing the
153434 ** cell, adjust the r-tree data structure if required.
153435 */
153436 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
153437   RtreeNode *pParent;
153438   int rc;
153439 
153440   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
153441     return rc;
153442   }
153443 
153444   /* Remove the cell from the node. This call just moves bytes around
153445   ** the in-memory node image, so it cannot fail.
153446   */
153447   nodeDeleteCell(pRtree, pNode, iCell);
153448 
153449   /* If the node is not the tree root and now has less than the minimum
153450   ** number of cells, remove it from the tree. Otherwise, update the
153451   ** cell in the parent node so that it tightly contains the updated
153452   ** node.
153453   */
153454   pParent = pNode->pParent;
153455   assert( pParent || pNode->iNode==1 );
153456   if( pParent ){
153457     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
153458       rc = removeNode(pRtree, pNode, iHeight);
153459     }else{
153460       rc = fixBoundingBox(pRtree, pNode);
153461     }
153462   }
153463 
153464   return rc;
153465 }
153466 
153467 static int Reinsert(
153468   Rtree *pRtree,
153469   RtreeNode *pNode,
153470   RtreeCell *pCell,
153471   int iHeight
153472 ){
153473   int *aOrder;
153474   int *aSpare;
153475   RtreeCell *aCell;
153476   RtreeDValue *aDistance;
153477   int nCell;
153478   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
153479   int iDim;
153480   int ii;
153481   int rc = SQLITE_OK;
153482   int n;
153483 
153484   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
153485 
153486   nCell = NCELL(pNode)+1;
153487   n = (nCell+1)&(~1);
153488 
153489   /* Allocate the buffers used by this operation. The allocation is
153490   ** relinquished before this function returns.
153491   */
153492   aCell = (RtreeCell *)sqlite3_malloc(n * (
153493     sizeof(RtreeCell)     +         /* aCell array */
153494     sizeof(int)           +         /* aOrder array */
153495     sizeof(int)           +         /* aSpare array */
153496     sizeof(RtreeDValue)             /* aDistance array */
153497   ));
153498   if( !aCell ){
153499     return SQLITE_NOMEM;
153500   }
153501   aOrder    = (int *)&aCell[n];
153502   aSpare    = (int *)&aOrder[n];
153503   aDistance = (RtreeDValue *)&aSpare[n];
153504 
153505   for(ii=0; ii<nCell; ii++){
153506     if( ii==(nCell-1) ){
153507       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
153508     }else{
153509       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
153510     }
153511     aOrder[ii] = ii;
153512     for(iDim=0; iDim<pRtree->nDim; iDim++){
153513       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
153514       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
153515     }
153516   }
153517   for(iDim=0; iDim<pRtree->nDim; iDim++){
153518     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
153519   }
153520 
153521   for(ii=0; ii<nCell; ii++){
153522     aDistance[ii] = RTREE_ZERO;
153523     for(iDim=0; iDim<pRtree->nDim; iDim++){
153524       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
153525                                DCOORD(aCell[ii].aCoord[iDim*2]));
153526       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
153527     }
153528   }
153529 
153530   SortByDistance(aOrder, nCell, aDistance, aSpare);
153531   nodeZero(pRtree, pNode);
153532 
153533   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
153534     RtreeCell *p = &aCell[aOrder[ii]];
153535     nodeInsertCell(pRtree, pNode, p);
153536     if( p->iRowid==pCell->iRowid ){
153537       if( iHeight==0 ){
153538         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
153539       }else{
153540         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
153541       }
153542     }
153543   }
153544   if( rc==SQLITE_OK ){
153545     rc = fixBoundingBox(pRtree, pNode);
153546   }
153547   for(; rc==SQLITE_OK && ii<nCell; ii++){
153548     /* Find a node to store this cell in. pNode->iNode currently contains
153549     ** the height of the sub-tree headed by the cell.
153550     */
153551     RtreeNode *pInsert;
153552     RtreeCell *p = &aCell[aOrder[ii]];
153553     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
153554     if( rc==SQLITE_OK ){
153555       int rc2;
153556       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
153557       rc2 = nodeRelease(pRtree, pInsert);
153558       if( rc==SQLITE_OK ){
153559         rc = rc2;
153560       }
153561     }
153562   }
153563 
153564   sqlite3_free(aCell);
153565   return rc;
153566 }
153567 
153568 /*
153569 ** Insert cell pCell into node pNode. Node pNode is the head of a
153570 ** subtree iHeight high (leaf nodes have iHeight==0).
153571 */
153572 static int rtreeInsertCell(
153573   Rtree *pRtree,
153574   RtreeNode *pNode,
153575   RtreeCell *pCell,
153576   int iHeight
153577 ){
153578   int rc = SQLITE_OK;
153579   if( iHeight>0 ){
153580     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
153581     if( pChild ){
153582       nodeRelease(pRtree, pChild->pParent);
153583       nodeReference(pNode);
153584       pChild->pParent = pNode;
153585     }
153586   }
153587   if( nodeInsertCell(pRtree, pNode, pCell) ){
153588     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
153589       rc = SplitNode(pRtree, pNode, pCell, iHeight);
153590     }else{
153591       pRtree->iReinsertHeight = iHeight;
153592       rc = Reinsert(pRtree, pNode, pCell, iHeight);
153593     }
153594   }else{
153595     rc = AdjustTree(pRtree, pNode, pCell);
153596     if( rc==SQLITE_OK ){
153597       if( iHeight==0 ){
153598         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
153599       }else{
153600         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
153601       }
153602     }
153603   }
153604   return rc;
153605 }
153606 
153607 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
153608   int ii;
153609   int rc = SQLITE_OK;
153610   int nCell = NCELL(pNode);
153611 
153612   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
153613     RtreeNode *pInsert;
153614     RtreeCell cell;
153615     nodeGetCell(pRtree, pNode, ii, &cell);
153616 
153617     /* Find a node to store this cell in. pNode->iNode currently contains
153618     ** the height of the sub-tree headed by the cell.
153619     */
153620     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
153621     if( rc==SQLITE_OK ){
153622       int rc2;
153623       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
153624       rc2 = nodeRelease(pRtree, pInsert);
153625       if( rc==SQLITE_OK ){
153626         rc = rc2;
153627       }
153628     }
153629   }
153630   return rc;
153631 }
153632 
153633 /*
153634 ** Select a currently unused rowid for a new r-tree record.
153635 */
153636 static int newRowid(Rtree *pRtree, i64 *piRowid){
153637   int rc;
153638   sqlite3_bind_null(pRtree->pWriteRowid, 1);
153639   sqlite3_bind_null(pRtree->pWriteRowid, 2);
153640   sqlite3_step(pRtree->pWriteRowid);
153641   rc = sqlite3_reset(pRtree->pWriteRowid);
153642   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
153643   return rc;
153644 }
153645 
153646 /*
153647 ** Remove the entry with rowid=iDelete from the r-tree structure.
153648 */
153649 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
153650   int rc;                         /* Return code */
153651   RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
153652   int iCell;                      /* Index of iDelete cell in pLeaf */
153653   RtreeNode *pRoot;               /* Root node of rtree structure */
153654 
153655 
153656   /* Obtain a reference to the root node to initialize Rtree.iDepth */
153657   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
153658 
153659   /* Obtain a reference to the leaf node that contains the entry
153660   ** about to be deleted.
153661   */
153662   if( rc==SQLITE_OK ){
153663     rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
153664   }
153665 
153666   /* Delete the cell in question from the leaf node. */
153667   if( rc==SQLITE_OK ){
153668     int rc2;
153669     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
153670     if( rc==SQLITE_OK ){
153671       rc = deleteCell(pRtree, pLeaf, iCell, 0);
153672     }
153673     rc2 = nodeRelease(pRtree, pLeaf);
153674     if( rc==SQLITE_OK ){
153675       rc = rc2;
153676     }
153677   }
153678 
153679   /* Delete the corresponding entry in the <rtree>_rowid table. */
153680   if( rc==SQLITE_OK ){
153681     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
153682     sqlite3_step(pRtree->pDeleteRowid);
153683     rc = sqlite3_reset(pRtree->pDeleteRowid);
153684   }
153685 
153686   /* Check if the root node now has exactly one child. If so, remove
153687   ** it, schedule the contents of the child for reinsertion and
153688   ** reduce the tree height by one.
153689   **
153690   ** This is equivalent to copying the contents of the child into
153691   ** the root node (the operation that Gutman's paper says to perform
153692   ** in this scenario).
153693   */
153694   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
153695     int rc2;
153696     RtreeNode *pChild;
153697     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
153698     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
153699     if( rc==SQLITE_OK ){
153700       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
153701     }
153702     rc2 = nodeRelease(pRtree, pChild);
153703     if( rc==SQLITE_OK ) rc = rc2;
153704     if( rc==SQLITE_OK ){
153705       pRtree->iDepth--;
153706       writeInt16(pRoot->zData, pRtree->iDepth);
153707       pRoot->isDirty = 1;
153708     }
153709   }
153710 
153711   /* Re-insert the contents of any underfull nodes removed from the tree. */
153712   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
153713     if( rc==SQLITE_OK ){
153714       rc = reinsertNodeContent(pRtree, pLeaf);
153715     }
153716     pRtree->pDeleted = pLeaf->pNext;
153717     sqlite3_free(pLeaf);
153718   }
153719 
153720   /* Release the reference to the root node. */
153721   if( rc==SQLITE_OK ){
153722     rc = nodeRelease(pRtree, pRoot);
153723   }else{
153724     nodeRelease(pRtree, pRoot);
153725   }
153726 
153727   return rc;
153728 }
153729 
153730 /*
153731 ** Rounding constants for float->double conversion.
153732 */
153733 #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
153734 #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
153735 
153736 #if !defined(SQLITE_RTREE_INT_ONLY)
153737 /*
153738 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
153739 ** while taking care to round toward negative or positive, respectively.
153740 */
153741 static RtreeValue rtreeValueDown(sqlite3_value *v){
153742   double d = sqlite3_value_double(v);
153743   float f = (float)d;
153744   if( f>d ){
153745     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
153746   }
153747   return f;
153748 }
153749 static RtreeValue rtreeValueUp(sqlite3_value *v){
153750   double d = sqlite3_value_double(v);
153751   float f = (float)d;
153752   if( f<d ){
153753     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
153754   }
153755   return f;
153756 }
153757 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
153758 
153759 
153760 /*
153761 ** The xUpdate method for rtree module virtual tables.
153762 */
153763 static int rtreeUpdate(
153764   sqlite3_vtab *pVtab,
153765   int nData,
153766   sqlite3_value **azData,
153767   sqlite_int64 *pRowid
153768 ){
153769   Rtree *pRtree = (Rtree *)pVtab;
153770   int rc = SQLITE_OK;
153771   RtreeCell cell;                 /* New cell to insert if nData>1 */
153772   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
153773 
153774   rtreeReference(pRtree);
153775   assert(nData>=1);
153776 
153777   cell.iRowid = 0;  /* Used only to suppress a compiler warning */
153778 
153779   /* Constraint handling. A write operation on an r-tree table may return
153780   ** SQLITE_CONSTRAINT for two reasons:
153781   **
153782   **   1. A duplicate rowid value, or
153783   **   2. The supplied data violates the "x2>=x1" constraint.
153784   **
153785   ** In the first case, if the conflict-handling mode is REPLACE, then
153786   ** the conflicting row can be removed before proceeding. In the second
153787   ** case, SQLITE_CONSTRAINT must be returned regardless of the
153788   ** conflict-handling mode specified by the user.
153789   */
153790   if( nData>1 ){
153791     int ii;
153792 
153793     /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
153794     **
153795     ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
153796     ** with "column" that are interpreted as table constraints.
153797     ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
153798     ** This problem was discovered after years of use, so we silently ignore
153799     ** these kinds of misdeclared tables to avoid breaking any legacy.
153800     */
153801     assert( nData<=(pRtree->nDim*2 + 3) );
153802 
153803 #ifndef SQLITE_RTREE_INT_ONLY
153804     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
153805       for(ii=0; ii<nData-4; ii+=2){
153806         cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
153807         cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
153808         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
153809           rc = SQLITE_CONSTRAINT;
153810           goto constraint;
153811         }
153812       }
153813     }else
153814 #endif
153815     {
153816       for(ii=0; ii<nData-4; ii+=2){
153817         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
153818         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
153819         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
153820           rc = SQLITE_CONSTRAINT;
153821           goto constraint;
153822         }
153823       }
153824     }
153825 
153826     /* If a rowid value was supplied, check if it is already present in
153827     ** the table. If so, the constraint has failed. */
153828     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
153829       cell.iRowid = sqlite3_value_int64(azData[2]);
153830       if( sqlite3_value_type(azData[0])==SQLITE_NULL
153831        || sqlite3_value_int64(azData[0])!=cell.iRowid
153832       ){
153833         int steprc;
153834         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
153835         steprc = sqlite3_step(pRtree->pReadRowid);
153836         rc = sqlite3_reset(pRtree->pReadRowid);
153837         if( SQLITE_ROW==steprc ){
153838           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
153839             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
153840           }else{
153841             rc = SQLITE_CONSTRAINT;
153842             goto constraint;
153843           }
153844         }
153845       }
153846       bHaveRowid = 1;
153847     }
153848   }
153849 
153850   /* If azData[0] is not an SQL NULL value, it is the rowid of a
153851   ** record to delete from the r-tree table. The following block does
153852   ** just that.
153853   */
153854   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
153855     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
153856   }
153857 
153858   /* If the azData[] array contains more than one element, elements
153859   ** (azData[2]..azData[argc-1]) contain a new record to insert into
153860   ** the r-tree structure.
153861   */
153862   if( rc==SQLITE_OK && nData>1 ){
153863     /* Insert the new record into the r-tree */
153864     RtreeNode *pLeaf = 0;
153865 
153866     /* Figure out the rowid of the new row. */
153867     if( bHaveRowid==0 ){
153868       rc = newRowid(pRtree, &cell.iRowid);
153869     }
153870     *pRowid = cell.iRowid;
153871 
153872     if( rc==SQLITE_OK ){
153873       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
153874     }
153875     if( rc==SQLITE_OK ){
153876       int rc2;
153877       pRtree->iReinsertHeight = -1;
153878       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
153879       rc2 = nodeRelease(pRtree, pLeaf);
153880       if( rc==SQLITE_OK ){
153881         rc = rc2;
153882       }
153883     }
153884   }
153885 
153886 constraint:
153887   rtreeRelease(pRtree);
153888   return rc;
153889 }
153890 
153891 /*
153892 ** The xRename method for rtree module virtual tables.
153893 */
153894 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
153895   Rtree *pRtree = (Rtree *)pVtab;
153896   int rc = SQLITE_NOMEM;
153897   char *zSql = sqlite3_mprintf(
153898     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
153899     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
153900     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
153901     , pRtree->zDb, pRtree->zName, zNewName
153902     , pRtree->zDb, pRtree->zName, zNewName
153903     , pRtree->zDb, pRtree->zName, zNewName
153904   );
153905   if( zSql ){
153906     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
153907     sqlite3_free(zSql);
153908   }
153909   return rc;
153910 }
153911 
153912 /*
153913 ** This function populates the pRtree->nRowEst variable with an estimate
153914 ** of the number of rows in the virtual table. If possible, this is based
153915 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
153916 */
153917 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
153918   const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
153919   char *zSql;
153920   sqlite3_stmt *p;
153921   int rc;
153922   i64 nRow = 0;
153923 
153924   zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
153925   if( zSql==0 ){
153926     rc = SQLITE_NOMEM;
153927   }else{
153928     rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
153929     if( rc==SQLITE_OK ){
153930       if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
153931       rc = sqlite3_finalize(p);
153932     }else if( rc!=SQLITE_NOMEM ){
153933       rc = SQLITE_OK;
153934     }
153935 
153936     if( rc==SQLITE_OK ){
153937       if( nRow==0 ){
153938         pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
153939       }else{
153940         pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
153941       }
153942     }
153943     sqlite3_free(zSql);
153944   }
153945 
153946   return rc;
153947 }
153948 
153949 static sqlite3_module rtreeModule = {
153950   0,                          /* iVersion */
153951   rtreeCreate,                /* xCreate - create a table */
153952   rtreeConnect,               /* xConnect - connect to an existing table */
153953   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
153954   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
153955   rtreeDestroy,               /* xDestroy - Drop a table */
153956   rtreeOpen,                  /* xOpen - open a cursor */
153957   rtreeClose,                 /* xClose - close a cursor */
153958   rtreeFilter,                /* xFilter - configure scan constraints */
153959   rtreeNext,                  /* xNext - advance a cursor */
153960   rtreeEof,                   /* xEof */
153961   rtreeColumn,                /* xColumn - read data */
153962   rtreeRowid,                 /* xRowid - read data */
153963   rtreeUpdate,                /* xUpdate - write data */
153964   0,                          /* xBegin - begin transaction */
153965   0,                          /* xSync - sync transaction */
153966   0,                          /* xCommit - commit transaction */
153967   0,                          /* xRollback - rollback transaction */
153968   0,                          /* xFindFunction - function overloading */
153969   rtreeRename,                /* xRename - rename the table */
153970   0,                          /* xSavepoint */
153971   0,                          /* xRelease */
153972   0                           /* xRollbackTo */
153973 };
153974 
153975 static int rtreeSqlInit(
153976   Rtree *pRtree,
153977   sqlite3 *db,
153978   const char *zDb,
153979   const char *zPrefix,
153980   int isCreate
153981 ){
153982   int rc = SQLITE_OK;
153983 
153984   #define N_STATEMENT 9
153985   static const char *azSql[N_STATEMENT] = {
153986     /* Read and write the xxx_node table */
153987     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
153988     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
153989     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
153990 
153991     /* Read and write the xxx_rowid table */
153992     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
153993     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
153994     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
153995 
153996     /* Read and write the xxx_parent table */
153997     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
153998     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
153999     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
154000   };
154001   sqlite3_stmt **appStmt[N_STATEMENT];
154002   int i;
154003 
154004   pRtree->db = db;
154005 
154006   if( isCreate ){
154007     char *zCreate = sqlite3_mprintf(
154008 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
154009 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
154010 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
154011                                   " parentnode INTEGER);"
154012 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
154013       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
154014     );
154015     if( !zCreate ){
154016       return SQLITE_NOMEM;
154017     }
154018     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
154019     sqlite3_free(zCreate);
154020     if( rc!=SQLITE_OK ){
154021       return rc;
154022     }
154023   }
154024 
154025   appStmt[0] = &pRtree->pReadNode;
154026   appStmt[1] = &pRtree->pWriteNode;
154027   appStmt[2] = &pRtree->pDeleteNode;
154028   appStmt[3] = &pRtree->pReadRowid;
154029   appStmt[4] = &pRtree->pWriteRowid;
154030   appStmt[5] = &pRtree->pDeleteRowid;
154031   appStmt[6] = &pRtree->pReadParent;
154032   appStmt[7] = &pRtree->pWriteParent;
154033   appStmt[8] = &pRtree->pDeleteParent;
154034 
154035   rc = rtreeQueryStat1(db, pRtree);
154036   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
154037     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
154038     if( zSql ){
154039       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
154040     }else{
154041       rc = SQLITE_NOMEM;
154042     }
154043     sqlite3_free(zSql);
154044   }
154045 
154046   return rc;
154047 }
154048 
154049 /*
154050 ** The second argument to this function contains the text of an SQL statement
154051 ** that returns a single integer value. The statement is compiled and executed
154052 ** using database connection db. If successful, the integer value returned
154053 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
154054 ** code is returned and the value of *piVal after returning is not defined.
154055 */
154056 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
154057   int rc = SQLITE_NOMEM;
154058   if( zSql ){
154059     sqlite3_stmt *pStmt = 0;
154060     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
154061     if( rc==SQLITE_OK ){
154062       if( SQLITE_ROW==sqlite3_step(pStmt) ){
154063         *piVal = sqlite3_column_int(pStmt, 0);
154064       }
154065       rc = sqlite3_finalize(pStmt);
154066     }
154067   }
154068   return rc;
154069 }
154070 
154071 /*
154072 ** This function is called from within the xConnect() or xCreate() method to
154073 ** determine the node-size used by the rtree table being created or connected
154074 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
154075 ** Otherwise, an SQLite error code is returned.
154076 **
154077 ** If this function is being called as part of an xConnect(), then the rtree
154078 ** table already exists. In this case the node-size is determined by inspecting
154079 ** the root node of the tree.
154080 **
154081 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
154082 ** This ensures that each node is stored on a single database page. If the
154083 ** database page-size is so large that more than RTREE_MAXCELLS entries
154084 ** would fit in a single node, use a smaller node-size.
154085 */
154086 static int getNodeSize(
154087   sqlite3 *db,                    /* Database handle */
154088   Rtree *pRtree,                  /* Rtree handle */
154089   int isCreate,                   /* True for xCreate, false for xConnect */
154090   char **pzErr                    /* OUT: Error message, if any */
154091 ){
154092   int rc;
154093   char *zSql;
154094   if( isCreate ){
154095     int iPageSize = 0;
154096     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
154097     rc = getIntFromStmt(db, zSql, &iPageSize);
154098     if( rc==SQLITE_OK ){
154099       pRtree->iNodeSize = iPageSize-64;
154100       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
154101         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
154102       }
154103     }else{
154104       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
154105     }
154106   }else{
154107     zSql = sqlite3_mprintf(
154108         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
154109         pRtree->zDb, pRtree->zName
154110     );
154111     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
154112     if( rc!=SQLITE_OK ){
154113       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
154114     }
154115   }
154116 
154117   sqlite3_free(zSql);
154118   return rc;
154119 }
154120 
154121 /*
154122 ** This function is the implementation of both the xConnect and xCreate
154123 ** methods of the r-tree virtual table.
154124 **
154125 **   argv[0]   -> module name
154126 **   argv[1]   -> database name
154127 **   argv[2]   -> table name
154128 **   argv[...] -> column names...
154129 */
154130 static int rtreeInit(
154131   sqlite3 *db,                        /* Database connection */
154132   void *pAux,                         /* One of the RTREE_COORD_* constants */
154133   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
154134   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
154135   char **pzErr,                       /* OUT: Error message, if any */
154136   int isCreate                        /* True for xCreate, false for xConnect */
154137 ){
154138   int rc = SQLITE_OK;
154139   Rtree *pRtree;
154140   int nDb;              /* Length of string argv[1] */
154141   int nName;            /* Length of string argv[2] */
154142   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
154143 
154144   const char *aErrMsg[] = {
154145     0,                                                    /* 0 */
154146     "Wrong number of columns for an rtree table",         /* 1 */
154147     "Too few columns for an rtree table",                 /* 2 */
154148     "Too many columns for an rtree table"                 /* 3 */
154149   };
154150 
154151   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
154152   if( aErrMsg[iErr] ){
154153     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
154154     return SQLITE_ERROR;
154155   }
154156 
154157   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
154158 
154159   /* Allocate the sqlite3_vtab structure */
154160   nDb = (int)strlen(argv[1]);
154161   nName = (int)strlen(argv[2]);
154162   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
154163   if( !pRtree ){
154164     return SQLITE_NOMEM;
154165   }
154166   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
154167   pRtree->nBusy = 1;
154168   pRtree->base.pModule = &rtreeModule;
154169   pRtree->zDb = (char *)&pRtree[1];
154170   pRtree->zName = &pRtree->zDb[nDb+1];
154171   pRtree->nDim = (argc-4)/2;
154172   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
154173   pRtree->eCoordType = eCoordType;
154174   memcpy(pRtree->zDb, argv[1], nDb);
154175   memcpy(pRtree->zName, argv[2], nName);
154176 
154177   /* Figure out the node size to use. */
154178   rc = getNodeSize(db, pRtree, isCreate, pzErr);
154179 
154180   /* Create/Connect to the underlying relational database schema. If
154181   ** that is successful, call sqlite3_declare_vtab() to configure
154182   ** the r-tree table schema.
154183   */
154184   if( rc==SQLITE_OK ){
154185     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
154186       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
154187     }else{
154188       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
154189       char *zTmp;
154190       int ii;
154191       for(ii=4; zSql && ii<argc; ii++){
154192         zTmp = zSql;
154193         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
154194         sqlite3_free(zTmp);
154195       }
154196       if( zSql ){
154197         zTmp = zSql;
154198         zSql = sqlite3_mprintf("%s);", zTmp);
154199         sqlite3_free(zTmp);
154200       }
154201       if( !zSql ){
154202         rc = SQLITE_NOMEM;
154203       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
154204         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
154205       }
154206       sqlite3_free(zSql);
154207     }
154208   }
154209 
154210   if( rc==SQLITE_OK ){
154211     *ppVtab = (sqlite3_vtab *)pRtree;
154212   }else{
154213     assert( *ppVtab==0 );
154214     assert( pRtree->nBusy==1 );
154215     rtreeRelease(pRtree);
154216   }
154217   return rc;
154218 }
154219 
154220 
154221 /*
154222 ** Implementation of a scalar function that decodes r-tree nodes to
154223 ** human readable strings. This can be used for debugging and analysis.
154224 **
154225 ** The scalar function takes two arguments: (1) the number of dimensions
154226 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
154227 ** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
154228 ** deserialize all nodes, a statement like:
154229 **
154230 **   SELECT rtreenode(2, data) FROM rt_node;
154231 **
154232 ** The human readable string takes the form of a Tcl list with one
154233 ** entry for each cell in the r-tree node. Each entry is itself a
154234 ** list, containing the 8-byte rowid/pageno followed by the
154235 ** <num-dimension>*2 coordinates.
154236 */
154237 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
154238   char *zText = 0;
154239   RtreeNode node;
154240   Rtree tree;
154241   int ii;
154242 
154243   UNUSED_PARAMETER(nArg);
154244   memset(&node, 0, sizeof(RtreeNode));
154245   memset(&tree, 0, sizeof(Rtree));
154246   tree.nDim = sqlite3_value_int(apArg[0]);
154247   tree.nBytesPerCell = 8 + 8 * tree.nDim;
154248   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
154249 
154250   for(ii=0; ii<NCELL(&node); ii++){
154251     char zCell[512];
154252     int nCell = 0;
154253     RtreeCell cell;
154254     int jj;
154255 
154256     nodeGetCell(&tree, &node, ii, &cell);
154257     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
154258     nCell = (int)strlen(zCell);
154259     for(jj=0; jj<tree.nDim*2; jj++){
154260 #ifndef SQLITE_RTREE_INT_ONLY
154261       sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
154262                        (double)cell.aCoord[jj].f);
154263 #else
154264       sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
154265                        cell.aCoord[jj].i);
154266 #endif
154267       nCell = (int)strlen(zCell);
154268     }
154269 
154270     if( zText ){
154271       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
154272       sqlite3_free(zText);
154273       zText = zTextNew;
154274     }else{
154275       zText = sqlite3_mprintf("{%s}", zCell);
154276     }
154277   }
154278 
154279   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
154280 }
154281 
154282 /* This routine implements an SQL function that returns the "depth" parameter
154283 ** from the front of a blob that is an r-tree node.  For example:
154284 **
154285 **     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
154286 **
154287 ** The depth value is 0 for all nodes other than the root node, and the root
154288 ** node always has nodeno=1, so the example above is the primary use for this
154289 ** routine.  This routine is intended for testing and analysis only.
154290 */
154291 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
154292   UNUSED_PARAMETER(nArg);
154293   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
154294    || sqlite3_value_bytes(apArg[0])<2
154295   ){
154296     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
154297   }else{
154298     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
154299     sqlite3_result_int(ctx, readInt16(zBlob));
154300   }
154301 }
154302 
154303 /*
154304 ** Register the r-tree module with database handle db. This creates the
154305 ** virtual table module "rtree" and the debugging/analysis scalar
154306 ** function "rtreenode".
154307 */
154308 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
154309   const int utf8 = SQLITE_UTF8;
154310   int rc;
154311 
154312   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
154313   if( rc==SQLITE_OK ){
154314     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
154315   }
154316   if( rc==SQLITE_OK ){
154317 #ifdef SQLITE_RTREE_INT_ONLY
154318     void *c = (void *)RTREE_COORD_INT32;
154319 #else
154320     void *c = (void *)RTREE_COORD_REAL32;
154321 #endif
154322     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
154323   }
154324   if( rc==SQLITE_OK ){
154325     void *c = (void *)RTREE_COORD_INT32;
154326     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
154327   }
154328 
154329   return rc;
154330 }
154331 
154332 /*
154333 ** This routine deletes the RtreeGeomCallback object that was attached
154334 ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
154335 ** or sqlite3_rtree_query_callback().  In other words, this routine is the
154336 ** destructor for an RtreeGeomCallback objecct.  This routine is called when
154337 ** the corresponding SQL function is deleted.
154338 */
154339 static void rtreeFreeCallback(void *p){
154340   RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
154341   if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
154342   sqlite3_free(p);
154343 }
154344 
154345 /*
154346 ** Each call to sqlite3_rtree_geometry_callback() or
154347 ** sqlite3_rtree_query_callback() creates an ordinary SQLite
154348 ** scalar function that is implemented by this routine.
154349 **
154350 ** All this function does is construct an RtreeMatchArg object that
154351 ** contains the geometry-checking callback routines and a list of
154352 ** parameters to this function, then return that RtreeMatchArg object
154353 ** as a BLOB.
154354 **
154355 ** The R-Tree MATCH operator will read the returned BLOB, deserialize
154356 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
154357 ** out which elements of the R-Tree should be returned by the query.
154358 */
154359 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
154360   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
154361   RtreeMatchArg *pBlob;
154362   int nBlob;
154363 
154364   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
154365   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
154366   if( !pBlob ){
154367     sqlite3_result_error_nomem(ctx);
154368   }else{
154369     int i;
154370     pBlob->magic = RTREE_GEOMETRY_MAGIC;
154371     pBlob->cb = pGeomCtx[0];
154372     pBlob->nParam = nArg;
154373     for(i=0; i<nArg; i++){
154374 #ifdef SQLITE_RTREE_INT_ONLY
154375       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
154376 #else
154377       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
154378 #endif
154379     }
154380     sqlite3_result_blob(ctx, pBlob, nBlob, sqlite3_free);
154381   }
154382 }
154383 
154384 /*
154385 ** Register a new geometry function for use with the r-tree MATCH operator.
154386 */
154387 SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
154388   sqlite3 *db,                  /* Register SQL function on this connection */
154389   const char *zGeom,            /* Name of the new SQL function */
154390   int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
154391   void *pContext                /* Extra data associated with the callback */
154392 ){
154393   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
154394 
154395   /* Allocate and populate the context object. */
154396   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
154397   if( !pGeomCtx ) return SQLITE_NOMEM;
154398   pGeomCtx->xGeom = xGeom;
154399   pGeomCtx->xQueryFunc = 0;
154400   pGeomCtx->xDestructor = 0;
154401   pGeomCtx->pContext = pContext;
154402   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
154403       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
154404   );
154405 }
154406 
154407 /*
154408 ** Register a new 2nd-generation geometry function for use with the
154409 ** r-tree MATCH operator.
154410 */
154411 SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
154412   sqlite3 *db,                 /* Register SQL function on this connection */
154413   const char *zQueryFunc,      /* Name of new SQL function */
154414   int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
154415   void *pContext,              /* Extra data passed into the callback */
154416   void (*xDestructor)(void*)   /* Destructor for the extra data */
154417 ){
154418   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
154419 
154420   /* Allocate and populate the context object. */
154421   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
154422   if( !pGeomCtx ) return SQLITE_NOMEM;
154423   pGeomCtx->xGeom = 0;
154424   pGeomCtx->xQueryFunc = xQueryFunc;
154425   pGeomCtx->xDestructor = xDestructor;
154426   pGeomCtx->pContext = pContext;
154427   return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
154428       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
154429   );
154430 }
154431 
154432 #if !SQLITE_CORE
154433 #ifdef _WIN32
154434 __declspec(dllexport)
154435 #endif
154436 SQLITE_API int SQLITE_STDCALL sqlite3_rtree_init(
154437   sqlite3 *db,
154438   char **pzErrMsg,
154439   const sqlite3_api_routines *pApi
154440 ){
154441   SQLITE_EXTENSION_INIT2(pApi)
154442   return sqlite3RtreeInit(db);
154443 }
154444 #endif
154445 
154446 #endif
154447 
154448 /************** End of rtree.c ***********************************************/
154449 /************** Begin file icu.c *********************************************/
154450 /*
154451 ** 2007 May 6
154452 **
154453 ** The author disclaims copyright to this source code.  In place of
154454 ** a legal notice, here is a blessing:
154455 **
154456 **    May you do good and not evil.
154457 **    May you find forgiveness for yourself and forgive others.
154458 **    May you share freely, never taking more than you give.
154459 **
154460 *************************************************************************
154461 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
154462 **
154463 ** This file implements an integration between the ICU library
154464 ** ("International Components for Unicode", an open-source library
154465 ** for handling unicode data) and SQLite. The integration uses
154466 ** ICU to provide the following to SQLite:
154467 **
154468 **   * An implementation of the SQL regexp() function (and hence REGEXP
154469 **     operator) using the ICU uregex_XX() APIs.
154470 **
154471 **   * Implementations of the SQL scalar upper() and lower() functions
154472 **     for case mapping.
154473 **
154474 **   * Integration of ICU and SQLite collation sequences.
154475 **
154476 **   * An implementation of the LIKE operator that uses ICU to
154477 **     provide case-independent matching.
154478 */
154479 
154480 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
154481 
154482 /* Include ICU headers */
154483 #include <unicode/utypes.h>
154484 #include <unicode/uregex.h>
154485 #include <unicode/ustring.h>
154486 #include <unicode/ucol.h>
154487 
154488 /* #include <assert.h> */
154489 
154490 #ifndef SQLITE_CORE
154491   SQLITE_EXTENSION_INIT1
154492 #else
154493 #endif
154494 
154495 /*
154496 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
154497 ** operator.
154498 */
154499 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
154500 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
154501 #endif
154502 
154503 /*
154504 ** Version of sqlite3_free() that is always a function, never a macro.
154505 */
154506 static void xFree(void *p){
154507   sqlite3_free(p);
154508 }
154509 
154510 /*
154511 ** Compare two UTF-8 strings for equality where the first string is
154512 ** a "LIKE" expression. Return true (1) if they are the same and
154513 ** false (0) if they are different.
154514 */
154515 static int icuLikeCompare(
154516   const uint8_t *zPattern,   /* LIKE pattern */
154517   const uint8_t *zString,    /* The UTF-8 string to compare against */
154518   const UChar32 uEsc         /* The escape character */
154519 ){
154520   static const int MATCH_ONE = (UChar32)'_';
154521   static const int MATCH_ALL = (UChar32)'%';
154522 
154523   int iPattern = 0;       /* Current byte index in zPattern */
154524   int iString = 0;        /* Current byte index in zString */
154525 
154526   int prevEscape = 0;     /* True if the previous character was uEsc */
154527 
154528   while( zPattern[iPattern]!=0 ){
154529 
154530     /* Read (and consume) the next character from the input pattern. */
154531     UChar32 uPattern;
154532     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
154533     assert(uPattern!=0);
154534 
154535     /* There are now 4 possibilities:
154536     **
154537     **     1. uPattern is an unescaped match-all character "%",
154538     **     2. uPattern is an unescaped match-one character "_",
154539     **     3. uPattern is an unescaped escape character, or
154540     **     4. uPattern is to be handled as an ordinary character
154541     */
154542     if( !prevEscape && uPattern==MATCH_ALL ){
154543       /* Case 1. */
154544       uint8_t c;
154545 
154546       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
154547       ** MATCH_ALL. For each MATCH_ONE, skip one character in the
154548       ** test string.
154549       */
154550       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
154551         if( c==MATCH_ONE ){
154552           if( zString[iString]==0 ) return 0;
154553           U8_FWD_1_UNSAFE(zString, iString);
154554         }
154555         iPattern++;
154556       }
154557 
154558       if( zPattern[iPattern]==0 ) return 1;
154559 
154560       while( zString[iString] ){
154561         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
154562           return 1;
154563         }
154564         U8_FWD_1_UNSAFE(zString, iString);
154565       }
154566       return 0;
154567 
154568     }else if( !prevEscape && uPattern==MATCH_ONE ){
154569       /* Case 2. */
154570       if( zString[iString]==0 ) return 0;
154571       U8_FWD_1_UNSAFE(zString, iString);
154572 
154573     }else if( !prevEscape && uPattern==uEsc){
154574       /* Case 3. */
154575       prevEscape = 1;
154576 
154577     }else{
154578       /* Case 4. */
154579       UChar32 uString;
154580       U8_NEXT_UNSAFE(zString, iString, uString);
154581       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
154582       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
154583       if( uString!=uPattern ){
154584         return 0;
154585       }
154586       prevEscape = 0;
154587     }
154588   }
154589 
154590   return zString[iString]==0;
154591 }
154592 
154593 /*
154594 ** Implementation of the like() SQL function.  This function implements
154595 ** the build-in LIKE operator.  The first argument to the function is the
154596 ** pattern and the second argument is the string.  So, the SQL statements:
154597 **
154598 **       A LIKE B
154599 **
154600 ** is implemented as like(B, A). If there is an escape character E,
154601 **
154602 **       A LIKE B ESCAPE E
154603 **
154604 ** is mapped to like(B, A, E).
154605 */
154606 static void icuLikeFunc(
154607   sqlite3_context *context,
154608   int argc,
154609   sqlite3_value **argv
154610 ){
154611   const unsigned char *zA = sqlite3_value_text(argv[0]);
154612   const unsigned char *zB = sqlite3_value_text(argv[1]);
154613   UChar32 uEsc = 0;
154614 
154615   /* Limit the length of the LIKE or GLOB pattern to avoid problems
154616   ** of deep recursion and N*N behavior in patternCompare().
154617   */
154618   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
154619     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
154620     return;
154621   }
154622 
154623 
154624   if( argc==3 ){
154625     /* The escape character string must consist of a single UTF-8 character.
154626     ** Otherwise, return an error.
154627     */
154628     int nE= sqlite3_value_bytes(argv[2]);
154629     const unsigned char *zE = sqlite3_value_text(argv[2]);
154630     int i = 0;
154631     if( zE==0 ) return;
154632     U8_NEXT(zE, i, nE, uEsc);
154633     if( i!=nE){
154634       sqlite3_result_error(context,
154635           "ESCAPE expression must be a single character", -1);
154636       return;
154637     }
154638   }
154639 
154640   if( zA && zB ){
154641     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
154642   }
154643 }
154644 
154645 /*
154646 ** This function is called when an ICU function called from within
154647 ** the implementation of an SQL scalar function returns an error.
154648 **
154649 ** The scalar function context passed as the first argument is
154650 ** loaded with an error message based on the following two args.
154651 */
154652 static void icuFunctionError(
154653   sqlite3_context *pCtx,       /* SQLite scalar function context */
154654   const char *zName,           /* Name of ICU function that failed */
154655   UErrorCode e                 /* Error code returned by ICU function */
154656 ){
154657   char zBuf[128];
154658   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
154659   zBuf[127] = '\0';
154660   sqlite3_result_error(pCtx, zBuf, -1);
154661 }
154662 
154663 /*
154664 ** Function to delete compiled regexp objects. Registered as
154665 ** a destructor function with sqlite3_set_auxdata().
154666 */
154667 static void icuRegexpDelete(void *p){
154668   URegularExpression *pExpr = (URegularExpression *)p;
154669   uregex_close(pExpr);
154670 }
154671 
154672 /*
154673 ** Implementation of SQLite REGEXP operator. This scalar function takes
154674 ** two arguments. The first is a regular expression pattern to compile
154675 ** the second is a string to match against that pattern. If either
154676 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
154677 ** is 1 if the string matches the pattern, or 0 otherwise.
154678 **
154679 ** SQLite maps the regexp() function to the regexp() operator such
154680 ** that the following two are equivalent:
154681 **
154682 **     zString REGEXP zPattern
154683 **     regexp(zPattern, zString)
154684 **
154685 ** Uses the following ICU regexp APIs:
154686 **
154687 **     uregex_open()
154688 **     uregex_matches()
154689 **     uregex_close()
154690 */
154691 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
154692   UErrorCode status = U_ZERO_ERROR;
154693   URegularExpression *pExpr;
154694   UBool res;
154695   const UChar *zString = sqlite3_value_text16(apArg[1]);
154696 
154697   (void)nArg;  /* Unused parameter */
154698 
154699   /* If the left hand side of the regexp operator is NULL,
154700   ** then the result is also NULL.
154701   */
154702   if( !zString ){
154703     return;
154704   }
154705 
154706   pExpr = sqlite3_get_auxdata(p, 0);
154707   if( !pExpr ){
154708     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
154709     if( !zPattern ){
154710       return;
154711     }
154712     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
154713 
154714     if( U_SUCCESS(status) ){
154715       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
154716     }else{
154717       assert(!pExpr);
154718       icuFunctionError(p, "uregex_open", status);
154719       return;
154720     }
154721   }
154722 
154723   /* Configure the text that the regular expression operates on. */
154724   uregex_setText(pExpr, zString, -1, &status);
154725   if( !U_SUCCESS(status) ){
154726     icuFunctionError(p, "uregex_setText", status);
154727     return;
154728   }
154729 
154730   /* Attempt the match */
154731   res = uregex_matches(pExpr, 0, &status);
154732   if( !U_SUCCESS(status) ){
154733     icuFunctionError(p, "uregex_matches", status);
154734     return;
154735   }
154736 
154737   /* Set the text that the regular expression operates on to a NULL
154738   ** pointer. This is not really necessary, but it is tidier than
154739   ** leaving the regular expression object configured with an invalid
154740   ** pointer after this function returns.
154741   */
154742   uregex_setText(pExpr, 0, 0, &status);
154743 
154744   /* Return 1 or 0. */
154745   sqlite3_result_int(p, res ? 1 : 0);
154746 }
154747 
154748 /*
154749 ** Implementations of scalar functions for case mapping - upper() and
154750 ** lower(). Function upper() converts its input to upper-case (ABC).
154751 ** Function lower() converts to lower-case (abc).
154752 **
154753 ** ICU provides two types of case mapping, "general" case mapping and
154754 ** "language specific". Refer to ICU documentation for the differences
154755 ** between the two.
154756 **
154757 ** To utilise "general" case mapping, the upper() or lower() scalar
154758 ** functions are invoked with one argument:
154759 **
154760 **     upper('ABC') -> 'abc'
154761 **     lower('abc') -> 'ABC'
154762 **
154763 ** To access ICU "language specific" case mapping, upper() or lower()
154764 ** should be invoked with two arguments. The second argument is the name
154765 ** of the locale to use. Passing an empty string ("") or SQL NULL value
154766 ** as the second argument is the same as invoking the 1 argument version
154767 ** of upper() or lower().
154768 **
154769 **     lower('I', 'en_us') -> 'i'
154770 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
154771 **
154772 ** http://www.icu-project.org/userguide/posix.html#case_mappings
154773 */
154774 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
154775   const UChar *zInput;
154776   UChar *zOutput;
154777   int nInput;
154778   int nOutput;
154779 
154780   UErrorCode status = U_ZERO_ERROR;
154781   const char *zLocale = 0;
154782 
154783   assert(nArg==1 || nArg==2);
154784   if( nArg==2 ){
154785     zLocale = (const char *)sqlite3_value_text(apArg[1]);
154786   }
154787 
154788   zInput = sqlite3_value_text16(apArg[0]);
154789   if( !zInput ){
154790     return;
154791   }
154792   nInput = sqlite3_value_bytes16(apArg[0]);
154793 
154794   nOutput = nInput * 2 + 2;
154795   zOutput = sqlite3_malloc(nOutput);
154796   if( !zOutput ){
154797     return;
154798   }
154799 
154800   if( sqlite3_user_data(p) ){
154801     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
154802   }else{
154803     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
154804   }
154805 
154806   if( !U_SUCCESS(status) ){
154807     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
154808     return;
154809   }
154810 
154811   sqlite3_result_text16(p, zOutput, -1, xFree);
154812 }
154813 
154814 /*
154815 ** Collation sequence destructor function. The pCtx argument points to
154816 ** a UCollator structure previously allocated using ucol_open().
154817 */
154818 static void icuCollationDel(void *pCtx){
154819   UCollator *p = (UCollator *)pCtx;
154820   ucol_close(p);
154821 }
154822 
154823 /*
154824 ** Collation sequence comparison function. The pCtx argument points to
154825 ** a UCollator structure previously allocated using ucol_open().
154826 */
154827 static int icuCollationColl(
154828   void *pCtx,
154829   int nLeft,
154830   const void *zLeft,
154831   int nRight,
154832   const void *zRight
154833 ){
154834   UCollationResult res;
154835   UCollator *p = (UCollator *)pCtx;
154836   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
154837   switch( res ){
154838     case UCOL_LESS:    return -1;
154839     case UCOL_GREATER: return +1;
154840     case UCOL_EQUAL:   return 0;
154841   }
154842   assert(!"Unexpected return value from ucol_strcoll()");
154843   return 0;
154844 }
154845 
154846 /*
154847 ** Implementation of the scalar function icu_load_collation().
154848 **
154849 ** This scalar function is used to add ICU collation based collation
154850 ** types to an SQLite database connection. It is intended to be called
154851 ** as follows:
154852 **
154853 **     SELECT icu_load_collation(<locale>, <collation-name>);
154854 **
154855 ** Where <locale> is a string containing an ICU locale identifier (i.e.
154856 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
154857 ** collation sequence to create.
154858 */
154859 static void icuLoadCollation(
154860   sqlite3_context *p,
154861   int nArg,
154862   sqlite3_value **apArg
154863 ){
154864   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
154865   UErrorCode status = U_ZERO_ERROR;
154866   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
154867   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
154868   UCollator *pUCollator;    /* ICU library collation object */
154869   int rc;                   /* Return code from sqlite3_create_collation_x() */
154870 
154871   assert(nArg==2);
154872   zLocale = (const char *)sqlite3_value_text(apArg[0]);
154873   zName = (const char *)sqlite3_value_text(apArg[1]);
154874 
154875   if( !zLocale || !zName ){
154876     return;
154877   }
154878 
154879   pUCollator = ucol_open(zLocale, &status);
154880   if( !U_SUCCESS(status) ){
154881     icuFunctionError(p, "ucol_open", status);
154882     return;
154883   }
154884   assert(p);
154885 
154886   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
154887       icuCollationColl, icuCollationDel
154888   );
154889   if( rc!=SQLITE_OK ){
154890     ucol_close(pUCollator);
154891     sqlite3_result_error(p, "Error registering collation function", -1);
154892   }
154893 }
154894 
154895 /*
154896 ** Register the ICU extension functions with database db.
154897 */
154898 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
154899   struct IcuScalar {
154900     const char *zName;                        /* Function name */
154901     int nArg;                                 /* Number of arguments */
154902     int enc;                                  /* Optimal text encoding */
154903     void *pContext;                           /* sqlite3_user_data() context */
154904     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
154905   } scalars[] = {
154906     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
154907 
154908     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
154909     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
154910     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
154911     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
154912 
154913     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
154914     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
154915     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
154916     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
154917 
154918     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
154919     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
154920 
154921     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
154922   };
154923 
154924   int rc = SQLITE_OK;
154925   int i;
154926 
154927   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
154928     struct IcuScalar *p = &scalars[i];
154929     rc = sqlite3_create_function(
154930         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
154931     );
154932   }
154933 
154934   return rc;
154935 }
154936 
154937 #if !SQLITE_CORE
154938 #ifdef _WIN32
154939 __declspec(dllexport)
154940 #endif
154941 SQLITE_API int SQLITE_STDCALL sqlite3_icu_init(
154942   sqlite3 *db,
154943   char **pzErrMsg,
154944   const sqlite3_api_routines *pApi
154945 ){
154946   SQLITE_EXTENSION_INIT2(pApi)
154947   return sqlite3IcuInit(db);
154948 }
154949 #endif
154950 
154951 #endif
154952 
154953 /************** End of icu.c *************************************************/
154954 /************** Begin file fts3_icu.c ****************************************/
154955 /*
154956 ** 2007 June 22
154957 **
154958 ** The author disclaims copyright to this source code.  In place of
154959 ** a legal notice, here is a blessing:
154960 **
154961 **    May you do good and not evil.
154962 **    May you find forgiveness for yourself and forgive others.
154963 **    May you share freely, never taking more than you give.
154964 **
154965 *************************************************************************
154966 ** This file implements a tokenizer for fts3 based on the ICU library.
154967 */
154968 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
154969 #ifdef SQLITE_ENABLE_ICU
154970 
154971 /* #include <assert.h> */
154972 /* #include <string.h> */
154973 
154974 #include <unicode/ubrk.h>
154975 /* #include <unicode/ucol.h> */
154976 /* #include <unicode/ustring.h> */
154977 #include <unicode/utf16.h>
154978 
154979 typedef struct IcuTokenizer IcuTokenizer;
154980 typedef struct IcuCursor IcuCursor;
154981 
154982 struct IcuTokenizer {
154983   sqlite3_tokenizer base;
154984   char *zLocale;
154985 };
154986 
154987 struct IcuCursor {
154988   sqlite3_tokenizer_cursor base;
154989 
154990   UBreakIterator *pIter;      /* ICU break-iterator object */
154991   int nChar;                  /* Number of UChar elements in pInput */
154992   UChar *aChar;               /* Copy of input using utf-16 encoding */
154993   int *aOffset;               /* Offsets of each character in utf-8 input */
154994 
154995   int nBuffer;
154996   char *zBuffer;
154997 
154998   int iToken;
154999 };
155000 
155001 /*
155002 ** Create a new tokenizer instance.
155003 */
155004 static int icuCreate(
155005   int argc,                            /* Number of entries in argv[] */
155006   const char * const *argv,            /* Tokenizer creation arguments */
155007   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
155008 ){
155009   IcuTokenizer *p;
155010   int n = 0;
155011 
155012   if( argc>0 ){
155013     n = strlen(argv[0])+1;
155014   }
155015   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
155016   if( !p ){
155017     return SQLITE_NOMEM;
155018   }
155019   memset(p, 0, sizeof(IcuTokenizer));
155020 
155021   if( n ){
155022     p->zLocale = (char *)&p[1];
155023     memcpy(p->zLocale, argv[0], n);
155024   }
155025 
155026   *ppTokenizer = (sqlite3_tokenizer *)p;
155027 
155028   return SQLITE_OK;
155029 }
155030 
155031 /*
155032 ** Destroy a tokenizer
155033 */
155034 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
155035   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
155036   sqlite3_free(p);
155037   return SQLITE_OK;
155038 }
155039 
155040 /*
155041 ** Prepare to begin tokenizing a particular string.  The input
155042 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
155043 ** used to incrementally tokenize this string is returned in
155044 ** *ppCursor.
155045 */
155046 static int icuOpen(
155047   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
155048   const char *zInput,                    /* Input string */
155049   int nInput,                            /* Length of zInput in bytes */
155050   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
155051 ){
155052   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
155053   IcuCursor *pCsr;
155054 
155055   const int32_t opt = U_FOLD_CASE_DEFAULT;
155056   UErrorCode status = U_ZERO_ERROR;
155057   int nChar;
155058 
155059   UChar32 c;
155060   int iInput = 0;
155061   int iOut = 0;
155062 
155063   *ppCursor = 0;
155064 
155065   if( zInput==0 ){
155066     nInput = 0;
155067     zInput = "";
155068   }else if( nInput<0 ){
155069     nInput = strlen(zInput);
155070   }
155071   nChar = nInput+1;
155072   pCsr = (IcuCursor *)sqlite3_malloc(
155073       sizeof(IcuCursor) +                /* IcuCursor */
155074       ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
155075       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
155076   );
155077   if( !pCsr ){
155078     return SQLITE_NOMEM;
155079   }
155080   memset(pCsr, 0, sizeof(IcuCursor));
155081   pCsr->aChar = (UChar *)&pCsr[1];
155082   pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
155083 
155084   pCsr->aOffset[iOut] = iInput;
155085   U8_NEXT(zInput, iInput, nInput, c);
155086   while( c>0 ){
155087     int isError = 0;
155088     c = u_foldCase(c, opt);
155089     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
155090     if( isError ){
155091       sqlite3_free(pCsr);
155092       return SQLITE_ERROR;
155093     }
155094     pCsr->aOffset[iOut] = iInput;
155095 
155096     if( iInput<nInput ){
155097       U8_NEXT(zInput, iInput, nInput, c);
155098     }else{
155099       c = 0;
155100     }
155101   }
155102 
155103   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
155104   if( !U_SUCCESS(status) ){
155105     sqlite3_free(pCsr);
155106     return SQLITE_ERROR;
155107   }
155108   pCsr->nChar = iOut;
155109 
155110   ubrk_first(pCsr->pIter);
155111   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
155112   return SQLITE_OK;
155113 }
155114 
155115 /*
155116 ** Close a tokenization cursor previously opened by a call to icuOpen().
155117 */
155118 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
155119   IcuCursor *pCsr = (IcuCursor *)pCursor;
155120   ubrk_close(pCsr->pIter);
155121   sqlite3_free(pCsr->zBuffer);
155122   sqlite3_free(pCsr);
155123   return SQLITE_OK;
155124 }
155125 
155126 /*
155127 ** Extract the next token from a tokenization cursor.
155128 */
155129 static int icuNext(
155130   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
155131   const char **ppToken,               /* OUT: *ppToken is the token text */
155132   int *pnBytes,                       /* OUT: Number of bytes in token */
155133   int *piStartOffset,                 /* OUT: Starting offset of token */
155134   int *piEndOffset,                   /* OUT: Ending offset of token */
155135   int *piPosition                     /* OUT: Position integer of token */
155136 ){
155137   IcuCursor *pCsr = (IcuCursor *)pCursor;
155138 
155139   int iStart = 0;
155140   int iEnd = 0;
155141   int nByte = 0;
155142 
155143   while( iStart==iEnd ){
155144     UChar32 c;
155145 
155146     iStart = ubrk_current(pCsr->pIter);
155147     iEnd = ubrk_next(pCsr->pIter);
155148     if( iEnd==UBRK_DONE ){
155149       return SQLITE_DONE;
155150     }
155151 
155152     while( iStart<iEnd ){
155153       int iWhite = iStart;
155154       U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
155155       if( u_isspace(c) ){
155156         iStart = iWhite;
155157       }else{
155158         break;
155159       }
155160     }
155161     assert(iStart<=iEnd);
155162   }
155163 
155164   do {
155165     UErrorCode status = U_ZERO_ERROR;
155166     if( nByte ){
155167       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
155168       if( !zNew ){
155169         return SQLITE_NOMEM;
155170       }
155171       pCsr->zBuffer = zNew;
155172       pCsr->nBuffer = nByte;
155173     }
155174 
155175     u_strToUTF8(
155176         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
155177         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
155178         &status                                  /* Output success/failure */
155179     );
155180   } while( nByte>pCsr->nBuffer );
155181 
155182   *ppToken = pCsr->zBuffer;
155183   *pnBytes = nByte;
155184   *piStartOffset = pCsr->aOffset[iStart];
155185   *piEndOffset = pCsr->aOffset[iEnd];
155186   *piPosition = pCsr->iToken++;
155187 
155188   return SQLITE_OK;
155189 }
155190 
155191 /*
155192 ** The set of routines that implement the simple tokenizer
155193 */
155194 static const sqlite3_tokenizer_module icuTokenizerModule = {
155195   0,                           /* iVersion */
155196   icuCreate,                   /* xCreate  */
155197   icuDestroy,                  /* xCreate  */
155198   icuOpen,                     /* xOpen    */
155199   icuClose,                    /* xClose   */
155200   icuNext,                     /* xNext    */
155201 };
155202 
155203 /*
155204 ** Set *ppModule to point at the implementation of the ICU tokenizer.
155205 */
155206 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
155207   sqlite3_tokenizer_module const**ppModule
155208 ){
155209   *ppModule = &icuTokenizerModule;
155210 }
155211 
155212 #endif /* defined(SQLITE_ENABLE_ICU) */
155213 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
155214 
155215 /************** End of fts3_icu.c ********************************************/
155216 /************** Begin file dbstat.c ******************************************/
155217 /*
155218 ** 2010 July 12
155219 **
155220 ** The author disclaims copyright to this source code.  In place of
155221 ** a legal notice, here is a blessing:
155222 **
155223 **    May you do good and not evil.
155224 **    May you find forgiveness for yourself and forgive others.
155225 **    May you share freely, never taking more than you give.
155226 **
155227 ******************************************************************************
155228 **
155229 ** This file contains an implementation of the "dbstat" virtual table.
155230 **
155231 ** The dbstat virtual table is used to extract low-level formatting
155232 ** information from an SQLite database in order to implement the
155233 ** "sqlite3_analyzer" utility.  See the ../tool/spaceanal.tcl script
155234 ** for an example implementation.
155235 */
155236 
155237 #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
155238     && !defined(SQLITE_OMIT_VIRTUALTABLE)
155239 
155240 /*
155241 ** Page paths:
155242 **
155243 **   The value of the 'path' column describes the path taken from the
155244 **   root-node of the b-tree structure to each page. The value of the
155245 **   root-node path is '/'.
155246 **
155247 **   The value of the path for the left-most child page of the root of
155248 **   a b-tree is '/000/'. (Btrees store content ordered from left to right
155249 **   so the pages to the left have smaller keys than the pages to the right.)
155250 **   The next to left-most child of the root page is
155251 **   '/001', and so on, each sibling page identified by a 3-digit hex
155252 **   value. The children of the 451st left-most sibling have paths such
155253 **   as '/1c2/000/, '/1c2/001/' etc.
155254 **
155255 **   Overflow pages are specified by appending a '+' character and a
155256 **   six-digit hexadecimal value to the path to the cell they are linked
155257 **   from. For example, the three overflow pages in a chain linked from
155258 **   the left-most cell of the 450th child of the root page are identified
155259 **   by the paths:
155260 **
155261 **      '/1c2/000+000000'         // First page in overflow chain
155262 **      '/1c2/000+000001'         // Second page in overflow chain
155263 **      '/1c2/000+000002'         // Third page in overflow chain
155264 **
155265 **   If the paths are sorted using the BINARY collation sequence, then
155266 **   the overflow pages associated with a cell will appear earlier in the
155267 **   sort-order than its child page:
155268 **
155269 **      '/1c2/000/'               // Left-most child of 451st child of root
155270 */
155271 #define VTAB_SCHEMA                                                         \
155272   "CREATE TABLE xx( "                                                       \
155273   "  name       STRING,           /* Name of table or index */"             \
155274   "  path       INTEGER,          /* Path to page from root */"             \
155275   "  pageno     INTEGER,          /* Page number */"                        \
155276   "  pagetype   STRING,           /* 'internal', 'leaf' or 'overflow' */"   \
155277   "  ncell      INTEGER,          /* Cells on page (0 for overflow) */"     \
155278   "  payload    INTEGER,          /* Bytes of payload on this page */"      \
155279   "  unused     INTEGER,          /* Bytes of unused space on this page */" \
155280   "  mx_payload INTEGER,          /* Largest payload size of all cells */"  \
155281   "  pgoffset   INTEGER,          /* Offset of page in file */"             \
155282   "  pgsize     INTEGER           /* Size of the page */"                   \
155283   ");"
155284 
155285 
155286 typedef struct StatTable StatTable;
155287 typedef struct StatCursor StatCursor;
155288 typedef struct StatPage StatPage;
155289 typedef struct StatCell StatCell;
155290 
155291 struct StatCell {
155292   int nLocal;                     /* Bytes of local payload */
155293   u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */
155294   int nOvfl;                      /* Entries in aOvfl[] */
155295   u32 *aOvfl;                     /* Array of overflow page numbers */
155296   int nLastOvfl;                  /* Bytes of payload on final overflow page */
155297   int iOvfl;                      /* Iterates through aOvfl[] */
155298 };
155299 
155300 struct StatPage {
155301   u32 iPgno;
155302   DbPage *pPg;
155303   int iCell;
155304 
155305   char *zPath;                    /* Path to this page */
155306 
155307   /* Variables populated by statDecodePage(): */
155308   u8 flags;                       /* Copy of flags byte */
155309   int nCell;                      /* Number of cells on page */
155310   int nUnused;                    /* Number of unused bytes on page */
155311   StatCell *aCell;                /* Array of parsed cells */
155312   u32 iRightChildPg;              /* Right-child page number (or 0) */
155313   int nMxPayload;                 /* Largest payload of any cell on this page */
155314 };
155315 
155316 struct StatCursor {
155317   sqlite3_vtab_cursor base;
155318   sqlite3_stmt *pStmt;            /* Iterates through set of root pages */
155319   int isEof;                      /* After pStmt has returned SQLITE_DONE */
155320 
155321   StatPage aPage[32];
155322   int iPage;                      /* Current entry in aPage[] */
155323 
155324   /* Values to return. */
155325   char *zName;                    /* Value of 'name' column */
155326   char *zPath;                    /* Value of 'path' column */
155327   u32 iPageno;                    /* Value of 'pageno' column */
155328   char *zPagetype;                /* Value of 'pagetype' column */
155329   int nCell;                      /* Value of 'ncell' column */
155330   int nPayload;                   /* Value of 'payload' column */
155331   int nUnused;                    /* Value of 'unused' column */
155332   int nMxPayload;                 /* Value of 'mx_payload' column */
155333   i64 iOffset;                    /* Value of 'pgOffset' column */
155334   int szPage;                     /* Value of 'pgSize' column */
155335 };
155336 
155337 struct StatTable {
155338   sqlite3_vtab base;
155339   sqlite3 *db;
155340   int iDb;                        /* Index of database to analyze */
155341 };
155342 
155343 #ifndef get2byte
155344 # define get2byte(x)   ((x)[0]<<8 | (x)[1])
155345 #endif
155346 
155347 /*
155348 ** Connect to or create a statvfs virtual table.
155349 */
155350 static int statConnect(
155351   sqlite3 *db,
155352   void *pAux,
155353   int argc, const char *const*argv,
155354   sqlite3_vtab **ppVtab,
155355   char **pzErr
155356 ){
155357   StatTable *pTab = 0;
155358   int rc = SQLITE_OK;
155359   int iDb;
155360 
155361   if( argc>=4 ){
155362     iDb = sqlite3FindDbName(db, argv[3]);
155363     if( iDb<0 ){
155364       *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
155365       return SQLITE_ERROR;
155366     }
155367   }else{
155368     iDb = 0;
155369   }
155370   rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
155371   if( rc==SQLITE_OK ){
155372     pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
155373     if( pTab==0 ) rc = SQLITE_NOMEM;
155374   }
155375 
155376   assert( rc==SQLITE_OK || pTab==0 );
155377   if( rc==SQLITE_OK ){
155378     memset(pTab, 0, sizeof(StatTable));
155379     pTab->db = db;
155380     pTab->iDb = iDb;
155381   }
155382 
155383   *ppVtab = (sqlite3_vtab*)pTab;
155384   return rc;
155385 }
155386 
155387 /*
155388 ** Disconnect from or destroy a statvfs virtual table.
155389 */
155390 static int statDisconnect(sqlite3_vtab *pVtab){
155391   sqlite3_free(pVtab);
155392   return SQLITE_OK;
155393 }
155394 
155395 /*
155396 ** There is no "best-index". This virtual table always does a linear
155397 ** scan of the binary VFS log file.
155398 */
155399 static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
155400 
155401   /* Records are always returned in ascending order of (name, path).
155402   ** If this will satisfy the client, set the orderByConsumed flag so that
155403   ** SQLite does not do an external sort.
155404   */
155405   if( ( pIdxInfo->nOrderBy==1
155406      && pIdxInfo->aOrderBy[0].iColumn==0
155407      && pIdxInfo->aOrderBy[0].desc==0
155408      ) ||
155409       ( pIdxInfo->nOrderBy==2
155410      && pIdxInfo->aOrderBy[0].iColumn==0
155411      && pIdxInfo->aOrderBy[0].desc==0
155412      && pIdxInfo->aOrderBy[1].iColumn==1
155413      && pIdxInfo->aOrderBy[1].desc==0
155414      )
155415   ){
155416     pIdxInfo->orderByConsumed = 1;
155417   }
155418 
155419   pIdxInfo->estimatedCost = 10.0;
155420   return SQLITE_OK;
155421 }
155422 
155423 /*
155424 ** Open a new statvfs cursor.
155425 */
155426 static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
155427   StatTable *pTab = (StatTable *)pVTab;
155428   StatCursor *pCsr;
155429   int rc;
155430 
155431   pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
155432   if( pCsr==0 ){
155433     rc = SQLITE_NOMEM;
155434   }else{
155435     char *zSql;
155436     memset(pCsr, 0, sizeof(StatCursor));
155437     pCsr->base.pVtab = pVTab;
155438 
155439     zSql = sqlite3_mprintf(
155440         "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
155441         "  UNION ALL  "
155442         "SELECT name, rootpage, type"
155443         "  FROM \"%w\".sqlite_master WHERE rootpage!=0"
155444         "  ORDER BY name", pTab->db->aDb[pTab->iDb].zName);
155445     if( zSql==0 ){
155446       rc = SQLITE_NOMEM;
155447     }else{
155448       rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
155449       sqlite3_free(zSql);
155450     }
155451     if( rc!=SQLITE_OK ){
155452       sqlite3_free(pCsr);
155453       pCsr = 0;
155454     }
155455   }
155456 
155457   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
155458   return rc;
155459 }
155460 
155461 static void statClearPage(StatPage *p){
155462   int i;
155463   if( p->aCell ){
155464     for(i=0; i<p->nCell; i++){
155465       sqlite3_free(p->aCell[i].aOvfl);
155466     }
155467     sqlite3_free(p->aCell);
155468   }
155469   sqlite3PagerUnref(p->pPg);
155470   sqlite3_free(p->zPath);
155471   memset(p, 0, sizeof(StatPage));
155472 }
155473 
155474 static void statResetCsr(StatCursor *pCsr){
155475   int i;
155476   sqlite3_reset(pCsr->pStmt);
155477   for(i=0; i<ArraySize(pCsr->aPage); i++){
155478     statClearPage(&pCsr->aPage[i]);
155479   }
155480   pCsr->iPage = 0;
155481   sqlite3_free(pCsr->zPath);
155482   pCsr->zPath = 0;
155483 }
155484 
155485 /*
155486 ** Close a statvfs cursor.
155487 */
155488 static int statClose(sqlite3_vtab_cursor *pCursor){
155489   StatCursor *pCsr = (StatCursor *)pCursor;
155490   statResetCsr(pCsr);
155491   sqlite3_finalize(pCsr->pStmt);
155492   sqlite3_free(pCsr);
155493   return SQLITE_OK;
155494 }
155495 
155496 static void getLocalPayload(
155497   int nUsable,                    /* Usable bytes per page */
155498   u8 flags,                       /* Page flags */
155499   int nTotal,                     /* Total record (payload) size */
155500   int *pnLocal                    /* OUT: Bytes stored locally */
155501 ){
155502   int nLocal;
155503   int nMinLocal;
155504   int nMaxLocal;
155505 
155506   if( flags==0x0D ){              /* Table leaf node */
155507     nMinLocal = (nUsable - 12) * 32 / 255 - 23;
155508     nMaxLocal = nUsable - 35;
155509   }else{                          /* Index interior and leaf nodes */
155510     nMinLocal = (nUsable - 12) * 32 / 255 - 23;
155511     nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
155512   }
155513 
155514   nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
155515   if( nLocal>nMaxLocal ) nLocal = nMinLocal;
155516   *pnLocal = nLocal;
155517 }
155518 
155519 static int statDecodePage(Btree *pBt, StatPage *p){
155520   int nUnused;
155521   int iOff;
155522   int nHdr;
155523   int isLeaf;
155524   int szPage;
155525 
155526   u8 *aData = sqlite3PagerGetData(p->pPg);
155527   u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
155528 
155529   p->flags = aHdr[0];
155530   p->nCell = get2byte(&aHdr[3]);
155531   p->nMxPayload = 0;
155532 
155533   isLeaf = (p->flags==0x0A || p->flags==0x0D);
155534   nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
155535 
155536   nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
155537   nUnused += (int)aHdr[7];
155538   iOff = get2byte(&aHdr[1]);
155539   while( iOff ){
155540     nUnused += get2byte(&aData[iOff+2]);
155541     iOff = get2byte(&aData[iOff]);
155542   }
155543   p->nUnused = nUnused;
155544   p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
155545   szPage = sqlite3BtreeGetPageSize(pBt);
155546 
155547   if( p->nCell ){
155548     int i;                        /* Used to iterate through cells */
155549     int nUsable;                  /* Usable bytes per page */
155550 
155551     sqlite3BtreeEnter(pBt);
155552     nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
155553     sqlite3BtreeLeave(pBt);
155554     p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
155555     if( p->aCell==0 ) return SQLITE_NOMEM;
155556     memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
155557 
155558     for(i=0; i<p->nCell; i++){
155559       StatCell *pCell = &p->aCell[i];
155560 
155561       iOff = get2byte(&aData[nHdr+i*2]);
155562       if( !isLeaf ){
155563         pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
155564         iOff += 4;
155565       }
155566       if( p->flags==0x05 ){
155567         /* A table interior node. nPayload==0. */
155568       }else{
155569         u32 nPayload;             /* Bytes of payload total (local+overflow) */
155570         int nLocal;               /* Bytes of payload stored locally */
155571         iOff += getVarint32(&aData[iOff], nPayload);
155572         if( p->flags==0x0D ){
155573           u64 dummy;
155574           iOff += sqlite3GetVarint(&aData[iOff], &dummy);
155575         }
155576         if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
155577         getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
155578         pCell->nLocal = nLocal;
155579         assert( nLocal>=0 );
155580         assert( nPayload>=(u32)nLocal );
155581         assert( nLocal<=(nUsable-35) );
155582         if( nPayload>(u32)nLocal ){
155583           int j;
155584           int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
155585           pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
155586           pCell->nOvfl = nOvfl;
155587           pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
155588           if( pCell->aOvfl==0 ) return SQLITE_NOMEM;
155589           pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
155590           for(j=1; j<nOvfl; j++){
155591             int rc;
155592             u32 iPrev = pCell->aOvfl[j-1];
155593             DbPage *pPg = 0;
155594             rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg);
155595             if( rc!=SQLITE_OK ){
155596               assert( pPg==0 );
155597               return rc;
155598             }
155599             pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
155600             sqlite3PagerUnref(pPg);
155601           }
155602         }
155603       }
155604     }
155605   }
155606 
155607   return SQLITE_OK;
155608 }
155609 
155610 /*
155611 ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
155612 ** the current value of pCsr->iPageno.
155613 */
155614 static void statSizeAndOffset(StatCursor *pCsr){
155615   StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
155616   Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
155617   Pager *pPager = sqlite3BtreePager(pBt);
155618   sqlite3_file *fd;
155619   sqlite3_int64 x[2];
155620 
155621   /* The default page size and offset */
155622   pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
155623   pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
155624 
155625   /* If connected to a ZIPVFS backend, override the page size and
155626   ** offset with actual values obtained from ZIPVFS.
155627   */
155628   fd = sqlite3PagerFile(pPager);
155629   x[0] = pCsr->iPageno;
155630   if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
155631     pCsr->iOffset = x[0];
155632     pCsr->szPage = (int)x[1];
155633   }
155634 }
155635 
155636 /*
155637 ** Move a statvfs cursor to the next entry in the file.
155638 */
155639 static int statNext(sqlite3_vtab_cursor *pCursor){
155640   int rc;
155641   int nPayload;
155642   char *z;
155643   StatCursor *pCsr = (StatCursor *)pCursor;
155644   StatTable *pTab = (StatTable *)pCursor->pVtab;
155645   Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
155646   Pager *pPager = sqlite3BtreePager(pBt);
155647 
155648   sqlite3_free(pCsr->zPath);
155649   pCsr->zPath = 0;
155650 
155651 statNextRestart:
155652   if( pCsr->aPage[0].pPg==0 ){
155653     rc = sqlite3_step(pCsr->pStmt);
155654     if( rc==SQLITE_ROW ){
155655       int nPage;
155656       u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
155657       sqlite3PagerPagecount(pPager, &nPage);
155658       if( nPage==0 ){
155659         pCsr->isEof = 1;
155660         return sqlite3_reset(pCsr->pStmt);
155661       }
155662       rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg);
155663       pCsr->aPage[0].iPgno = iRoot;
155664       pCsr->aPage[0].iCell = 0;
155665       pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
155666       pCsr->iPage = 0;
155667       if( z==0 ) rc = SQLITE_NOMEM;
155668     }else{
155669       pCsr->isEof = 1;
155670       return sqlite3_reset(pCsr->pStmt);
155671     }
155672   }else{
155673 
155674     /* Page p itself has already been visited. */
155675     StatPage *p = &pCsr->aPage[pCsr->iPage];
155676 
155677     while( p->iCell<p->nCell ){
155678       StatCell *pCell = &p->aCell[p->iCell];
155679       if( pCell->iOvfl<pCell->nOvfl ){
155680         int nUsable;
155681         sqlite3BtreeEnter(pBt);
155682         nUsable = sqlite3BtreeGetPageSize(pBt) -
155683                         sqlite3BtreeGetReserveNoMutex(pBt);
155684         sqlite3BtreeLeave(pBt);
155685         pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
155686         pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
155687         pCsr->zPagetype = "overflow";
155688         pCsr->nCell = 0;
155689         pCsr->nMxPayload = 0;
155690         pCsr->zPath = z = sqlite3_mprintf(
155691             "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
155692         );
155693         if( pCell->iOvfl<pCell->nOvfl-1 ){
155694           pCsr->nUnused = 0;
155695           pCsr->nPayload = nUsable - 4;
155696         }else{
155697           pCsr->nPayload = pCell->nLastOvfl;
155698           pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
155699         }
155700         pCell->iOvfl++;
155701         statSizeAndOffset(pCsr);
155702         return z==0 ? SQLITE_NOMEM : SQLITE_OK;
155703       }
155704       if( p->iRightChildPg ) break;
155705       p->iCell++;
155706     }
155707 
155708     if( !p->iRightChildPg || p->iCell>p->nCell ){
155709       statClearPage(p);
155710       if( pCsr->iPage==0 ) return statNext(pCursor);
155711       pCsr->iPage--;
155712       goto statNextRestart; /* Tail recursion */
155713     }
155714     pCsr->iPage++;
155715     assert( p==&pCsr->aPage[pCsr->iPage-1] );
155716 
155717     if( p->iCell==p->nCell ){
155718       p[1].iPgno = p->iRightChildPg;
155719     }else{
155720       p[1].iPgno = p->aCell[p->iCell].iChildPg;
155721     }
155722     rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg);
155723     p[1].iCell = 0;
155724     p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
155725     p->iCell++;
155726     if( z==0 ) rc = SQLITE_NOMEM;
155727   }
155728 
155729 
155730   /* Populate the StatCursor fields with the values to be returned
155731   ** by the xColumn() and xRowid() methods.
155732   */
155733   if( rc==SQLITE_OK ){
155734     int i;
155735     StatPage *p = &pCsr->aPage[pCsr->iPage];
155736     pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
155737     pCsr->iPageno = p->iPgno;
155738 
155739     rc = statDecodePage(pBt, p);
155740     if( rc==SQLITE_OK ){
155741       statSizeAndOffset(pCsr);
155742 
155743       switch( p->flags ){
155744         case 0x05:             /* table internal */
155745         case 0x02:             /* index internal */
155746           pCsr->zPagetype = "internal";
155747           break;
155748         case 0x0D:             /* table leaf */
155749         case 0x0A:             /* index leaf */
155750           pCsr->zPagetype = "leaf";
155751           break;
155752         default:
155753           pCsr->zPagetype = "corrupted";
155754           break;
155755       }
155756       pCsr->nCell = p->nCell;
155757       pCsr->nUnused = p->nUnused;
155758       pCsr->nMxPayload = p->nMxPayload;
155759       pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
155760       if( z==0 ) rc = SQLITE_NOMEM;
155761       nPayload = 0;
155762       for(i=0; i<p->nCell; i++){
155763         nPayload += p->aCell[i].nLocal;
155764       }
155765       pCsr->nPayload = nPayload;
155766     }
155767   }
155768 
155769   return rc;
155770 }
155771 
155772 static int statEof(sqlite3_vtab_cursor *pCursor){
155773   StatCursor *pCsr = (StatCursor *)pCursor;
155774   return pCsr->isEof;
155775 }
155776 
155777 static int statFilter(
155778   sqlite3_vtab_cursor *pCursor,
155779   int idxNum, const char *idxStr,
155780   int argc, sqlite3_value **argv
155781 ){
155782   StatCursor *pCsr = (StatCursor *)pCursor;
155783 
155784   statResetCsr(pCsr);
155785   return statNext(pCursor);
155786 }
155787 
155788 static int statColumn(
155789   sqlite3_vtab_cursor *pCursor,
155790   sqlite3_context *ctx,
155791   int i
155792 ){
155793   StatCursor *pCsr = (StatCursor *)pCursor;
155794   switch( i ){
155795     case 0:            /* name */
155796       sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
155797       break;
155798     case 1:            /* path */
155799       sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
155800       break;
155801     case 2:            /* pageno */
155802       sqlite3_result_int64(ctx, pCsr->iPageno);
155803       break;
155804     case 3:            /* pagetype */
155805       sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
155806       break;
155807     case 4:            /* ncell */
155808       sqlite3_result_int(ctx, pCsr->nCell);
155809       break;
155810     case 5:            /* payload */
155811       sqlite3_result_int(ctx, pCsr->nPayload);
155812       break;
155813     case 6:            /* unused */
155814       sqlite3_result_int(ctx, pCsr->nUnused);
155815       break;
155816     case 7:            /* mx_payload */
155817       sqlite3_result_int(ctx, pCsr->nMxPayload);
155818       break;
155819     case 8:            /* pgoffset */
155820       sqlite3_result_int64(ctx, pCsr->iOffset);
155821       break;
155822     default:           /* pgsize */
155823       assert( i==9 );
155824       sqlite3_result_int(ctx, pCsr->szPage);
155825       break;
155826   }
155827   return SQLITE_OK;
155828 }
155829 
155830 static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
155831   StatCursor *pCsr = (StatCursor *)pCursor;
155832   *pRowid = pCsr->iPageno;
155833   return SQLITE_OK;
155834 }
155835 
155836 /*
155837 ** Invoke this routine to register the "dbstat" virtual table module
155838 */
155839 SQLITE_API int SQLITE_STDCALL sqlite3_dbstat_register(sqlite3 *db){
155840   static sqlite3_module dbstat_module = {
155841     0,                            /* iVersion */
155842     statConnect,                  /* xCreate */
155843     statConnect,                  /* xConnect */
155844     statBestIndex,                /* xBestIndex */
155845     statDisconnect,               /* xDisconnect */
155846     statDisconnect,               /* xDestroy */
155847     statOpen,                     /* xOpen - open a cursor */
155848     statClose,                    /* xClose - close a cursor */
155849     statFilter,                   /* xFilter - configure scan constraints */
155850     statNext,                     /* xNext - advance a cursor */
155851     statEof,                      /* xEof - check for end of scan */
155852     statColumn,                   /* xColumn - read data */
155853     statRowid,                    /* xRowid - read data */
155854     0,                            /* xUpdate */
155855     0,                            /* xBegin */
155856     0,                            /* xSync */
155857     0,                            /* xCommit */
155858     0,                            /* xRollback */
155859     0,                            /* xFindMethod */
155860     0,                            /* xRename */
155861   };
155862   return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
155863 }
155864 #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
155865 
155866 /************** End of dbstat.c **********************************************/
155867